简体   繁体   中英

Why should I avoid using Java Label Statements?

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?

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM