开发者

Exiting a loop in Java

I'm using Java but I guess this question applies to whatever language. I just want to ask whether it's better practice to exit a loop using a boolean which I toggle within the loop or to just use break;

For example, I was just writing a method to get the valid moves for a Queen in chess.

private static final int[][] DIRS = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {-1, -1}, {-1, 1}, {1, -1}};

public Vector<Move> getValidMoves() {
    Vector<Move> validMoves = new Vector<Move>();

    for (int开发者_如何学编程 i = 0; i < DIRS.length; i++) {
        boolean stopped = false;
        int newX = x + DIRS[i][0];
        int newY = y + DIRS[i][1];
        while (!stopped && newX >= 0 && newX < 8 && newY >= 0 && newY < 8) {
            if (board[newX][newY] == null) {
                validMoves.add(new Move(x, y, newX, newY));
                newX += DIRS[i][0];
                newY += DIRS[i][1];
            } else {
                if (board[newX][newY].getColour() == colour) {
                    stopped = true;
                } else {
                    validMoves.add(new Move(x, y, newX, newY));
                    stopped = true;
                }
            }
        }
    }

    return validMoves;
}

If I exit the while loop using break; instead of setting stopped to true like I do it's my understanding that it runs more efficiently but is not the greatest code style.


break exists for the sole reason of exiting a loop, I can't think of any better way to do that.


Performance-wise, it won't matter much, you are allocating 1 boolean on the stack and adding 1 comparison at each loop iteration, so nothing to worry about.

It mainly depends on whether you want to finish executing the rest of the loop code before exiting it or not. Break will exit immediatly and setting a boolean will wait for the next iteration before stopping.

If you don't need to finish the loop iteration, your code will be easier to read if you use break


As using boolean variable here does not affect much for performance, this is about readability. Some people believes using break statement reduces code's readability for two reasons.

One is that user sometimes cannot read the code sequentially (need to jump read) when break statement is used. This can be confusing as reader need to determine where the break statement brings next operation to.

Another thing is that using variable for stop condition helps reader understands why it is stopped if you name the variable meaningfully. e.g if you use isEmpty boolean variable for stop condition, it is very clear that the loop has stopped because whatever is empty.

I am not against using break statement but I think what you should do is to make it readable as possible.


I suggest you do what you believe is clearest. IMHO Using a boolean can be clearer for nested loops, but for simple loops using a flag is needlessly verbose.

while (0 <= newX && newX < 8 && 0 <= newY && newY < 8) {
    if (board[newX][newY] == null) {
        validMoves.add(new Move(x, y, newX, newY));
        newX += DIRS[i][0];
        newY += DIRS[i][1];
    } else {
        if (board[newX][newY].getColour() != colour) 
            validMoves.add(new Move(x, y, newX, newY));
        break;
    }
}


Definitively use break. That is what the keyword is for, it generates more concise code, does not make someone reading your code wonder where that "stopped" in the loop comes from, and is likely faster, too.


Depends on who you talk to. I have a college professor who swore he'd shoot any student who didn't exit a control structure (such as a loop) with a normal expression check.

However, I have seen that as much as that might be "disciplined", there are times where to exit a loop or other control structure early is desireable. With that in mind, I say "go for it". You can still be disciplined and have readable code that does not have unexpected behavior with an early exit (as long as that exit would be a valid reason for leaving that structure.


Thats exactly why there is break in the language. I would just use it.


Like the users above mentioned, definitely use break. Exiting loops is what it's made for.


A point that seems not to have been raised yet:

In Java (not exclusively though), exiting nested loops will be more elegant with break than having the same condition nested in every level. It will also make the code more maintainable.

In addition, it can make the logic of the loop much more simple, because as soon as your come to a breaking condition you can act, rather than continue executing code. This too promotoes modularity within the loop body.


You may want to read up on the usage of break from the oracle webpage

Branching Statements Tutorial

using a Break to exit a loop is accept as a good practice. then if you use it or not is up to you.

now if you want to improve the readability of your code and its flexibility you can consider breaking down you complex loops into functions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜