else or return?

后端 未结 19 833
故里飘歌
故里飘歌 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:56

    I think you should't worry about performance here. In this case readability and maintainability are way more important.

    Sticking to one exit point for a routine is a good practice.

    However, sometimes multiple returns just make the code a lot clearer, especially when you have a number of tests near the beginning of the code (ie checking if all of the input parameters are in the correct format) for which an 'if-true' should lead to a return.

    ie:

    if (date not set) return false;
    age = calculateAgeBasedOnDate();
    if (age higher than 100) return false;
    ...lots of code...
    return result;
    

提交回复
热议问题