Best Practice on IF/ELSE Statement Order

前端 未结 10 2239
陌清茗
陌清茗 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:32

    Use whichever makes the code easier to read. This is usually the second of your options.

    Edit

    In a lot of cases, it depends on what you're trying to achieve, for example, if you want to check that a connection started correctly:

    Connect()
    if connected then
        SendString("Hello!")
    else
        FlagConnectionFailed()
    endif
    

    Whereas if you want to catch an error:

    ' Just about to send something
    if not connected then
        FlagConnectionLost()
        return
    endif
    SendString("Still connected!")
    

    But you may even want to:

    Disconnect()
    if not connected then
        return "Complete"
    else
        FlagConnectionDisconnectFailure()
    endif
    

    (I'm not a VB programmer, so the syntax above is largely made up!)

提交回复
热议问题