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.
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.
One of the few possible situations where this might be a good idea is where you have several nested
if
statements, but fewerelse
clauses. The language will specify whichif
theelse
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.This is no more true than requiring a catch clause in every method ensures that all possible exceptions has been properly handled.
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
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
instead of
could eventually prevent
I can't really think of any language I know where omitting an unnecessary else can lead to potential errors :-?
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.