• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Single return vs many?

 
Bartender
Posts: 1868
81
Android IntelliJ IDE MySQL Database Chrome Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Which do you think is better, having many return statements or having a single return statement?
Here is a sample with both:

I prefer one single return statement (sampleIntMethodB), but I can work with either.
What exactly is the convention or consensus on this?
 
Marshal
Posts: 75724
354
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There isn't a consensus. I prefer one return statement too, which you can write like this:-
 
Ranch Foreman
Posts: 264
6
Eclipse IDE MySQL Database Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The code won't compile either way if your method does not end with a return statement, therefore I would say the one return statement is the best solution since it is neater and you need the last one either way but not all the others.

However in only one situation so far do I prefer multiple return statements and that is if I am using if else statement where is the condition is met I am ready to exit and do not require the computer to go over the rest of my code. For example:

 
Marshal
Posts: 27214
87
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There's lots of people who insist that a single return statement is the Only True Way to code. And then there are people who will accept Yosuf's suggestion about allowing returns for simple reasons near the beginning of the method but not otherwise. If you look around for published examples of equals() methods in Java you'll find that kind of usage a lot. (Try rewriting them with only a single return statement and then compare your results against the original version for readability.) My habit is a lot like what Yosuf said, and after that I rarely find myself in a situation where I might have to argue with somebody about how many return statements I chose to use.
 
Pete Letkeman
Bartender
Posts: 1868
81
Android IntelliJ IDE MySQL Database Chrome Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I ask because I'm currently working my way through a few different Java tutorials and the various authors are some times in favor of the many return statements.
So I thought that if this was indeed the recommended way to do things (in Java) then I should continue with that practice.

In the end then I'm glad that I do not have to change to the many return statements practice.
 
Paul Clapham
Marshal
Posts: 27214
87
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I know it's easy to make an unreadable method by having return statements all over the place. And unreadable methods should be rewritten to make them readable. But I don't think that the "Only One Return Statement" rule automatically produces readable code -- bad programmers can produce bad code no matter what rules they are following.

On the other hand if you're running an organization which is full of bad programmers, then having them follow rules which reduce the quantity of unreadable code is a good strategy. (Although you might question whether having rooms full of bad programmers is a good strategy or not.)

But me, I'm not running that organization. Nor am I employed by it. So I'm not going to make myself follow excessively rigid rules.
 
Bartender
Posts: 2907
150
Google Web Toolkit Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I prefer multiple returns especially at the beginning of a method for validations.

vs
 
Saloon Keeper
Posts: 13891
314
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think the whole single return business is bollocks. The rule was intended to make escape analysis for humans easier (which it doesn't), or resulted from a misguided feeling that returns, breaks and continues were similar to gotos.

Early returns actually lessen the burden of execution path analysis, because you can eliminate cases you have to consider from your reasoning. This is one of the reasons why many people make an exception to the rule for simple cases at the start of the method. Guess what? The rest of the method isn't any different. If I can eliminate cases I have to consider within a loop or switch using a return statement, I will gladly do so. The switch statement that Pete showed is a great example. You had to introduce an extra variable to make it work. Extra variables aren't just extra memory for the virtual machine, it's also an indication that the programmer needs to remember more. Besides, it's not a clear indication that it's really going to be the real return value of the method. Are you still going to do processing on the variable after the switch? I have to keep that in mind while I'm analysing the switch statement. Using a simple return tells me: no, we're really done with this case.

Keywords like return, break and continue also help eliminate the dreadful arrow anti-pattern. This is very cut and dry: lower nested scope levels == simpler code.

I can explain why these keywords make the code simpler for me. So far I've never really heard a good argument why the single return convention does so as well. Programmers are just drilled to follow this useless convention.
 
Rancher
Posts: 4801
50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The one reason behind "single return" that I can remember was being shown a method with a single return at the end and being told that if it had multiple returns it was harder to follow where it exited.
The method in question was over 100 lines long, and stupidly complex.

I suggested that maybe that was the actual problem...
 
Campbell Ritchie
Marshal
Posts: 75724
354
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

salvin francis wrote:. . .. . .

Are you sure there aren't some !s missing there?
 
Sheriff
Posts: 16964
286
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm with the nonconformists on this one. The escape hatches at the top of a method are called guard clauses and, yes, they can help mitigate or eliminate arrow code. Stephan said most of what I wanted to say already. And I agree with what Dave suggested, that stupid long methods are usually the real problem with multiple points of exit from a method. With small methods and properly formatted code, return statements are much harder to miss.
 
Junilu Lacar
Sheriff
Posts: 16964
286
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I know it was just an example but in some cases like this one, the control structure can be replaced with a formula or turned into a single method call by using an abstract data type like a List or Map as a lookup table. That way, the multiple exit point issue becomes moot.
 
Sheriff
Posts: 67637
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The original intent of the "single return" dogma of the Structure Programming wars was to ensure clarity in the code.

So I follow that intent and use as many return statements as achieves clarity. It may be one, it may be many.

The important part is to use them to achieve clarity, not adhere to any dogma.
 
salvin francis
Bartender
Posts: 2907
150
Google Web Toolkit Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:. . . Are you sure there aren't some !s missing there?


You got me! I intended to write if(validation1Fails) ...
 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This comes from the time of structured programming.
https://en.wikipedia.org/wiki/Structured_programming

Before the structured programming paradigm people programmed disastrously, the control of the program flows arbitrarily from anywhere in the program to arbitrarily anywhere else. This caused countless problems and made it very difficult to debug the programs.

As the paradigm of structured programming emerged, the complexity of the programmes was drastically reduced. It defined the control structures (IF, WHILE, FOR, etc.) and defined the concept that each structure should have ONLY ONE entry and ONLY ONE exit. The aim of this was to simplify things and lower the complexity (this is the holy grail).

Early on, Donald E. Knuth demonstrated that there were cases where the rule (that each structure had a single entry and a single exit) made things more complicated.

Generally, the "only one entry and only one exit" rule is a good one, and should be followed, but there are cases where a program is much more complicated when that rule is followed. My advice is. If you're a novice, follow the rules at all times, you're learning to program. If you are more advanced you can break the rule, but only when things get extremely complicated if you follows the rule and simplifies significatively if you breaks the rule.

Why the rule?

Because when you're going to review the code, or debug it, understanding its logic is much easier when you have only one entry and only one exit. The entry is at the beginning, and the exit is at the end. If you have a lot of places to go outside the structure, things can get very complicated for analysis and understanding of the code. So you must know what you're doing before you break the rule, a beginner doesn't know.

In the example you shows there are not advantages on using multiple returns, but the opposite is true, you're slightly complicating the understanding of the program. If you repeat this behavior several times, you are severely complicating the program's readinness.
 
Junilu Lacar
Sheriff
Posts: 16964
286
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

German Martinez wrote:
In the example you shows there are not advantages on using multiple returns, but the opposite is true, you're slightly complicating the understanding of the program. If you repeat this behavior several times, you are severely complicating the program's readinness.


Assuming you are referring to the OP's original examples, I would agree that they are not the best examples to use as the basis for a good Single vs. Multiple return statements debate/discussion. I wouldn't choose any of OP's proffered options, in fact, I would probably prefer Campbell's single return statement that uses cascaded ternary operators.  The one small con to that approach is that code formatting has to be preserved to maintain readability.  This makes it necessary to use an IDE-specific annotation to disable autoformatting, if it can be guaranteed that all team members will use the same IDE or formatting tool.
 
Campbell Ritchie
Marshal
Posts: 75724
354
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
We have a copy of the book which introduced the term structured programming in our office.
The idea is that every program can be assembled from sequence iteration and selection, which was shown by Böhm and Jacopini in 1968. Along with the letter from Dijkstra in 1966 entitled “Goto considered harmful,” it set the scene for the development of structured programming. Removing goto or similar means that each control structure has a single exit point; if that creates complicated code, there are several possible responses:-
  • 1: The code is complicated because the function is trying to do too much all in one place. (The term method hadn't been introduced yet in 1968.)
  • 2: If I breach the rules of structured programming, the code will be no harder to read with multiple return.
  • 3: If you learn structured programming, you will have no difficulty moving to an idiom which permits multiple returns; it would be more difficult to move the other way.
  • I am not sure that structured programming actually made software development more successful or led to more reliable products. Maybe my suggestion with ?: which I made sure to indent correctly (as Junilu mentions) is a way of compressing multiple returns into one statement. Maybe the structure of multiple return is like this:-and maybe it is like this:-I think Stephan is arguing for the latter.
     
    There are 10 kinds of people in this world. Those that understand binary get this tiny ad:
    Free, earth friendly heat - from the CodeRanch trailboss
    https://www.kickstarter.com/projects/paulwheaton/free-heat
    reply
      Bookmark Topic Watch Topic
    • New Topic