I am trying a TDD Tutorial and want to write good code. I faced a problem with duplicate code using loops.
My code looks like this:
public Board(int rows, int columns) {
this.rows = rows;
this.columns = columns;
blocks = new Block[rows][columns];
for (int row = 0; row < rows; row++) {
for (int col = 0; col < columns; col++) {
blocks[row][col] = new Block('.');
}
}
}
public boolean hasFalling(){
boolean falling = false;
for (int row = 0; row < rows; row++) {
for (int col = 0; col < columns; col++) {
if(blocks[row][col].getChar() == 'X'){
falling = true;
}
}
}
return falling;
}
public String toString() {
String s = "";
for (int row = 0; row < rows; row++) {
for (int col = 0; col < columns; col++) {
s += blocks[row][col].getChar();
}
s += "\n";
}
return s;
}
As you see I am using the same for loop in different methods. Is there a way to avoid this and how are the approaches to avoid it ?
I am programming with Java.
I think you are taking the "avoiding code duplication" idea of good code a bit too serious. It is true that you should avoid duplicate code since it makes it harder to read and maintain your code. But the loops are control statements and don't need to be avoided. It is similar to if statements, although you will use those a lot of times in your code, you will not put your if into an extra method.
Nevertheless, if you really want to do that, you can create a Runnable for each code block inside the for loop and create a method like this:
public void loop(Runnable runnable) {
for (int row = 0; row < rows; row++) {
for (int col = 0; col < columns; col++) {
runnable.run();
}
}
}
You can then pass the Runnable you want to that method (also you probably need to pass the parameters to the runnable in some way). For more info see e.g. this post on SO.
I'm not sure how to simplify all the loops (and I'm not entirely sure you need/want to) but you can essentially eliminate most of the code in your hasFalling() method. Instead you could do this:
public boolean hasFalling(){
return toString().contains('X');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With