I love returns 2
Some people like to have only one return statement in their methods.
This makes no sense to me. I don’t get the “one exit flow” argument. This is like saying you can’t use break or continue inside a loop, or that you can’t have fallthrough in a switch statement. I can understand why you’d want to document the use of special behaviour, but I can’t see why I should cut myself off from a feature of the language. A return is not, and never has been, a goto.
I’ve grown into the use of return statements. Originally I didn’t use them at all: I’d go through hoops to make everything work.
public void doStuff(String pName)
{
if (pName != null)
{
Object obj = lookupName(pName);
if (obj != null)
{
obj.doThingy();
} else
{
if (isLoggingError())
{
logError("null obj for pName: " + pName);
}
}
} else
{
if (isLoggingError())
{
logError("null pName: " + pName);
}
}
}
Now I don’t bother with nested if statements. I do this instead:
public void doStuff(String pName)
{
if (pName == null)
{
if (isLoggingError())
{
logError("null pName: " + pName);
}
return;
}
Object obj = lookupName(pName);
if (obj == null)
{
if (isLoggingError())
{
logError("null obj for pName: " + pName);
}
return;
}
obj.doThingy();
}
I proceed down the main code path. If there’s something I can’t do, I log an error and get out of there. My logic is simpler – I don’t have to nest anything, and I can reuse the same pattern over and over. Complicated condition to test? Extract it to a method and test against the return.
The same thing works in loops as well:
for (int i = 0; i < pArray.length; i++)
{
String element = pArray[i];
if (SOME_CONSTANT.equals(element))
{
return element;
}
}
return null;
Sure, I could do this:
String element = null;
for (...)
{
element = pArray[i];
if (SOME_CONSTANT.equals(element))
{
break;
}
}
return element;
But it’s that much cleaner to me to declare elements where they are used, especially if they need not be used outside of that scope.
The basic idea is that returns are an easy way to remove nested conditionals. Anywhere you can use an assert, you can use a return. Anywhere you throw an exception, you are using a return. So know them. Use them. And love them.
I hate exceptions, I nver know if it’s an error or a Use Case
Glad to see that someone else didn’t go to the “one exit flow” school. I do this all the time since, at least to me, it’s easier to read. However, it sometimes is harder to debug since you may not get to your debug statement in the method.