Best Practice on IF/ELSE Statement Order

前端 未结 10 2254
陌清茗
陌清茗 2020-12-16 14:48

Which is a better practice? (I\'m coding in .Net if that makes a difference)

IF condition = true THEN
   ...true action--even if rare...
ELSE
   ...action
E         


        
10条回答
  •  半阙折子戏
    2020-12-16 15:22

    Generally, I would always put the true clause first. Something like this, for me, obfuscates meaning:

    If not something Then
      'do something 1
    Else
      'do something 2
    End If
    

    This results in a double-negative, much better to write it like this:

    If something Then
      'do something 2
    Else
      'do something 1
    End If
    

    I believe this recommendation comes from code complete. A great book well worth reading

    http://www.cc2e.com/

    If you're going to have more than one else then it might be better to consider a case statement.

提交回复
热议问题