I'm staring at some old code from 2001 and came across this statement:
else { do { int c = XMLDocumentFragmentScannerImpl.this.scanContent(); if (c == 60) { XMLDocumentFragmentScannerImpl.this.fEntityScanner.scanChar(); XMLDocumentFragmentScannerImpl.this.setScannerState(1); break label913; }
I had never seeen this before, and discovered labeled breaks here:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Doesn't this essentially function like goto
? Is it even good practice to use it? It makes me uneasy.
Break and continue are OK unless you have several of them in the loop which becomes confusing. The need to avoid multiple returns has been obviated by shorter functions, which are the norm now.
Labels are fine to break out of nested for-loops. I'd suggest to put the nested loops in a separate method and then break out with return . The problem is that the complex flows of processing becomes really hard to follow.
break is a completely acceptable statement to use (so is continue, btw). It's all about code readability -- as long as you don't have overcomplicated loops and such, it's fine.
Java break label Labeled break statement is used to terminate the outer loop, the loop should be labeled for it to work.
No, it's not like a goto, since you can't "go" to another part of the control flow.
From the page you linked:
The break statement terminates the labeled statement; it does not transfer the flow of control to the label. Control flow is transferred to the statement immediately following the labeled (terminated) statement.
This means you can only break loops that are currently being executed.
Consider this example:
first: for( int i = 0; i < 10; i++) { second: for(int j = 0; j < 5; j ++ ) { break xxx; } } third: for( int a = 0; a < 10; a++) { }
You could replace xxx
with first
or second
(to break the outer or inner loop), since both loops are being executed, when you hit the break
statement, but replacing xxx
with third
won't compile.
It's not as terrible as goto
because it only sends control to the end of the labeled statement (typically a loop construct). The thing that makes goto
unlikeable is that it is an arbitrary branch to anywhere, including labels found higher up in the method source, so that you can have home-grown looping behavior. The label-break functionality in Java doesn't allow that kind of craziness because control only goes forward.
I've only used it once about 12 years ago, in a situation where I was needing to break out of nested loops, the more-structured alternative would've made for more complicated tests in the loops. I wouldn't advise using it a lot but I wouldn't flag it as an automatic bad-code smell.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With