我有以下代碼。唯一的問題是我們通過一個checkstyle程序來運行它,它出現錯誤Cyclomatic Complexity是11(最大允許值是10)。我想知道如何刪除if語句中的一個,以使其執行相同的操作並讓程序通過測試。如何刪除其中的一個if語句並縮短代碼?
/**
* Check if there is a winner on the board
* @return the winner if BLANK there is no winner
**/
public char checkWinner(){
this.winner = BLANK;
int totalTiles = GRIDSIZE*GRIDSIZE;
//Check if the game has a win
for (int i=0; i < GRIDSIZE; i++) {
if((grid[i][0] == grid[i][1]) && (grid[i][1] == grid[i][2])){
winner = grid[i][0];
return winner;
}
if((grid[0][i] == grid[1][i]) && (grid[1][i] == grid[2][i])){
winner = grid[0][i];
return winner;
}
}
if((grid[0][0] == grid[1][1]) && (grid[1][1] == grid[2][2])){
winner = grid[0][0];
return winner;
}
if((grid[0][2] == grid[1][1]) && (grid[1][1] == grid[2][0])){
winner = grid[0][2];
return winner;
}
//Check if the game is a tie
if (movesMade == totalTiles){
winner = TIE;
}
return winner;
}
幾乎是它是檢查3x3的井字遊戲的贏家。 – ron8 2011-05-14 15:16:42
這是一個愚蠢的檢查運行..代碼看起來很可讀.. – Claudiu 2011-05-14 15:24:04
看起來是可讀的,我可以看到,減少if語句的數量,而不損害可讀性的唯一的事情是捕獲他們在一個方法和迭代它,而不是if語句:'boolean checkWinner(GRID_TYPE squrare1,GRID_TYPE aquare2,GRID_TYPE square3)'返回是否有勝利(並設置this.winner)。我不知道我會做到這一點,或只是保持原樣。 – amit 2011-05-14 15:27:36