A return to Good Code

 By Jasone Tee

TheServerSide.com

 

 

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) { 
   flag=true;
 }  
 else {
   flag=false;
 }
 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.

02 Mar 2011

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章