Best Practice on IF/ELSE Statement Order

前端 未结 10 2227
陌清茗
陌清茗 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!)

    0 讨论(0)
  • 2020-12-16 15:36

    Go with the most readable version for your specific case, and by the way, don't compare a boolean expression to true and false. Use condition and Not condition (!condition in C#.)

    if (condition == true) // bad
    if (condition) // better 
    
    0 讨论(0)
  • 2020-12-16 15:36

    In the final assembly/machine code, it does make a difference. The statement which is most likely to be executed is done in the path without the branch. This way, the pipeline isn't broken causing valuable cycles to be lost.

    I have no clue if the compiler leaves your if then statement order intact and this way forces the assembly to take this optimized route.

    I have read that visual studio 2008 (when it was announced) would have an optimization functionality where the compiler adds measurements at branches and then during runtime measures how often a certian path is taken. Then in subsequent recompiles the most optimal code path is preferred.

    I have no clue if this feature ever made it past the 'design/academic phase'

    0 讨论(0)
  • 2020-12-16 15:44

    First of all, you shouldn't compare to boolean values, this is, do

    if condition then
    

    instead of

    if condition = true then
    

    About your question, it depends on the natural variable names, IMO.

    For example, if you are creating a client that needs to check if it's connected (the most common case)

    if connected then
        //Proceed
    else
        //Throw error
    end if
    

    Or, if you are creating a different program, where you have a variable, say, retrieved and you want to know if the content has been retrieved

    if not retrieved then
       //Error
    end if
    

    Do not do

    if retrieved then
    else
        //Error
    end if
    
    0 讨论(0)
提交回复
热议问题