Should 'if' statement always have an 'else' clause?

Viewed 104765

This may be a religious argument, but it has been debated ad-nauseum here at my work whether all IF statements should include an ELSE clause - even if the ELSE clause only contains a comment stating that it was 'intentionally left blank'.

I have heard arguments for both sides: The 'For' camp - ensures that the codes has actually addressed whether the condition requires an ELSE clause The 'Against' camp - code is harder to read, adds too much noise

I am interested in any other points of view as I have to resolve this debate with an answer that would satisfy both parties.

Thank you for your help.

BTW: I did search StackOverflow for an answer to this and was unable to find one. If there is one, just include a link to it and close. Thanks.

18 Answers

I tend to use "early if" statements as means of reducing the level of nested braces (or indentation in Python) like so:

if (inParam == null) {
  return;
}

if (inParam.Value < 0) {
  throw new ArgumentException(...,...);
}
// Else ... from here on my if statements are simpler since I got here.

Of course, .Net 4.0 now has code contracts, which is great! But, most languages do not have that just yet, so "early ifs" (for the lack of better term) are great precisely because they eliminate a number of else clauses and nested ifs. I do not think it is beneficial to have an else clause in high-level languages ... heck, even in assembly! The idea is: if you checked and did not jump, then the condition was false and we can carry on. Makes logical sense to me ...

EDIT: Check out this article as well to see why else clauses are not of much help: http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html

Having an "else" with just an empty line of a code comment can usually mean the developer thought-through the condition and has a better idea of what execution path is actually taken at a given time. All recent compilers will remove the "else" and the comment, so you are not slowing software execution.

Unless I am reading the other responses incorrectly, it looks like most folks are objecting to the time it takes to declare their thoughts in the code and would rather just do it.

if (thereIsSomeThingToDoInTheElse)
{
    putAnElseClause();
}
else
{
    // intentionally left blank
}

Haskell's if is always ternary. So else is mandatory.

There are situations where using an optional syntax element when not required can improve readability or prevent future errors. A typical case are the brackets around one-sentence conditionals:

Doing

if(foo){
    bar
}

instead of

if(foo)
    bar

could eventually prevent

if(foo)
    bar
    dot

I can't really think of any language I know where omitting an unnecessary else can lead to potential errors :-?

Related