为什么Java允许在任意语句上标记中断? [英] Why does Java allow for labeled breaks on arbitrary statements?

查看:115
本文介绍了为什么Java允许在任意语句上标记中断?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天刚刚了解到以下Java代码是完全合法的:

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

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

    if (doneExecutingThisBlock())
        break myBlock;

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

请注意 myBlock 不是循环 - 它只是我用花括号分隔的代码块。

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

这似乎是一个相当奇怪的功能。这意味着您可以使用命名的 break 来打破 if 语句或匿名阻止,尽管你可以'通常在这些情境中使用 break 语句。

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.

我的问题是:有好处这个设计决定的原因是什么?也就是说,为什么要这样做,你只能使用标记的 break 而不是常规<$ c来打破某些封闭语句$ C>断裂 S'为什么要允许这种行为呢?鉴于(相对)精心设计的Java如何作为一种语言,我认为这是有原因的,但老实说我想不出一个。

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.

推荐答案

这样做似乎是为了简单起见。如果最初标记的中断只能破坏循环语句,那么语言设计者应该立即明白限制是不必要的,语义对所有语句都是一样的。对于语言规范的经济性,编译器的简单实现,或者只是出于普遍性的习惯,为任何语句定义标记的break,而不仅仅是循环语句。

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.

如果在并行宇宙中它仅限于循环语句,那么有人发布问题的机会仍然可能小得多在stackoverflow上:为什么它不能在任意语句上工作?

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?

这篇关于为什么Java允许在任意语句上标记中断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆