And*_*huk 8 c# java oop continue break
我被告知在OOP语言中使用break和continue标签不是OOP编程风格.你能详细解释一下原因和问题是什么吗?
诀窍在于这个标签词.我的意思是打破/继续.
class BreakWithLabelDemo {
public static void main(String[] args) {
int[][] arrayOfInts = {
{ 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length;
j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
if (foundIt) {
System.out.println("Found " + searchfor +
" at " + i + ", " + j);
} else {
System.out.println(searchfor +
" not in the array");
}
}
}
Run Code Online (Sandbox Code Playgroud)
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
tib*_*ibo 25
告诉你的人可能意味着中断和继续是分支语句,如goto,这是命令式编程的一种机制.
中断/继续只允许您跳转到外部语句,这意味着您无法在代码中到处运行.所以你留在同一个方法对象中,所以它与OOP不相容.
无论如何,说断裂并继续不是OOP是没有意义的.我们可以讨论它们对可读性的影响,但这就是全部.
Pet*_*rey 16
break和continue不是函数式编程.没有任何关于OOP的建议break
,continue
甚至goto
在方法中也是一个坏主意.
在OOP语言中劝阻使用break和continue的恕我直言,因为它们可能导致复杂性和混乱.由于很少使用标签,因此可能会进一步混淆.我会说当你觉得它是问题最简单的解决方案时你仍应该使用它们.
// confusing use of LABEL
http://www.google.com/
do {
if (condition) continue http;
} while(condition2)
Run Code Online (Sandbox Code Playgroud)
另一个令人困惑的用途
GOTO: {
// code
if (condition)
break GOTO; // without a loop
// code
}
Run Code Online (Sandbox Code Playgroud)
好好利用标签
OUTER:
for(outer loop) {
for(inner loop)
if (condition)
continue or break OUTER;
}
Run Code Online (Sandbox Code Playgroud)
奇怪的使用标签
FOUND: {
for(loop)
if(found)
break FOUND;
// not found
handle not found
}
Run Code Online (Sandbox Code Playgroud)
不使用 break/continue 的建议可能与 OOP 没有真正的关系。它基于这样一个事实,即这些语句类似于臭名昭著的 GOTO,它可以使代码完全不可读。然而,教条是不好的忠告。主要范式应该是代码的可读性。使用 break 或 continue 跳出第一行的循环比将整个其余部分放入 if 条件要清楚得多。