Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should 'if' statement always have an 'else' clause? [closed]

Tags:

coding-style

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.

like image 643
Jack Avatar asked Nov 22 '09 23:11

Jack


People also ask

Should an if statement always have an else?

An if statement looks at any and every thing in the parentheses and if true, executes block of code that follows. If you require code to run only when the statement returns true (and do nothing else if false) then an else statement is not needed.

Does IF statement have to end with Else?

In the multiline syntax, the If statement must be the only statement on the first line. The ElseIf , Else , and End If statements can be preceded only by a line label. The If ... Then ... Else block must end with an End If statement.

Is it mandatory to use the else clause with every for while and if statement?

else clause is optional in if , for , while , and try block. Only one suite will be executed in the if statement. [either if-suite or elif-suite or else-suite). else clause is executed if there is no exception raised in the try block.


2 Answers

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

like image 133
jldupont Avatar answered Sep 20 '22 06:09

jldupont


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

like image 31
Robert Harvey Avatar answered Sep 20 '22 06:09

Robert Harvey