<p>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?</p>

[{'answer_id': 46517, 'author': 'Tim Frey', 'author_id': 1471, 'author_profile': 'https://Stackoverflow.com/users/1471', 'pm_score': 3, 'selected': False, 'text': '<p>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."</p>\n\n<p>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.</p>\n'}, {'answer_id': 46534, 'author': 'Bartosz Bierkowski', 'author_id': 3666, 'author_profile': 'https://Stackoverflow.com/users/3666', 'pm_score': 2, 'selected': False, 'text': "<p>I never use labels in my code. I prefer to create a guard and initialize it to <em>null</em> or 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. </p>\n"}, {'answer_id': 46579, 'author': 'Tom Hawtin - tackline', 'author_id': 4725, 'author_profile': 'https://Stackoverflow.com/users/4725', 'pm_score': 7, 'selected': True, 'text': '<p>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.</p>\n\n<p>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.</p>\n\n<p>What I would strongly avoid doing is introducing auxilary variables. Hiding control-flow within state adds to confusion.</p>\n\n<p>Splitting labeled loops into two methods may well be difficult. Exceptions are probably too heavyweight. Try a single entry, single exit approach.</p>\n'}, {'answer_id': 46581, 'author': 'BIBD', 'author_id': 685, 'author_profile': 'https://Stackoverflow.com/users/685', 'pm_score': 5, 'selected': False, 'text': "<p>Labels are like goto's: Use them sparingly, and only when they make your code faster <strong>and</strong> more importantly, more understandable, </p>\n\n<blockquote>\n  <p>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.</p>\n</blockquote>\n\n<p>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).</p>\n\n<p>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.</p>\n"}, {'answer_id': 46911, 'author': 'Don Kirkby', 'author_id': 4794, 'author_profile': 'https://Stackoverflow.com/users/4794', 'pm_score': 3, 'selected': False, 'text': '<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n'}, {'answer_id': 130390, 'author': 'Pyrolistical', 'author_id': 21838, 'author_profile': 'https://Stackoverflow.com/users/21838', 'pm_score': 3, 'selected': False, 'text': '<p>I think with the new for-each loop, the label can be really clear.</p>\n\n<p>For example:</p>\n\n<pre><code>sentence: for(Sentence sentence: paragraph) {\n  for(String word: sentence) {\n    // do something\n    if(isDone()) {\n      continue sentence;\n    }\n  }\n}\n</code></pre>\n\n<p>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</p>\n'}, {'answer_id': 479629, 'author': 'Ceilingfish', 'author_id': 58991, 'author_profile': 'https://Stackoverflow.com/users/58991', 'pm_score': 3, 'selected': False, 'text': "<p>I'd argue in favour of them in some locations, I found them particularly useful in this example:</p>\n\n<pre><code>\nnextItem: for(CartItem item : user.getCart()) {\n\n  nextCondition : for(PurchaseCondition cond : item.getConditions()) {\n     if(!cond.check())\n        continue nextItem;\n     else\n        continue nextCondition;\n\n  }\n  purchasedItems.add(item);\n}\n</code></pre>\n"}, {'answer_id': 481514, 'author': 'Peter Lawrey', 'author_id': 57695, 'author_profile': 'https://Stackoverflow.com/users/57695', 'pm_score': 5, 'selected': False, 'text': '<p>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.</p>\n\n<p>BTW: this compiles and runs.</p>\n\n<pre><code>class MyFirstJavaProg {  \n        public static void main(String args[]) {\n           http://www.javacoffeebreak.com/java101/java101.html\n           System.out.println("Hello World!");\n        }\n}\n</code></pre>\n'}, {'answer_id': 2676495, 'author': 'Selenia', 'author_id': 321444, 'author_profile': 'https://Stackoverflow.com/users/321444', 'pm_score': 3, 'selected': False, 'text': '<p>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.</p>\n\n<pre><code>private static void testByFactoring() {\n    primes: for (int ctr = 0; ctr &lt; m_toFactor.length; ctr++) {\n        int toTest = m_toFactor[ctr];\n        for (int ctr2 = 0; ctr2 &lt; m_divisors.length; ctr2++) {\n            // max (int) Math.sqrt(m_numberToTest) + 1 iterations\n            if (toTest != m_divisors[ctr2]\n                        &amp;&amp; toTest % m_divisors[ctr2] == 0) {\n                continue primes; \n            }\n        } // end of the divisor loop\n    } // end of primes loop\n} // method\n</code></pre>\n\n<p>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.</p>\n\n<p>So they have their uses, it depends on the problem you were trying to solve. </p>\n'}, {'answer_id': 36525519, 'author': 'Jeremy Harton', 'author_id': 2411774, 'author_profile': 'https://Stackoverflow.com/users/2411774', 'pm_score': 1, 'selected': False, 'text': '<p>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.  </p>\n\n<p>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.  </p>\n\n<p>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.</p>\n'}, {'answer_id': 40549383, 'author': 'polaretto', 'author_id': 255931, 'author_profile': 'https://Stackoverflow.com/users/255931', 'pm_score': 1, 'selected': False, 'text': '<p>I found labels to be sometimes useful in tests, to separate the usual setup, excercise and verify phases and group related statements. For example, using the BDD terminology:</p>\n\n<pre><code>@Test\npublic void should_Clear_Cached_Element() throws Exception {\n    given: {\n        elementStream = defaultStream();\n        elementStream.readElement();\n        Assume.assumeNotNull(elementStream.lastRead());\n    }\n    when:\n        elementStream.clearLast();\n    then:\n        assertThat(elementStream.lastRead()).isEmpty();\n}\n</code></pre>\n\n<p>Your formatting choices may vary but the core idea is that labels, in this case, provide a noticeable distinction between the logical sections comprising your test, better than comments can. I think the <a href="http://spockframework.org" rel="nofollow noreferrer">Spock</a> library just builds on this very feature to declare its test phases.</p>\n'}, {'answer_id': 69244209, 'author': 'Yassir Khaldi', 'author_id': 5517465, 'author_profile': 'https://Stackoverflow.com/users/5517465', 'pm_score': 0, 'selected': False, 'text': '<p>Personally whenever I need to use nested loops with the innermost one having to break out of all the parent loops, I just write everything in a method with a return statement when my condition is met, it\'s far more readable and logical.</p>\n<p>Example Using method:</p>\n<pre class="lang-java prettyprint-override"><code>  private static boolean exists(int[][] array, int searchFor) {\n    for (int[] nums : array) {\n      for (int num : nums) {\n        if (num == searchFor) {\n          return true;\n        }\n      }\n    }\n    return false;\n  }\n</code></pre>\n<p>Example Using label (less readable imo):</p>\n<pre class="lang-java prettyprint-override"><code>boolean exists = false;\nexistenceLoop:\nfor (int[] nums : array) {\n  for (int num : nums) {\n    if (num == searchFor) {\n      exists = true;\n      break existenceLoop;\n    }\n  }\n}\n\nreturn exists;\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/46496', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2628/']