Archive for the ‘Best practices’ Category

Coding best practices: thinking about it

August 15, 2006

Today I have joined a discussion that emerged on our development team: whether to use multiple return statements within the same method.

Well, back when I was a terrible newbie programmer using Clipper as the main development language, someone convinced me that every function (that was the name for a procedural equivalent of today’s object’s methods) needed one unique return point. I stickied to it but never questioned myself ever again if this is really a good thing to do. Nowadays I got myself doing just the opposite: using multiple return points and when I analyzed it, I found that really better. I’ll explain.

Imagine the following method that searches for a particular object within an ArrayList:

private boolean userExists(String name) {
  boolean found = false;
  for (User u : this.getAllUsers()) {
    if (u != null && name.equals(u.getName())) {
      found = true;
      break;
    }
  }
  return found;
} 

Doesn’t this method seems a lot cleaner and easier to understand than:

private boolean userExists(String name) {
  for (User u : this.getAllUsers()) {
    if (u != null && name.equals(u.getName())) {
      return true;
    }
  }
  return false;
} 

There are other cases where I can see the code begging for an immediate return 🙂 like:

private void loadUsers() {
  if (usersLoaded) {
    return;
  }

  // do all the lengthy user loading...
  (...)
}

In my opinion, the early return when the users are already loaded are easier to interpret and easy to review by another coder than:

private void loadUsers() {
  if (!usersLoaded) {
    // do all the lengthy user loading...
    (...)
  }
  return;
}

I really don’t think it’s a major problem and using one or the other is pretty acceptable but I’d like to hear from you what you think about it so please leave a comment about it if you can. Thanks.

Update: A friend of mine just e-mailed me an article that addresses the same issue.