Method with boolean return - if else vs. if
Take for example the following two statements:
if (booleanVariable)
{
doSomething();
return true;
}
else
{
return false;
}
and
if (booleanVariable)
{
doSomething();
return true;
}
return false;
Which one would be preferred?
They both return the same result in th开发者_运维百科e end.
Any reason one would be better to use than the other?
Personally, I think the cleanest way would be
if (booleanVariable) {
doSomething();
}
return booleanVariable;
Moving the redundant returns outside the if block highlights what you are doing differently if the variable is set.
The if...else structure provides more readable code, but if you understand it fine and don't want to write as much, just do the second one :-)
I would have done it in different way. since, your first code solution might give an error, at least in c# since you will need to return a value outside of if-else scope.
i would have created a separate bool variable, and set it to true/false depending on what your if-test results
bool test;
if (booleanVariable)
{
doSomething();
test = true;
}
return test;
now if the if-test fail, the return bool will stay false as default.
精彩评论