I find myself very commonly using a pattern like this:
if (a > b) {
foo();
}
elseif (c > d) {
bar();
}
else {
baz();
}
The point here being that the second condition is not obviously connected to the first, unless you're carefully following the program logic. Is this a very bad thing? Would it be preferable to phrase the above as
if (a > b) {
foo();
}
else {
if (c > d) {
bar();
}
else {
baz();
}
}
for maintainability reasons? Is there a better pattern that I'm missing entirely? The "not obviously connected" bit seems to be one of the more common sources of bugs in my code.
It doesn't really matter.
I prefer the Leaky Rowboat* pattern:
if (a > b)
{
foo();
return;
}
if (c > d)
{
bar();
return;
}
baz();
which is even better when you are returning something:
if (a > b)
return foo();
if (c > d)
return bar();
return baz();
*bail early, bail fast
I think the first is definitely preferable. The only time I would use the second is to put code in the outer else that isn't in the inner if/else.
When I see an else if, I immediately look for the if. So I would say it is obviously connected.
I think this is a code smell. It's not very obvious what you are doing here, or why you are doing it. The fact that you think both that they aren't obviously connected and that they are a frequent source of bugs is telling you not to be doing this this way.
Rewrite this code so that the reason you are branching on these conditions is clear. Ideally you would be able to read the code and have it express your intent and/or your specifications.
taller_than_wide = a > b;
more_expensive_than_normal = c > d;
if (taller_than_wide) {
foo();
}
elseif (more_expensive_than_normal) {
bar();
}
else {
baz();
}
I avoid using the second approach since it leads to lot of indentation for large conditionals.
I would certainly use the first as it's much much readable than the second.
The second option will force the reader to keep in mind which conditions has to be true to get to the nested if
where it reads at each moment and in the third or fourth nested if
this becomes really annoying and very vulnerable and logically hard to follow.
来源:https://stackoverflow.com/questions/5518256/use-of-if-elseif-else-versus-if-elseif-else