HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Similar methods using loops

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
methodssimilarusingloops

Problem

Is it recommended to combine two similar methods into one?

public void initialize_board(){
    for(int y = 0; y < board.length; y++){
        for(int x = 0; x < board.length; x++){
            if(x == 0)
                board[x][y] = (char)y;
            else
                board[x][y] = '~';
        }
    }
}

public void display_board(){
    for(int y = 0; y < board.length; y++){
        for(int x = 0; x < board.length; x++){
            System.out.print(board[x][y]);
        }
        System.out.print("\n");
    }
}

Solution

Not so similar...

Just because the method bodies "look similar" doesn't make them similar. It's better to think in terms of purpose instead. The two methods are for completely different things. They are not similar, and good to be separated.

In functional languages you could use a "walk" method to iterate over all cells of the board and use a callback function to act on each cell. You could emulate that behavior in Java, but the code will get more complex, and I'm not sure it will be worth it in this example.

Robustness

Do you intend to initialize the board more than once in the lifetime of the object? If not (probably), then move the initialization to the constructor.

Writing style

You should use camelCase for naming, for example initializeBoard instead of initialize_board.

It's recommended to use braces with ifs, for example:

if (x == 0) {
    board[x][y] = (char)y;
} else {
    board[x][y] = '~';
}


It's better to print a newline using println:

System.out.println();
// instead of: System.out.print("\n");

Code Snippets

if (x == 0) {
    board[x][y] = (char)y;
} else {
    board[x][y] = '~';
}
System.out.println();
// instead of: System.out.print("\n");

Context

StackExchange Code Review Q#47090, answer score: 11

Revisions (0)

No revisions yet.