Here is a very simplified example. This isn't necessarily a language-specific question, and I ask that you ignore the many other ways the function can be written, and changes that can be made to it.. Color is of a unique type
string CanLeaveWithoutUmbrella()
{
if(sky.Color.Equals(Color.Blue))
{
return "Yes you can";
}
else
{
return "No you can't";
}
}
A lot of people I've met, ReSharper, and this guy (whose comment reminded me I've been looking to ask this for a while) would recommend refactoring the code to remove the else
block leaving this:
(I can't recall what the majority have said, I might not have asked this otherwise)
string CanLeaveWithoutUmbrella()
{
if(sky.Color.Equals(Color.Blue))
{
return "Yes you can";
}
return "No you can't";
}
Question: Is there an increase in complexity introduced by not including the else
block?
I'm under the impression the else
more directly states intent, by stating the fact that the code in both blocks is directly related.
Additionally I find that I can prevent subtle mistakes in logic, especially after modifications to code at a later date.
Take this variation of my simplified example (Ignoring the fact the or
operator since this is a purposely simplified example):
bool CanLeaveWithoutUmbrella()
{
if(sky.Color != Color.Blue)
{
return false;
}
return true;
}
Someone can now add a new if
block based on a condition after the first example without immediately correctly recognizing the first condition is placing a constraint on their own condition.
If an else
block were present, whoever added the new condition would be forced to go move the contents of the else
block (and if somehow they gloss over it heuristics will show the code is unreachable, which it does not in the case of one if
constraining another).
Of course there are other ways the specific example should be defined anyways, all of which prevent that situation, but it's just an example.
The length of the example I gave may skew the visual aspect of this, so assume that space taken up to the brackets is relatively insignificant to the rest of the method.
I forgot to mention a case in which I agree with the omission of an else block, and is when using an if
block to apply a constraint that must be logically satisfied for all following code, such as a null-check (or any other guards).