A return to Good Code

Just one simple suggestion: one return statement per method, and it's always the method's last line.

Stop doing this:

public boolean foo() {
 if (true) {
   return true;  
 }  else {  
 return false;  

It always amazes me when I dig into an open source project, and I see code written by supposed experts, and reviewed by seasoned professionals, and nobody slaps the wrists of the developer who shoves return statements right in the middle of a method.

Tell me, how hard is it to do this:

public boolean foo() {  
 boolean flag = true;  
 if (true) { 
 else {
 return flag;

This is Java 101. Actually, it's not even Java 101. It's grade school Java. If a method returns a value, you declare that value as a variable at the start of the method. Then you do things that will give that variable the appropriate meaning. And then, on your last line of code, you return that variable to the calling program. And doing so is more than just about writing good code. It's about being polite.

Have you ever tried to troubleshoot some code that has return statements thrown around all over the method? It's impossible. In fact, the first step in troubleshooting such a method is to rework the darn thing so that it doesn't have a bunch of return statements in it. And it can always be done. There is no method that can't be re-written to have just one, single, easy to identify return statement at the end of it.

Sure, bad programmers have a million different reasons as to why they must program poorly. "I just wanted to avoid a bunch of superfluous conditional statements that the code might have to go through later on." Well, first of all, computers are darned good at quickly evaluating a few conditional statements, so short-circuiting a method to avoid a clock cycle or two is simply ridiculous. And besides, if there's a bunch of superfluous conditional statements that end up getting bypassed, maybe that's a good indication that your 'superfluous' code should be rewritten, perhaps factored out into a different method that isn't superfluous?

The bottom line is that there's no excuse for writing bad code or being a lazy programmer, especially when writing good code isn't that much more difficult. Stop writing methods with a million return statements in them. A method in Java can only return one thing, and correspondingly, a method should have only one return statement in it.

This was last published in March 2011

Dig Deeper on Software development techniques and Agile methodologies

Start the conversation

Send me notifications when other members comment.


Please create a username to comment.