oka*_*han 2 java refactoring loops duplicates
我正在尝试TDD教程,并希望编写好的代码.我遇到了使用循环重复代码的问题.
我的代码看起来像这样:
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;
}
Run Code Online (Sandbox Code Playgroud)
如你所见,我在不同的方法中使用相同的for循环.有没有办法避免这种情况,以及如何避免这种情况?
我正在用Java编程.
我认为你正在采取"避免代码重复"的好代码的想法有点太严重了.确实,您应该避免重复代码,因为这会使您更难以阅读和维护代码.但循环是控制语句,不需要避免.它与if语句类似,虽然您将在代码中多次使用它们,但您不会将if放入额外的方法中.
不过,如果你真的想这样做,可以为for循环中的每个代码块创建一个Runnable,并创建一个这样的方法:
public void loop(Runnable runnable) {
for (int row = 0; row < rows; row++) {
for (int col = 0; col < columns; col++) {
runnable.run();
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以将所需的Runnable传递给该方法(您可能还需要以某种方式将参数传递给runnable).有关更多信息,请参阅此帖子上的SO.