我应该避免使用 Java 标签语句吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Should I avoid using Java Label Statements?
提问by Aaron
Today I had a coworker suggest I refactor my code to use a label statement to control flow through 2 nested for loops I had created. I've never used them before because personally I think they decrease the readability of a program. I am willing to change my mind about using them if the argument is solid enough however. What are people's opinions on label statements?
今天我有一个同事建议我重构我的代码以使用标签语句来控制我创建的 2 个嵌套 for 循环的流程。我以前从未使用过它们,因为我个人认为它们会降低程序的可读性。但是,如果论点足够扎实,我愿意改变使用它们的想法。人们对标签声明有什么看法?
采纳答案by Tom Hawtin - tackline
Many algorithms are expressed more easily if you can jump across two loops (or a loop containing a switch statement). Don't feel bad about it. On the other hand, it may indicate an overly complex solution. So stand back and look at the problem.
如果您可以跳过两个循环(或包含 switch 语句的循环),则可以更轻松地表达许多算法。不要为此感到难过。另一方面,它可能表示一个过于复杂的解决方案。所以退后一步看问题。
Some people prefer a "single entry, single exit" approach to all loops. That is to say avoiding break (and continue) and early return for loops altogether. This may result in some duplicate code.
有些人更喜欢所有循环的“单入口单出口”方法。也就是说,完全避免中断(和继续)和提前返回循环。这可能会导致一些重复的代码。
What I would strongly avoid doing is introducing auxilary variables. Hiding control-flow within state adds to confusion.
我强烈避免做的是引入辅助变量。在状态中隐藏控制流会增加混乱。
Splitting labeled loops into two methods may well be difficult. Exceptions are probably too heavyweight. Try a single entry, single exit approach.
将标记循环拆分为两种方法可能很困难。异常可能太重量级了。尝试单进单出方法。
回答by Outlaw Programmer
I'm curious to hear what your alternative to labels is. I think this is pretty much going to boil down to the argument of "return as early as possible" vs. "use a variable to hold the return value, and only return at the end."
我很想知道你的标签替代品是什么。我认为这几乎可以归结为“尽可能早地返回”与“使用变量来保存返回值,并且只在最后返回”的论点。
Labels are pretty standard when you have nested loops. The only way they really decrease readability is when another developer has never seen them before and doesn't understand what they mean.
当您有嵌套循环时,标签是非常标准的。它们真正降低可读性的唯一方法是当其他开发人员以前从未见过它们并且不理解它们的含义时。
回答by Bartosz Bierkowski
I never use labels in my code. I prefer to create a guard and initialize it to nullor other unusual value. This guard is often a result object. I haven't seen any of my coworkers using labels, nor found any in our repository. It really depends on your style of coding. In my opinion using labels would decrease the readability as it's not a common construct and usually it's not used in Java.
我从不在我的代码中使用标签。我更喜欢创建一个守卫并将其初始化为null或其他不寻常的值。这个守卫通常是一个结果对象。我没有看到我的任何同事使用标签,也没有在我们的存储库中找到任何标签。这真的取决于你的编码风格。在我看来,使用标签会降低可读性,因为它不是一种常见的结构,通常不会在 Java 中使用。
回答by BIBD
Labels are like goto's: Use them sparingly, and only when they make your code faster andmore importantly, more understandable,
标签就像 goto:谨慎使用它们,只有当它们使您的代码更快,更重要的是,更易于理解时,
e.g., If you are in big loops six levels deep and you encounter a condition that makes the rest of the loop pointless to complete, there's no sense in having 6 extra trap doors in your condition statements to exit out the loop early.
例如,如果您处于六层深的大循环中,并且遇到了使循环的其余部分毫无意义完成的条件,那么在您的条件语句中使用 6 个额外的陷门来提前退出循环是没有意义的。
Labels (and goto's) aren't evil, it's just that sometimes people use them in bad ways. Most of the time we are actually trying to write our code so it is understandable for you and the next programmer who comes along. Making it uber-fast is a secondary concern (be wary of premature optimization).
标签(和 goto 的)并不是邪恶的,只是有时人们以不好的方式使用它们。大多数时候,我们实际上是在尝试编写我们的代码,以便您和下一个出现的程序员可以理解。使其超快是次要的问题(注意过早的优化)。
When Labels (and goto's) are misused they make the code less readable, which causes grief for you and the next developer. The compiler doesn't care.
当标签(和 goto 的)被滥用时,它们会降低代码的可读性,这会让您和下一个开发人员感到悲伤。编译器不在乎。
回答by Don Kirkby
I've never seen labels used "in the wild" in Java code. If you really want to break across nested loops, see if you can refactor your method so that an early return statement does what you want.
我从未见过在 Java 代码中“随意”使用标签。如果你真的想打破嵌套循环,看看你是否可以重构你的方法,以便早期的 return 语句做你想要的。
Technically, I guess there's not much difference between an early return and a label. Practically, though, almost every Java developer has seen an early return and knows what it does. I'd guess many developers would at least be surprised by a label, and probably be confused.
从技术上讲,我想早期回归和标签之间没有太大区别。但实际上,几乎每个 Java 开发人员都看到了早期回报并知道它的作用。我猜许多开发人员至少会对标签感到惊讶,并且可能会感到困惑。
I was taught the single entry / single exit orthodoxy in school, but I've since come to appreciate early return statements and breaking out of loops as a way to simplify code and make it clearer.
我在学校学习了单入/单出正统,但从那以后,我开始欣赏早期的 return 语句和打破循环作为简化代码并使其更清晰的一种方式。
回答by Pyrolistical
I think with the new for-each loop, the label can be really clear.
我认为使用新的 for-each 循环,标签可以非常清晰。
For example:
例如:
sentence: for(Sentence sentence: paragraph) {
for(String word: sentence) {
// do something
if(isDone()) {
continue sentence;
}
}
}
I think that looks really clear by having your label the same as your variable in the new for-each. In fact, maybe Java should be evil and add implicit labels for-each variables heh
我认为通过在新的 for-each 中让您的标签与您的变量相同,这看起来非常清楚。事实上,也许 Java 应该是邪恶的,并为每个变量添加隐式标签 heh
回答by Ceilingfish
I'd argue in favour of them in some locations, I found them particularly useful in this example:
我会在某些地方支持它们,我发现它们在这个例子中特别有用:
nextItem: for(CartItem item : user.getCart()) {
nextCondition : for(PurchaseCondition cond : item.getConditions()) {
if(!cond.check())
continue nextItem;
else
continue nextCondition;
}
purchasedItems.add(item);
}
回答by Peter Lawrey
There are few occasions when you need labels and they can be confusing because they are rarely used. However if you need to use one then use one.
很少有您需要标签的情况,它们可能会令人困惑,因为它们很少使用。但是,如果您需要使用一种,请使用一种。
BTW: this compiles and runs.
顺便说一句:这会编译并运行。
class MyFirstJavaProg {
public static void main(String args[]) {
http://www.javacoffeebreak.com/java101/java101.html
System.out.println("Hello World!");
}
}
回答by Selenia
I have use a Java labeled loop for an implementation of a Sieve method to find prime numbers (done for one of the project Euler math problems) which made it 10x faster compared to nested loops. Eg if(certain condition) go back to outer loop.
我已经使用 Java 标记循环来实现 Sieve 方法来查找素数(针对 Euler 数学问题之一完成),与嵌套循环相比,它的速度提高了 10 倍。例如,如果(特定条件)回到外循环。
private static void testByFactoring() {
primes: for (int ctr = 0; ctr < m_toFactor.length; ctr++) {
int toTest = m_toFactor[ctr];
for (int ctr2 = 0; ctr2 < m_divisors.length; ctr2++) {
// max (int) Math.sqrt(m_numberToTest) + 1 iterations
if (toTest != m_divisors[ctr2]
&& toTest % m_divisors[ctr2] == 0) {
continue primes;
}
} // end of the divisor loop
} // end of primes loop
} // method
I asked a C++ programmer how bad labeled loops are, he said he would use them sparingly, but they can occasionally come in handy. For example, if you have 3 nested loops and for certain conditions you want to go back to the outermost loop.
我问过一个 C++ 程序员标签循环有多糟糕,他说他会谨慎使用它们,但它们偶尔会派上用场。例如,如果您有 3 个嵌套循环,并且在某些情况下您想返回到最外层循环。
So they have their uses, it depends on the problem you were trying to solve.
所以它们有它们的用途,这取决于你试图解决的问题。
回答by Jeremy Harton
Yes, you should avoid using label unless there's a specific reason to use them (the example of it simplifying implementation of an algorithm is pertinent). In such a case I would advise adding sufficient comments or other documentation to explain the reasoning behind it so that someone doesn't come along later and mangle it out of some notion of "improving the code" or "getting rid of code smell" or some other potentially BS excuse.
是的,你应该避免使用标签,除非有特定的理由使用它们(它简化算法实现的例子是相关的)。在这种情况下,我会建议添加足够的注释或其他文档来解释其背后的推理,以免有人稍后出现并将其从“改进代码”或“摆脱代码异味”的一些概念中解脱出来,或者其他一些潜在的 BS 借口。
I would equate this sort of question with deciding when one should or shouldn't use the ternary if. The chief rationale being that it can impede readability and unless the programmer is very careful to name things in a reasonable way then use of conventions such as labels might make things a lot worse. Suppose the example using 'nextCondition' and 'nextItem' had used 'loop1' and 'loop2' for his label names.
我会将这类问题等同于决定何时应该或不应该使用三元 if。主要的理由是它会妨碍可读性,除非程序员非常小心地以合理的方式命名事物,否则使用诸如标签之类的约定可能会使事情变得更糟。假设使用“nextCondition”和“nextItem”的示例使用“loop1”和“loop2”作为标签名称。
Personally labels are one of those features that don't make a lot of sense to me, outside of Assembly or BASIC and other similarly limited languages. Java has plenty of more conventional/regular loop and control constructs.
个人标签是那些对我来说没有多大意义的功能之一,在汇编或 BASIC 以及其他类似的有限语言之外。Java 有很多更传统/常规的循环和控制结构。