72

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 code 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.

starball
  • 20,030
  • 7
  • 43
  • 238
Jack
  • 3,444
  • 5
  • 34
  • 50
  • 1
    @Dave, it's not so much that developers are incapable of parsing the else; it's that most developers will not expect it to be there, so it's unnecessary noise. Kinda like getting cinnamon in your latte when you didn't ask for it. You can still drink it; it's just a less pleasant experience. – Robert Harvey Nov 22 '09 at 23:54
  • Would you recommend that switch statements always have a default case? – Bernard Chen Nov 23 '09 at 00:08
  • 1
    What language(s) are you working in? I've been doing this a while and as a generic "rule" the notion is just plain daft - which leads me to wonder if there are exceptional circumstances. – Murph Nov 23 '09 at 00:30
  • 6
    If this question is not some kind of joke, this is probably the most useless "generic rule" I've ever heard of; otherwise /* deliberately left blank */. – Erich Kitzmueller Nov 23 '09 at 13:53
  • See ISO/IEC TR 2477:2013 D.20.2, second paragraph. It's cheap and it prevents errors. – akalenuk Jul 09 '16 at 13:17
  • For a more complete discussion see: https://stackoverflow.com/questions/35053371/what-is-the-benefit-of-terminating-if-else-if-constructs-with-an-else-clause – jinawee Jul 16 '18 at 10:23

18 Answers18

145

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

jldupont
  • 93,734
  • 56
  • 203
  • 318
  • 5
    More typing = more chances for mistakes! – rashadb Feb 27 '15 at 05:19
  • 3
    Writing an `else` block for every conditional statement demonstrates that you have considered the "what if", even if the `else` block is empty. This is important for safety / reliability reasons in my opinion. – EM-Creations Oct 17 '19 at 09:09
  • without it alignment (and the meaning of the code) could be broken by accidental hitting of 'tab' key. – uuu777 Oct 23 '20 at 17:25
  • else could be a problem if missing. For example, try to make this work without an else >>> l = [22, 13, 45, 50, 98, 69, 43, 44, 1] >>> [x+1 if x >= 45 else x+5 for x in l] (good luck) – MMEL Jan 02 '22 at 07:12
49

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

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
34

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.

dredful
  • 4,378
  • 2
  • 35
  • 54
17

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.

Tim
  • 9,171
  • 33
  • 51
14

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.

Ken
  • 437
  • 7
  • 10
11

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.

Fredrik Mörk
  • 155,851
  • 29
  • 291
  • 343
8

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.

spender
  • 117,338
  • 33
  • 229
  • 351
8

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

Hamish Grubijan
  • 10,562
  • 23
  • 99
  • 147
6

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.

peacedog
  • 1,415
  • 20
  • 32
6

"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.

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
5

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.

Snowy
  • 5,942
  • 19
  • 65
  • 119
  • 1
    I have started liking the idea too. Not to put them everywhere blindly but it certainly makes the code more readable specially for slightly longer if blocks. Also, it helps express the intent clearly. – Rahul May 11 '12 at 04:58
4

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...

gbn
  • 422,506
  • 82
  • 585
  • 676
3
if (thereIsSomeThingToDoInTheElse)
{
    putAnElseClause();
}
else
{
    // intentionally left blank
}
JoelFan
  • 37,465
  • 35
  • 132
  • 205
3

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

Hai
  • 4,764
  • 8
  • 29
  • 26
2

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.

Breton
  • 15,401
  • 3
  • 59
  • 76
  • 1
    Trivial, yes. However when management is determined to force developers to standards such as these, even the trivial (and stunningly stupid) will become critical decisions. – Jack Nov 22 '09 at 23:56
  • 3
    The usual problem defending against pointy-haired bosses on technical issues like this is that engineers use logic and reason. Unfortunately, when one is battling superstition and authority, those will never succeed. Instead, use their point-of-view against them: ask, "What is the business case?" "How does going against established efficient industry-standard practice make our product cost less or be more valuable?" Having more code is more places for bugs, and slower engineer comprehension. – wallyk Nov 25 '09 at 04:42
2

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.

Tim
  • 9,171
  • 33
  • 51
2

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

Dimitri
  • 165
  • 8
2

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

Álvaro González
  • 142,137
  • 41
  • 261
  • 360