else or return?

后端 未结 19 920
故里飘歌
故里飘歌 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: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()
    

提交回复
热议问题