Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Labels in Java - bad practice?

Tags:

java

label

Why using labels in Java is a bad practice? I cant find a reason. All explanations - you shouldn't use it just because you shouldn't.

like image 407
ArtemPetrov Avatar asked Mar 17 '26 08:03

ArtemPetrov


1 Answers

It's difficult to read code containing breaks to a label. Also, a label can be accidentally moved, or code inserted at an incorrect location with respect to a label. The compiler is not able to warn you of these effects since the code remains syntactically valid.

Code that's difficult to read is difficult to maintain. Bugs will inevitably creep in.

Other control structures (break, continue, while, for, etc.) don't suffer from this.

Note that a switch to a label doesn't suffer from these effects either: the structure of a switch block is well-defined.

The most sensible alternative to breaking out of a nested loop is to recast the code to a function and use return. You also get the added benefit of being able (potentially) to return a value back to the caller.

like image 128
Bathsheba Avatar answered Mar 18 '26 20:03

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!