分支语句:在 for/while 循环中中断或返回更好?

发布于 2024-09-08 20:26:36 字数 156 浏览 5 评论 0原文

显然只有在方法可以立即退出的情况下才用 return

for (...) {
   return;
}

或者

for () {
   break;
}

哪个更好?

Obviously with return only in the case that the method can immediately exit

for (...) {
   return;
}

or

for () {
   break;
}

Which is better?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

紫瑟鸿黎 2024-09-15 20:26:36

您给出的两个示例并不完全相同,因此很难说哪种风格更好。这里有两种方法,它们的作用稍微相似:

for (Foo foo: foos) {

    // ...

    if (ok) { return foo; }
}
return null;

对比:

Foo result = null;

for (Foo foo: foos) {

    // ...

    if (ok) {
        result = foo;
        break;
    }
} 

return result;

在这种情况下,我推荐第一种,因为它简单得多。不太可能存在显着的性能差异。有些人更喜欢第二种,因为他们只希望每个函数中有一个返回,但我认为遵守该规则并不总是一个好主意。有时多个 return 语句会让事情变得更加清晰。

The two examples you gave aren't exactly equivalent so it's a little difficult to say which is better style. Here are two approaches that are slightly more similar in what they do:

for (Foo foo: foos) {

    // ...

    if (ok) { return foo; }
}
return null;

Versus:

Foo result = null;

for (Foo foo: foos) {

    // ...

    if (ok) {
        result = foo;
        break;
    }
} 

return result;

In this case I'd recommend the first because it's much simpler. It is unlikely that there is a significant performance difference. Some people prefer the second because they only want a single return in each function, but I don't think it is always a good idea to stick to that rule. Sometimes multiple return statements makes things much clearer.

谁的新欢旧爱 2024-09-15 20:26:36

我宁愿建议采用中断方法。看起来代码更多,但更容易理解。此外,以后进行更改也更容易。为了清楚起见,您可以使用带标签的循环。

I would rather suggest the break approach. It looks like more code but is easier to understand. Also, making changes later is easier. You can go for labeled loops for clarity.

路还长,别太狂 2024-09-15 20:26:36

显然只有在方法可以立即退出的情况下才用return

您已经回答了自己的问题。这两者具有不同的语义,并且不能真正互换,并且 return 变体仅适用于更具体的场景...

...因此正是在这些特定场景中,您应使用 return 变体。意图是显而易见的,因此具有更好的可读性。如果在 return 就足够的情况下使用 break,那么读者必须花费更多时间来弄清楚 break 后会发生什么。当没有发生任何重大事件时,return 会很快更清楚地传达这一点。

Obviously with return only in the case that the method can immediately exit

You've answered your own question. These two have different semantics and aren't really interchangeable, and the return variant is applicable only to more specific scenarios...

...thus precisely in those specific scenarios you should use the return variant. The intention is immediately obvious and thus it makes for better readability. If you use a break when return suffices, then the reader must spend more time to figure out what happens after the break. When nothing significant happens, a return would've quickly conveyed this much more clearly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文