Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

At work I stumbled uppon a method. It made a query, and returned a String based on the result of the query, such as de ID of a customer. If the query didn't return a single customer, it'd return a null. Otherwise, it'd return a String with the ID's of them. It looked like this:

String error = getOwners();
if (error != null) {
    throw new Exception("Can't delete, the flat is owned by: " + error);

Ignoring the fact that getCustomers() returns a null when it should instead return an empty String, two things are happening here. It checks if the flat is owned by someone, and then returns them.
I think a more readable logic would be to do this:

if (isOwned) {
    throw new Exception("Can't delete, the flat is owned by: " + getOwners());

The problem is that the first way does with one query what I do with two queries to the database.
What would be a good solution involving good design and efficiency for this?

share|improve this question
A good rule of thumb is to access the database the least number of times necessary. – Bernard Jun 1 '12 at 13:44
up vote 7 down vote accepted

Can you change the getOwners method? If so, I would change getOwners to return an ArrayList. That way you can you just check to see if the list is empty and if not just use the list. Like so.

public ArrayList<int> getOwners() {
    ArrayList<int> list = ArrayList<int>();
    // Magic...
    return list;

// Later...

ArrayList<int> owners = getOwners();
if (!owners.isEmpty()) {
    throw new Exception("Can't delete, the flat is owned by: " + owners.toString());

I think the above approach is much clearer than any of the other ways.

share|improve this answer
Indeed, sounds like the best way. Thanks! – Uri Jun 1 '12 at 13:55

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.