Why does Java allow for labeled breaks on arbitrary statements?

前端 未结 9 1863
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-07 13:16

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

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

    if (doneExecutingThisBlock())
        break myBlock;         


        
9条回答
  •  情话喂你
    2021-02-07 13:49

    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?

提交回复
热议问题