else or return?

后端 未结 19 586
故里飘歌
故里飘歌 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 14:01

    I think the 'single exit point' is overrated. Sticking to it too dogmatically can lead to some very complex code, which should really either have multiple exit points, or be split into smaller methods.

    I would say the choice between the two depends on the semantics.

    'If some condition is true then do this, otherwise do that' maps perfectly onto if-else.

    if (isLoggedIn) {
        RedirectToContent();
    } else {
        RedirectToLogin();
    }
    

    'If some condition then do some cleanup and bail out' maps better onto Code 2. This is called the guard pattern. This leaves the body of the code as normal, clear and uncluttered by unnecessary indentation as possible. It's commonly used to validate parameters or state (check if something is null, or something is cached, things like that).

    if (user == null) {
        RedirectToLogin();
        return;
    }
    
    DisplayHelloMessage(user.Name);
    

    It's not uncommon to see both forms used in the same project. Which to use, like I say, depends on what you're trying to convey.

提交回复
热议问题