Java: labelled break considered harmful

Readers of my last post may have thought that Eclipse makes refactoring easy. It does – up to a point. I had started to refactor an 800-line module with deeply nested loops – just a matter of extracting the inner loops as methods…
… NO!
When I tried this I got:
“Selection contains branch statement but corresponding branch target is not selected”
???
On closer examination I discovered that the code contained a construct like:
foo:
plunge();
for (int i = 0; i < 1; i++) {
boggle();
if (bar) {
break foo;
}
}

[Added later: PUBLIC GROVEL. Jim has pointed out that I have misunderstood the break syntax, so the code above is WRONG. At least this shows that I never use labelled break. It should read:
plunge();
foo: for (int i = 0; i < 1; i++) {
boggle();
if (bar) {
break foo;
}
}

Strikethoughs indicate my earlier misconceptions.
What’s happening here? The code contains a labelled break. If the break foo is encountered, then the control jumps to the label foo. This can be almost anywhere in the module – and in this case it was often before the start of the loop. to
out of the labelled loop.
Jumping to arbitrary parts of a module is considered harmful (Go To Statement Considered Harmful). Sun/Java announces:

2.2.6 No More Goto Statements
Java has no goto statement1. Studies illustrated that goto is (mis)used more often than not simply “because it’s there”. Eliminating goto led to a simplification of the language–there are no rules about the effects of a goto into the middle of a for statement, for example. Studies on approximately 100,000 lines of C code determined that roughly 90 percent of the goto statements were used purely to obtain the effect of breaking out of nested loops. As mentioned above, multi-level break and continue remove most of the need for goto statements.

but surely the code below is a direct replacement for goto.
while (true) {
break foo;
}

continue is useful. break out of single level (unlabelled) is useful. break out of multiple loops might just be OK if it was always downwards and always to the point immediately after a loop.
But it isn’t.
so – and I am surprised that I can’t easily find it on Google:
“labelled break considered harmful”
However as it is still extremely easy to write code that cannot be easily refactored I still hold that labelled breaks should be used only when essential.

This entry was posted in programming for scientists. Bookmark the permalink.

One Response to Java: labelled break considered harmful

  1. Except for the rather tricky refactoring, more importantly, it is no longer possible for formally prove that the implementation is correct. (Which is as difficult as it is already…)

Leave a Reply

Your email address will not be published. Required fields are marked *