Search code examples
javalanguage-designbreak

Why does Java allow for labeled breaks on arbitrary statements?


I just learned today that the following Java code is perfectly legal:

myBlock: {
    /* ... code ... */

    if (doneExecutingThisBlock())
        break myBlock;

    /* ... more code ... */
}

Note that myBlock isn't a loop - it's just a block of code I've delimited with curly braces.

This seems like a rather strange feature to have. It means that you can use a named break to break out of an if statement or anonymous block, though you can't normally use a break statement in these contexts.

My question is this: is there a good reason for this design decision? That is, why make it so that you can only break out of certain enclosing statements using labeled breaks but not regular breaks? And why allow for this behavior at all? Given how (comparatively) well-designed Java is as a language I would assume there's a reason for this, but I honestly can't think of one.


Solution

  • It is plausible that this was done for simplicity. If originally the labeled break can only break loop statements, then it should be immediately clear to language designer that the restriction isn't necessary, the semantics work the same for all statements. For the economics of the language spec, and simpler implementation of compilers, or just out of the habit towards generality, labeled break is defined for any statement, not just loop statements.

    Now we can look back and judge this choice. Does it benefit programmers, by giving them extra expression power? Seems very little, the feature is rarely used. Does it cost programmers in learning and understanding? Seems so, as evidenced by this discussion.

    If you could go back time and change it, would you? I can't say I would. We have a fetish for generality.

    If in a parallel universe it was limited to loop statements only, there is still a chance, probably much smaller, that someone posts the question on stackoverflow: why couldn't it work on arbitrary statements?