‘GOTO Considered Harmful’ Considered Harmful

Leave a comment

July 25, 2010 by huionn

During reading Programming Paradigm (http://en.wikipedia.org/wiki/Programming_paradigm) in wiki, I come across this very old article – ‘GOTO Considered Harmful’ Considered Harmful (interesting title) in wiki’s reference.

The author posed a question:

“Let X be an N x N matrix of integers. Write a program that will print the number of the first all-zero row of X, if any.”

It is a trivial problem.

Typically, I would write something like

public void printFirstRowWithZerosWithoutGoto(int[][] matrix) {
        for (int i = 0; i < matrix.length; i++) {
            boolean allZero = true;
            for (int j = 0; j < matrix[i].length; j++) {
                if (matrix[i][j] != 0) {
                    allZero = false;
                    break;
                }               
            }
            if (allZero) {
                print(i, matrix[i]);
                break;
            }
        }
}

In a nested loop, I always think that allZero flag is necessary (another alternative is comparing j with matrix[i].length which is less intention revealing). After reading the article, I realize that there are other better solutions.

public void printFirstRowWithZeros(int[][] matrix) {
        nextRow:
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                if (matrix[i][j] != 0) {
                    continue nextRow;
                }               
            }
            print(i, matrix[i]);
            break;
        }
}

Java disallows goto but it does allow labeled statement (continue and break with label) to achieve similar benefits of goto – simpler flow, less code and less variable.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: