问题
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