DEV Community

loading...

Discussion on: Don’t pay the for-loop tax

Collapse
danhomola profile image
Dan Homola Author

While I agree that breaking out of a loop is a point for the loops, breaking out of a for rubs me the wrong way. I believe you should use a while (or do-while) loops and specify the condition appropriately. Breaks hamper readability imho and make the code even harder to reason about or even formally verify.

Collapse
tbodt profile image
tbodt

I've written plenty of loops that would look a lot worse if I had to write them without break statements. For example, this code to look for possible forward moves for a white rook on a chessboard:

while (row++ < BOARD_TOP) {
    if (is_white_piece(row, column))
        break;
    GENERATE_MOVE;
    if (is_black_piece(row, column))
        break;
}

The first check could obviously be moved into the loop condition, but I can't think of a good way to move the second check into the loop condition too.

Edit: Language is C.
Edit 2: GENERATE_MOVE call was in the wrong place, moved it outside of the second if.

Thread Thread
danhomola profile image
Dan Homola Author

I agree the loop would look worse. However, in this case all you are doing is finding the first piece and if it's white calling a method, right?

So you could do something like

const pieceIndex = findFirstPiece(row);
if (pieceIndex > 0 && is_white_piece(pieceIndex , column))
  GENERATE_MOVE;

where the findFirstPiece would find the first row value that is either a white or a black piece, returning -1 if no such value was found.

Thread Thread
tbodt profile image
tbodt

Oops, I pasted the code wrong. What I wanted to do was generate every move from the current position of the rook up to a piece, and including the piece if the piece is a black piece. See updated post.

maxart2501 profile image
Massimo Artizzu

If that's still JavaScript (could be even C or Java), it could be refactored in a more expressive way:

const piece = chessboardRows.find(pieceAtColumn(column));
if (piece && isWhite(piece)) {
    GENERATE_MOVE;
}

function pieceAtColumn(column) {
    return function(row) {
        // something like row[column]?
    };
}

Maybe it's more verbose, but also clearer.

Thread Thread
tbodt profile image
tbodt

This was C, I didn't have a find method on all the arrays.

Thread Thread
maxart2501 profile image
Massimo Artizzu

Ah, crud, you're out of luck then XD

I think the aim of this article is mainly JavaScript or any other language that support methods for functional programming.

I guess you're stuck with classic loops unless some kind of abstraction helps you with that (in Java <8 it's still a mess anyway).

Thread Thread
tbodt profile image
tbodt

I discovered that I pasted the code wrong, so I've edited the post to correct that. In the original version I could have written a function to find the index in the array, but I can't do that for the correct version.