Tag Archives: java

Separate returns in an if statement?


if (true) {
   return this;
   }
else {
    return that;
    }

I wrinkle my nose. I don’t know if it’s just structured programming dogma, or if there are good reasons.

I’m wondering about readability and the shared-codebase ethic, and also about bug prevention. It just doesn’t look clean to me.

What do you say? One return, or several?

GeePaw sez…

Neither “never do this” nor “never forget to do this” actually work as rules. Since you’re skeptical of the multiple-returns, I’ll start with an example of bad code directly resulting from single-exit strategies.

public void SingleReturns(arg,arg2,arg3)
{
	if(arg is okay) {
		if( arg2 is okay )
		{
			if( arg3 does not make the world blow up )
			{
				do some work
				write a (calculated) message about success
			}
			else
			{
				construct stupid message and print it
			}
		else
		{
			construct another stupid message and print *that*
		}
	else
	{
		for crying out loud, all this logging is killing me
	}
}
 

public void MultiReturns(arg,arg2,arg3)
{
	if(ArgIsHosed()) return;
	if(Arg2IsScrewedUp()) return;
	if(arg3IsDegenerateOrAtLeastTypedByADegenerate()) return;
	do some work
	write a (calculated) message
}

Notice I’ve combined to different patterns two make this solution:

  1. I’ve reversed the logic of the conditionals. In Eclipse, that’s a mechanical refactoring.
  2. I’ve put the code that handles failures inside the extracted conditionals.

I will say, tho, that I don’t have good names. To me it feels like the second one is missing some word or words that make the idiom clear. I’ve played around with names like “ArgOneReturn”, or whatnot. Nothing, yet, satisfies. The pattern of moving all the failure-handling to the conditional function, I call Extract-Conditional-And-Branch.