Sunday, July 20, 2014

Regarding if/else versus if/implicit else

I have my own particular C# coding style which for the most part is fully in-line with the most popular style guidelines, but there's one thing I do that I've received criticism for:

Let's suppose you have an if statement with a return statement in the block:

if (someCondition)
{
    return x;
}

return y;

There's no need to write an else block, because it's implied that the only time return y will be executed is if the if condition is false.  Nevertheless, I prefer writing:

if (someCondition)
{
    return x;
}
else
{
    return y;
}

Why?  Because it's more resistant to change.  What if I (or someone else) suddenly modifies the true block, eliminating the return statement?  In the first code snippet, this may result in a bug.  The second one, however, is protected from this.