Skip to content

Consider extracting methods to simplify loops #11

Description

@ericlippert

This is another example of asking whether code can be simplified to eliminate a comment. In the code that begins

    //put the rooms into the grid
    for (let i = 0; i < existingrooms.length; i++) {
        const room = existingrooms[i];

notice that what you've done is created a loop that fetches a room, and then the 30 lines of code that follows affects only that room and the grid. This is a perfect candidate for an "extract method" refactoring. I would consider putting that 30 lines of code inside the Grid class itself, and then the loop becomes

    for (let i = 0; i < existingrooms.length; i++)
        gamegrid.addRoom(existingrooms[i]);

even better, you can use the of form of the for loop:

for (let room of existingrooms)
        gamegrid.addRoom(room);

The code is now so clear that it does not require a comment.

Every time I write a loop, particularly a long one, I ask myself "could this loop be easily made into a one-liner"? If the answer is yes, then I do it, and the code becomes easier to read.


This is particularly true for your recent update where you have

function createtherooms() {
    for (let attempt = 0; attempt < 100; attempt++) {

And then hundreds of lines of code in the loop body. It is much easier on readers of the code to write:

function createRooms() 
{
    for (let attempt = 0; attempt < 100; attempt++) {
        let success = tryCreateRooms();
        if (success) return;
    }
    throw new Error("whatever");
}

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions