使用“if/elseif/else”与“if/else{if/else}”相比
我发现自己经常使用这样的模式:
if (a > b) {
foo();
}
elseif (c > d) {
bar();
}
else {
baz();
}
这里的要点是,第二个条件与第一个条件没有明显的联系,除非您仔细遵循程序逻辑。这是一件非常糟糕的事情吗? 出于可维护性的原因,更好地表述上述内容吗
if (a > b) {
foo();
}
else {
if (c > d) {
bar();
}
else {
baz();
}
}
?有没有更好的模式我完全错过了? “不明显连接”位似乎是我的代码中更常见的错误来源之一。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这并不重要。
我更喜欢 Leaky Rowboat* 模式:
当您返回某些东西时,这种模式会更好:
*提早保释,快速保释
It doesn't really matter.
I prefer the Leaky Rowboat* pattern:
which is even better when you are returning something:
*bail early, bail fast
我认为第一个绝对是更好的选择。我唯一一次使用第二个方法是将代码放在外部 else 中,而不在内部 if/else 中。
当我看到 else if 时,我立即寻找 if。所以我想说这显然是有联系的。
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.
我避免使用第二种方法,因为它会导致大型条件语句出现大量缩进。
I avoid using the second approach since it leads to lot of indentation for large conditionals.
我当然会使用第一个,因为它比第二个更具可读性。
第二个选项将迫使读者记住哪些条件必须为真才能到达嵌套的
if
,它在每个时刻以及第三个或第四个嵌套的if
中读取> 这变得非常烦人、非常脆弱并且在逻辑上难以遵循。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 nestedif
this becomes really annoying and very vulnerable and logically hard to follow.