6

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?

4 Answers4

8

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.

akuhn
  • 27,477
  • 2
  • 76
  • 91
1

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.

Dan Dyer
  • 53,737
  • 19
  • 129
  • 165
1

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
0

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.

Vlad Gudim
  • 23,397
  • 16
  • 69
  • 92