views:

247

answers:

4

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?

+5  A: 

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.

Adrian
+1 for good advice and especially for scorn on religious nonsense.
Jonathan Feinberg
A: 

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
A: 

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.

Totophil
+1  A: 

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