In an If-Else Statement for a method return, should an Else be explicitly stated if it can instead be implicitly followed?
Solution 1:
It's really a matter of style and what you (and those you work with) find to be clearer. In general, I personally find the structure:
if( a )
someResult = doSomething();
else if( b )
someResult = doSomethingElse();
else
someResult = doSomethingAnyways();
return someResult;
clearer than:
if( a )
return doSomething();
if( b )
return doSomethingElse();
return doSomethingAnyways();
Solution 2:
I tend to prefer something like this to returning hard values.
static bool SomeFunc(string arg)
{
bool result = false;
if (arg.Length < 10)
{
result = true;
}
else if (arg.StartsWith("foo"))
{
result = true;
}
if (!result && arg.EndsWith("foo"))
{
result = true;
}
return result;
}
Solution 3:
Whatever expresses your intention best and/or is most readable.
All the following options are perfectly valid:
if (condition1)
return true;
if (condition2)
return true;
if (condition3)
return true;
return false;
or
if (condition1)
return true;
else if (condition2)
return true;
else if (condition3)
return true;
else
return false;
or
return condition1
|| condition2
|| condition3;
I tend to use the first two options if the conditions are non-trivial or if there are multiple statements in the if
branch. The last option can give much more concise code if the conditions aren't to complex.
Solution 4:
Personally, I generally prefer to use the ELSE because I think it makes the intent clearer. If you write
if (sensorScan()==ENEMY)
return FIRE_PHASERS;
else
return SEND_GREETING;
it is clear to the reader that you are dealing with two branches coming out of one condition. Sure, in a trivial case like this where each branch is just one line, that might be obvious anyway. But in real life you often have a block of many lines of code inside the IF and many conditions, so it might well not be immediately obvious to a reader that every block ends with a return and the last block is therefore only executed when all previous conditions are false.
One exception I make to this practice is when the code is deeply nested. When it starts crawling too far across the page, I often find it more readable to remove the ELSEs.
Another excpetion is when one condition is an odd case and the other condition is the main-line. Yes, this is completely subjective, but in such cases I prefer to put the main-line outside the ELSE when possible.