if-else or early return

后端 未结 3 512
时光说笑
时光说笑 2021-01-21 20:00

Sometimes I like to use early return statements to prevent nesting if statement, which I find makes for less readable code.

I am wondering if there is any objective or o

3条回答
  •  無奈伤痛
    2021-01-21 20:37

    I would opt for the first version. I was actually given a lengthy explanation several years ago regarding this.

    The two examples, as your wrote them now, are functionally identical. If the a condition be true, then the logic in the first if condition will execute, and the function will return. However, have a closer look at the second scenario:

    void func() {
        if (a) {
            do b
            return;
        }
    
        do c
    }
    

    Right now, should the first if fire, the function would return, otherwise c would execute. However, consider that at some point down the line a programmer decides to refactor the method for some reason. If he were to take out the return statement, then the logic for c would also execute if a were true. This may seem far-fetched, but it could happen more easily than you might think. On the other hand, if you use a full if-else, then even a refactor of the if condition would never result in the c logic evaluating at the same time.

提交回复
热议问题