Should 'if' statement always have an '

2019-01-07 15:33发布

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条回答
霸刀☆藐视天下
2楼-- · 2019-01-07 16:10

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

查看更多
▲ chillily
3楼-- · 2019-01-07 16:11

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.

查看更多
劫难
4楼-- · 2019-01-07 16:13

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

查看更多
贪生不怕死
5楼-- · 2019-01-07 16:14

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

查看更多
等我变得足够好
6楼-- · 2019-01-07 16:14

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

查看更多
Anthone
7楼-- · 2019-01-07 16:15

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.

查看更多
登录 后发表回答