Use of “if/elseif/else” versus “if/else{if/else}”

≡放荡痞女 提交于 2019-12-30 11:08:07

问题


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.


回答1:


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




回答2:


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.




回答3:


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();
}



回答4:


I avoid using the second approach since it leads to lot of indentation for large conditionals.




回答5:


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

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