If “if” is the last control statement in function and its block always executes “return”, then should I use “else”?

懵懂的女人 提交于 2019-12-25 05:46:07

问题


Consider this code (written in C to demonstrate the problem):

int foo1(int a)
{
    if(a)
         return 33;
    return 22;
}

int foo2(int a)
{
    if(a)
         return 33;
    else
         return 22;
}

As you can see, foo1(int a) does exactly the same as foo2(int a). foo1(int a) is shorter, however I get the impression that foo2(int a) is just more logical (that's only my impression). Which one is better? Is it good to use else with if that is the last control statement in function code and its block always executes return?


回答1:


I don't know about C specifically, but in C# at least the convention is to omit the else for any if conditions that immediately return. The reasoning is that the else is already implied, so explicitly adding it is not only redundant, but increases the nesting level of following code, thus making the code harder to read. Take a look at the following code as an example.

public int Test()
{
    if (condition)
        return 0;
    else
    {
        var ex1 = doCmd1();
        var ex2 = doCmd2();
        var result = ex1 + ex2;
        return result;
    }
    Console.WriteLine("Here I'm printing before returning");
    return -1;
}

If you take just a very brief glance at this code, you might think there are three ways the method can exit. However, that's not the case - it can only exit in two ways. Everything outside the if-else is completely unreachable. Now, here's the same code, but without the extra else:

public int Test()
{
    if (condition)
        return 0;

    var ex1 = doCmd1();
    var ex2 = doCmd2();
    var result = ex1 + ex2;
    Console.WriteLine("Here I'm printing before returning");
    return result;
}

This is much more clear to read and quickly identify what the results of the operation are going to be.




回答2:


My opinion is that foo1 is superior. The lines

    return 22;
}

as the end of the function trumps any other readability issue.

foo2 should FAPP be considered written as

int foo2(int a)
{
    if(a){
         return 33;
    } else {
         return 22;
    }
}

add some 20 or so lines of code before the return 22; line and it is a source of obscure bugs and hindering readability.



来源:https://stackoverflow.com/questions/32057896/if-if-is-the-last-control-statement-in-function-and-its-block-always-executes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!