I am a big fan of single return point functions.  Instead of:

public int dilbert() {
  if (…) {
    …
    return 1;
  }
  else {
    …
    return 0;
  }

I prefer:

public int dilbert() {
  int result = 0;
  if (…) {
    result = 1;
  }
  return result;
}

There are several advantages to this approach:

  • Clearer flow of execution.  You know the final return result will be run, no matter what.
     
  • Easier to debug.  I can set a breakpoint on the return and inspect the returned value.

However, I started questioning this habit in a particular case:  when the failure in a condition should cause the method to abort right away.  Compare:

public void dogbert1(Boss b) {
  if (b != null) {
    …
  } 
}

with:

public void dogbert2(Boss b) {
  if (b == null) return;
  …
}

Until recently, I used to favor the first form because, again, it made the execution flow more obvious.  If you make the second method more complicated and you start peppering returns a bit everywhere, it can become quite difficult to read.

The problem is that dogbert1() can also be difficult to read because "it leaves you dangling".

When you read the first if in dogbert1(), you make a mental note that there might be an else case further down and you will keep it in the back of your mind as you read the body of the if.  When you start adding several nested ifs, the mental state you need to store to understand the method is increasing, and if these else clauses are going to be empty, I would argue that the "early abort idiom" is probably a better choice.

Having said that, I believe there is a happy medium between these two conventions, so I would recommend using the early abort idiom only when…  well, it really is about an early abort.  If your abort logic has to end up buried down a few nested levels and that it’s only one of many other possible cases, you might want to refactor your code so that the abort logic will be featured prominently at the top of your method, as shown above.

What do you think?  In the code you read on a daily basis, what form is more prevalent?