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

Coding Style

Coding Style Problem Overview


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.

Coding Style Solutions


Solution 1 - Coding Style

Seems like useless typing to me... and a possible cause for confusion. If you don't need it, don't put it!

Solution 2 - Coding Style

No. If you don't need to run any code on the else side, you don't need an else clause.

Solution 3 - Coding Style

It is clear by the responses here that no one feels an unused else is needed. I have never heard nor read of such a thing. The more important issue before you is dealing with co-workers/developers who somehow believe adamantly that this is how If Then is to be used.

It sounds like you are not the senior person in this scenario so you cannot simply decree it to be so. I suggest asking the "empty else" parties to show where such a process is suggested in a book (blogs don't count) about development. Better yet, in 3 books about development. I have read my share of programming books across programming languages since 1982 and I have never seen such a suggestion.

This way you are not telling them that they are wrong which they could take personally. Instead you are willing to accept such a position but would like to see some documentation. The onus is on them to find the proof. Either they find it or they are left to argue that every programming book ever written is wrong while only they are right.

Good luck.

Solution 4 - Coding Style

The golden rule: put it in if it makes your code clearer and easier to understand, and leave it out otherwise. An experienced programmer will be able to make these judgements on a case-by-case basis.

Solution 5 - Coding Style

Are you talking about Algol-derived languages?

In Lisp, I'd say yes: every IF should have an else-clause. Otherwise, you should be using WHEN.

Solution 6 - Coding Style

As you say, this may be a question of style, but I would not dream of putting in empty else-blocks in my code just because "every if-block should have one". In my opinion, it adds nothing else than some more characters in the code and one more point (of very little value) to spend time on during code reviews.

Solution 7 - Coding Style

Requiring an else stinks. Use it when needed. All programmers understand the construct and the implication of a missing else. It's like a pointless comment that echoes the code. It's plain daft IMO.

Solution 8 - Coding Style

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

Solution 9 - Coding Style

No. Guard conditions are a great example. You could nest the rest of the method logic in else clauses but it could get ugly really quickly.

Solution 10 - Coding Style

> "ensures that the codes has actually > addressed whether the condition > requires an ELSE clause"

This is no more true than requiring a catch clause in every method ensures that all possible exceptions has been properly handled.

Solution 11 - Coding Style

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.

Solution 12 - Coding Style

SQL Server 2000, 2005 at least.

IF 1 = 1
BEGIN
    PRINT 'doing something productive'
END
ELSE
BEGIN
    --Just sitting here
END


Msg 102, Level 15, State 1, Line 8
Incorrect syntax near 'END'.

You have to have a meaningful statement, which means a dummy assign or return data to client. I suppose I could use WAITFOR DELAY...

Solution 13 - Coding Style

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

Solution 14 - Coding Style

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

Solution 15 - Coding Style

If your code is complex enough that this becomes an issue, you should probably be rethinking your approach to the problem. Break what you're doing down into smaller simpler functions where it should be unbelievably obvious what the if statements are doing.

If you can't break it down into smaller functions, or you find yourself nesting more than one if statement inside another, Using if statements for your conditional logic are probably not a good fit. Consider switches, lookup tables (if the only difference between your conditions is the value of some constant), or decision tables instead.

If you've already done all this, then you are quibbling over something so unbelievably trivial it's hardly worth your time to argue it.

Solution 16 - Coding Style

One of the few possible situations where this might be a good idea is where you have several nested if statements, but fewer else clauses. The language will specify which if the else matches, but this may not always be clear to the reader. Of course, where you put content in curly brackets, nesting will be obvious, so there's no ambiguity. This make this a bit of an artificial case, but still possibly worth mentioning. Also, if your code is this complicated, there's probably a clearer way of writing it.

Solution 17 - Coding Style

there are a lot of "words" telling you the way to programming such as DRY

in this case i'd use YAGNI.. you aint gonna need it..

so following this you shouldn't write the else.

anyhow in my opinion it makes it harder to read and understand the code.. the more you write the harder to understand the code is

edit: here are the links you requested: http://en.wikipedia.org/wiki/YAGNI http://en.wikipedia.org/wiki/Don%27t_repeat_yourself

Solution 18 - Coding Style

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 :-?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJackView Question on Stackoverflow
Solution 1 - Coding StylejldupontView Answer on Stackoverflow
Solution 2 - Coding StyleRobert HarveyView Answer on Stackoverflow
Solution 3 - Coding StyledredfulView Answer on Stackoverflow
Solution 4 - Coding StyleTimView Answer on Stackoverflow
Solution 5 - Coding StyleKenView Answer on Stackoverflow
Solution 6 - Coding StyleFredrik MörkView Answer on Stackoverflow
Solution 7 - Coding StylespenderView Answer on Stackoverflow
Solution 8 - Coding StyleHamish GrubijanView Answer on Stackoverflow
Solution 9 - Coding StylepeacedogView Answer on Stackoverflow
Solution 10 - Coding StyleMichael PetrottaView Answer on Stackoverflow
Solution 11 - Coding StyleSnowyView Answer on Stackoverflow
Solution 12 - Coding StylegbnView Answer on Stackoverflow
Solution 13 - Coding StyleJoelFanView Answer on Stackoverflow
Solution 14 - Coding StyleHaiView Answer on Stackoverflow
Solution 15 - Coding StyleBretonView Answer on Stackoverflow
Solution 16 - Coding StyleTimView Answer on Stackoverflow
Solution 17 - Coding StyleDimitriView Answer on Stackoverflow
Solution 18 - Coding StyleÁlvaro GonzálezView Answer on Stackoverflow