3

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?

  • A good rule of thumb is to access the database the least number of times necessary. – Bernard Jun 1 '12 at 13:44
7

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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