Only one return statement

original
2012/06/21 12:06
Reading number 212

Stop writing:

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

Every time I go deep into an open source project and see such code written by an expert and reviewed by experienced professionals, I am surprised that no one has stopped the developer from randomly placing return statements in this method.

Please tell me, is it difficult to write the code as follows?

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

This is the basic knowledge of Java. In fact, this is not only the basic knowledge of Java, but also the elementary level knowledge of Java. If your method returns a value, you should declare it as a variable at the beginning of the method. Then do some operations to give the correct meaning to this variable. Then, on your last line, return this variable to the caller. This is not just for writing good code, it is a civilized performance.

Have you ever tried to modify some program code with return statements everywhere in the method? No way to start. In fact, to maintain such code, the first thing you need to do is to reorganize its structure so that there are no more return statements in it. Only in this way can we do things well. No method can not be written in the form of a single, easy to find return statement with only one at the end.

Indeed, bad programmers always have ten thousand reasons to explain why they write such bad program code. "I just want to avoid a pile of redundant conditional statements when returning." Well, first of all, I tell you that the computer is damn fast when executing some conditional statements. Isn't it absurd to use a short circuit method to save one or two instruction operations of the CPU. In addition, if these so-called redundant conditional judgment statements are not used in the end, is it a useful signal that your "redundant" code may need to be rewritten, or maybe you can reconstruct them into another method so that they are not redundant?

The point is that there is no excuse for writing bad code or being a lazy programmer, especially when writing good code is not so difficult. Don't write methods with hundreds or thousands of return statements. A method in Java can only return one value. Accordingly, a method should have one and only one return statement.

Link to the original English text of this article: A return to Good Code

Only one return statement http://justjavac.com/java/2012/05/18/a-return-to-good-code.html

Expand to read the full text
Loading
Click to join the discussion 🔥 (2) Post and join the discussion 🔥
Reward
two comment
zero Collection
zero fabulous
 Back to top
Top