为什么应该避免使用 Java 标签语句?

发布于 2024-08-15 04:54:35 字数 162 浏览 9 评论 0原文

互联网上到处都有人说你应该避免在 java 中使用标签语句。但是,我发现它们在某些情况下非常有用,即嵌套循环。
关于为什么不使用它们,我找不到满意的答案。我认为标签的替代品通常会降低可读性或性能,或两者兼而有之。

那么是什么让带标签的 Break 和 continue 语句如此糟糕呢?

Everywhere across the internet people say that you should avoid using label statements in java. However, I find them very useful in some cases, namely nested loops.
I cannot find satisfactory answers as to why not to use them. I think that alternatives to labels often reduce either readability, or performance, or both.

So what makes labeled break and continue statements so bad?

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

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

发布评论

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

评论(4

我不吻晚风 2024-08-22 04:54:35

标签完全可以摆脱嵌套的 for 循环。

 

PS:就我个人而言,我建议(并且我在这一点上与 Kent Beck 一致,请参阅他的 实现模式书)将嵌套循环放入单独的方法中,然后用return突破,但这会引起“单一返回点”人们的愤怒在我身上。互联网,哦,互联网。

Labels are perfectly okay to break out of nested for-loops.

 

PS: personally, I'd suggest (and I am in accordance with Kent Beck on this, see his implementation patterns book) to put the nested loops in a separate method and then break out with return but that will cast the anger of the "single return point" folks upon me. Internet, oh, internet.

冰雪之触 2024-08-22 04:54:35

我发现标记的 Break 和 continue 语句都是完全没有必要的。这只是一种风格。还有其他方法可以达到相同的结果,并且许多人更喜欢这些方法。

I find both labelled breaks and continue statements to be completely unnecessary. It's just a style thing. There are other ways to achieve the same results and many people prefer those.

你如我软肋 2024-08-22 04:54:35

最常见的论点是它们对于初学者来说很难解释。另一个论点是(太多)嵌套循环被认为是不好的做法;换句话说,当你看到一个标签时,几乎可以肯定存在一个嵌套循环,这使得标签隐含地不好。常见的做法是将嵌套循环重构为方法。这应该可以提高可维护性和其他类似的事情。然而,如果嵌套循环除了几行代码中明显的事情之外没有做其他事情,那么我认为它是完全可以承受的。

Most common argument is that they're hard to interpret for starters. Another argument is that (too many) nested loops are considered bad practice; in other words, when you see a label, then there's almost certain a nested loop and that makes the label thus implicitly bad. Common practice is that nested loops are refactored into a method. This should improve maintainability and other things like that. However, if the nested loop isn't doing other things than the obvious thing in only a few lines of code, then it's in my opinion perfectly affordable.

千柳 2024-08-22 04:54:35

只要方法只做一件事,只做一件事并且做得很好,就不需要避免标签。

但是,如果需要标记的 Break 和 continue 语句,只需快速检查一下该方法是否仍然足够内聚。

No need to avoid labels as long as the method does just one thing, one thing only and does it well.

However, if there is a need for labelled breaks and continue statements just do a quick mental check if the method is still cohesive enough.

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