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

橙三吉。 提交于 2019-12-01 11:09:33

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.

CloudyMarble

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.

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