Java Secret: Labels as an Anti-Pattern
Overview
It is well known that Java has no goto. (Technically goto is a keyword, but it cannot be used any where)However, Java has continue and break which can be mis-used just like goto can.
NOTE: This article is not an example what to do. It is an article which will help you better understand Java's edge cases and help you recognise mis-use.
Recognising a label
A Java Puzzler uses a label to create some strange looking code.public static void main(String... args) { http://www.google.com/search?q=Hello+World System.out.println("Hello World"); }This compiles and runs. This is because what appears to be a URL is actually a label and a comment. ;)
goto backwards
If you want to go back you can use the following structure.while(true) { // do something. if(go-back) continue; // do something else. if(go-back) continue; break; }The only purpose of the loop is to allow code to jump back to the start. Using labels it could look like this.
LOOP1: while(true) { // do something. LOOP2: while(true) { // do something. if(go-back) continue LOOP1; // do something. } // do something else. if(go-back) continue LOOP1; break; }This creates the sort of spaghetti code which removing goto was supposed to avoid. :(
goto forwards
You can use break to goto forwardsONE: do { // do something if(goto-forwards) break ONE; // do something. } while(false);The while(false) is a loop which only loops once. i.e. not really a loop.
What is perhaps surprising and that unlike continue, break doesn't need a loop.
HERE: { System.out.println("First"); if (true) break HERE; System.out.println("Last"); }prints
First
I always thought break and continue are cousins of goto, but I never tried to prove it, thanks!:)
ReplyDeleteI find the idea you can use break without a loop or switch the most disturbing. ;)
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteNeat Article!
ReplyDeleteThe break does not need a loop. It is actually quite useful, and I have used it in not quite the contrived way you have, but effectively to short-circuit code.
The first example with the seeming URL is neat. I will need to use that one in a JUG meeting, or when I teach.