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.
Best Answer
break
exists for the sole reason of exiting a loop, I can't think of any better way to do that.