I was told that using break and continue labels in an OOP language is not OOP programming style. Can you explain in detail why and what is the problem?
The trick was with this label word. I meant labeled break/continue.
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");
}
}
}
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Break and continue are OK unless you have several of them in the loop which becomes confusing. Meanwhile there is nothing evil in typical construction: while (true) { // ... if (something) { break; } // ... } E.g. the loop with condition in the middle.
Labels are fine to break out of nested for-loops. I'd suggest to put the nested loops in a separate method and then break out with return . The problem is that the complex flows of processing becomes really hard to follow.
Overusing break statements is also bad practice because it introduces more exit points. We generally want to keep exit points to a minimum since multiple exit points complicate our logic and make it more difficult to comprehend code.
The advice not to use break/continue is probably not really related to OOP. It is based on the fact that these statements are similar to the infamous GOTO, which can make code completely unreadable. However, dogmas are bad counsels. The main paradigm should be readability of the code. Jumping out of a loop in the first line using break or continue can be much clearer than putting the whole rest into an if condition.
break and continue are not functional style programming. There is nothing about OOP which suggestsbreak
, continue
or even goto
within a method is a bad idea.
IMHO using break and continue are discouraged in OOP languages as they can lead to complexity and confusion. As Labels are used rarely they can confuse even further. I would say you should still use them when you feel its the simplest solution to the problem.
// confusing use of LABEL
http://www.google.com/
do {
if (condition) continue http;
} while(condition2)
another confusing use
GOTO: {
// code
if (condition)
break GOTO; // without a loop
// code
}
Good use of a label
OUTER:
for(outer loop) {
for(inner loop)
if (condition)
continue or break OUTER;
}
Odd use of a label
FOUND: {
for(loop)
if(found)
break FOUND;
// not found
handle not found
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With