问题描述
今天我有一位同事建议我重构我的代码,使用label语句来控制我创建的2个嵌套for循环的流程。我之前从未使用它们,因为我个人认为它们会降低程序的可读性。如果论证足够坚实,我愿意改变主意使用它们。人们对标签声明的看法是什么?
Today I had a coworker suggest I refactor my code to use a label statement to control flow through 2 nested for loops I had created. I've never used them before because personally I think they decrease the readability of a program. I am willing to change my mind about using them if the argument is solid enough however. What are people's opinions on label statements?
推荐答案
如果你可以跳过两个循环(或一个循环),很容易表达很多算法包含switch语句)。不要为此感到难过。另一方面,它可能表明过于复杂的解决方案。所以请退一步看看问题。
Many algorithms are expressed more easily if you can jump across two loops (or a loop containing a switch statement). Don't feel bad about it. On the other hand, it may indicate an overly complex solution. So stand back and look at the problem.
有些人更喜欢所有循环的单入口,单退出方法。也就是说,完全避免中断(并继续)和早期返回循环。这可能会导致一些重复的代码。
Some people prefer a "single entry, single exit" approach to all loops. That is to say avoiding break (and continue) and early return for loops altogether. This may result in some duplicate code.
我强烈要避免做的是引入辅助变量。隐藏状态内的控制流会增加混乱。
What I would strongly avoid doing is introducing auxilary variables. Hiding control-flow within state adds to confusion.
将标记循环拆分为两种方法可能很困难。例外情况可能太重了。尝试单一条目,单退出方法。
Splitting labeled loops into two methods may well be difficult. Exceptions are probably too heavyweight. Try a single entry, single exit approach.
这篇关于我应该避免使用Java标签语句吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!