我有一個標誌參數的方法。我認爲將布爾值傳遞給方法是一種不好的做法(使簽名複雜化,違反了「每種方法做一件事」的原則)。我認爲將該方法分解爲兩種不同的方法會更好。但如果我這樣做,這兩種方法會非常相似(代碼重複)。是否有任何技術用標誌參數拆分方法?
我想知道是否有一些通用的技術用於將標誌參數拆分爲兩個獨立的方法。
這裏是我的方法(JAVA)的代碼:
int calculateNumOfLiveOrDeadNeighbors(Cell c, int gen, boolean countLiveOnes) {
int x = c.getX();
int y = c.getY();
CellState state;
int aliveCounter = 0;
int deadCounter = 0;
for (int i = x - 1; i <= x + 1; i++) {
for (int j = y - 1; j <= y + 1; j++) {
if (i == x && j == y)
continue;
state = getCell(i, j).getCellState(gen);
if (state == CellState.LIVE || state == CellState.SICK){
aliveCounter++;
}
if(state == CellState.DEAD || state == CellState.DEAD4GOOD){
deadCounter++;
}
}
}
if(countLiveOnes){
return aliveCounter;
}
return deadCounter;
}
好主意,但使用靜態內部類來實現過濾器。 – Ralph 2010-11-24 12:09:06