Question

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?

No correct solution

Licensed under: CC-BY-SA with attribution
scroll top