780
337
I often talk to programmers who say "Don't put multiple return statements in the same method." When I ask them to tell me the reasons why, all I get is "The coding standard says so." or "It's confusing." When they show me solutions with a single return statement, the code looks uglier to me. For example:
if (condition)
return 42;
else
return 97;
"This is ugly, you have to use a local variable!"
int result;
if (condition)
result = 42;
else
result = 97;
return result;
How does this 50% code bloat make the program any easier to understand? Personally, I find it harder, because the state space has just increased by another variable that could easily have been prevented.
Of course, normally I would just write:
return (condition) ? 42 : 97;
But many programmers eschew the conditional operator and prefer the long form.
Where did this notion of "one return only" come from? Is there a historical reason why this convention came about?

this question is discussed at meta – gnat – 2016-02-17T07:13:49.527
1
This is somewhat connected to Guard Clause refactoring. http://stackoverflow.com/a/8493256/679340 Guard Clause will add returns to the beginning of your methods. And it makes code a lot cleaner in my opinion.
– Piotr Perak – 2013-12-14T09:14:43.3371and where is the discussion discussed? – Liviu – 2016-05-13T08:58:00.833
It came from the notion of structured programming. Some may argue that having just one return allows you to easily modify the code to do something just before returning or to easily debug. – martinkunev – 2016-05-14T11:39:10.153
i think the example is a simple enough case where i wouldn't have a strong opinion one way or the other. the single-entry-single-exit ideal is more to guide us away from crazy situations like 15 return statements and two more branches that don't return at all! – mendota – 2016-08-18T19:15:38.547