else or return?

后端 未结 19 578
故里飘歌
故里飘歌 2021-01-01 13:27

Which one out of following two is best wrt to performance and standard practice. How does .NET internally handles these two code snippets?

Code1

If(r         


        
相关标签:
19条回答
  • 2021-01-01 13:45

    Here's some additional reading on the guard clause: http://www.c2.com/cgi/wiki?GuardClause

    One term I did not see mentioned that I think is important -- the purpose of the guard clause is to increase readability. Single exit methods can tend toward "arrow" code (where nesting of statements makes an arrowhead).

    0 讨论(0)
  • 2021-01-01 13:45

    I think it does not matter. You should go for readability and I think the less brackets the better. So I would return without the last 2 brackets (see sample below). Please do not think about performance when writing something like this it won't give you anything but too much complexity at an too early stage.

    if(result)
    {
      process 1
      return;
    }
    
    process 2
    
    0 讨论(0)
  • 2021-01-01 13:46

    I tend to have multiple points of exit from a function. Personally I think it's clearer and in some cases it can be faster. If you check on something and then return the program won't execute any left commands. Then again as HZC said if you work on multi-threaded applications then your best shot might be using your first example. Anyway for small pieces of code it won't make any difference(probably not even for some larger ones). Most important is that you write how you feel comfortable with.

    0 讨论(0)
  • 2021-01-01 13:47

    I think the second option is better for cases of many condition (such as validation). If you use the first in these cases you will get ugly indentation.

     if (con){
        ...
        return;
     }
     if (other con){
        ...
        return;
     }
     ...
     return;
    
    0 讨论(0)
  • 2021-01-01 13:49

    I would use Code 1, because if I add something later after the if statement, I'm still positive it will execute, without me needing to remember to remove the return clause from where it is in Code 2.

    0 讨论(0)
  • 2021-01-01 13:52

    It depends on what "result", "process1" and "process2" are.

    If process2 is the logical consequence of "result" being false; you should go for Code 1. This is the most readable pattern if process1 and process2 are equivalent alternatives.

    if (do_A_or_B = A)
      A()
    else
      B()
    

    If result is some "no-go" condition and "process1" is merely a cleanup needed on such condition you should choose Code 2. It is the most readable pattern if "process2" is the main action of the function.

    if (NOT can_do_B)
    {
      A() 
      return
    }
    
    B()
    
    0 讨论(0)
提交回复
热议问题