public boolean hasCapturableEnemy(Piece[][] board, int startX, int startY, int endX, int endY) {
//If the Pawn belong to the Upper Team (Faces downward)
if(board[startX][startY] != null && board[startX][startY].getTeam() == Player.UP) {
//If a Piece exists on a diagonally adjacent tile, return true
if(startX - endX == -1 && Math.abs(startY - endY) == 1) {
if( (board[startX + 1][startY - 1] != null && board[startX + 1][startY - 1].getTeam() != Player.UP) ||
(board[startX + 1][startY + 1] != null && board[startX + 1][startY + 1].getTeam() != Player.UP)) {
return true;
}
}
}
if(board[startX][startY] != null && board[startX][startY].getTeam() == Player.DOWN) {
//If the Pawn belongs to the Down Team (Faces upward)
if(startX - endX == 1 && Math.abs(startY - endY) == 1) {
//If a Piece exists on a diagonally adjacent tile, return true
if( (board[startX - 1][startY - 1] != null && board[startX - 1][startY - 1].getTeam() != Player.DOWN) ||
(board[startX - 1][startY + 1] != null && board[startX - 1][startY + 1].getTeam() != Player.DOWN)) {
return true;
}
}
}
return false;
}
我有这个函数包含两个类似的if语句很难重构。
我这样说是因为这两个共享重复代码的重要部分,但由于部分与主板[startX + 1] [startY - 1]和主板[startX - 1] [startY - 1]略有不同,我发现很难有效地重构它。
换句话说,我肯定可以通过创建包含公共部分的另一个函数来重构它,但是我害怕在该函数中创建更多if循环并使代码更脏。
有关重构此类代码的建议吗?
答案 0 :(得分:1)
只需将乘数变量设置为1
或-1
,具体取决于" up",然后在您抵消&的任何时候乘以该变量#34; X"值。
这样的事情应该有用,我想:
if(board[startX][startY] == null) {
return false;
}
Player player = board[startX][startY].getTeam()
int xOffset = player == Player.UP
? 1
: -1;
//If a Piece exists on a diagonally adjacent tile, return true
if(endX - startX == xOffset && Math.abs(startY - endY) == 1) {
if( (board[startX + xOffset][startY - 1] != null && board[startX + xOffset][startY - 1].getTeam() != player) ||
(board[startX + xOffset][startY + 1] != null && board[startX + xOffset][startY + 1].getTeam() != player)) {
return true;
}
}
还有一些你可以做的进一步重构,在变量中捕获board[startX + xOffset]
以使事情更加清晰。