Why it is a bad practice to use break/continue labels in OOP (e.g. Java, C#)?

Andrii Muzychuk picture Andrii Muzychuk · Jun 21, 2012 · Viewed 21.8k times · Source

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

Answer

tibo picture tibo · Jun 21, 2012

The person who told you that would probably means that break and continue are branching statements like goto which are one mechanism of imperative programming.

A break/continue only allow you to jump to an outer statement, which means that you cannot go everywhere in the code. So you stay in the same method object, so it's not incompatible with OOP.

Anyway, saying that break and continue are not OOP is a non-sense. We can discuss about their impact on the readibility maybe but that's all.