I really hate copy and pasting my code from one method to another. It signals something in my brain, "This could be done either more efficiently or more readable". This is used in a minesweeper program I am implementing with a JavaFx GUI (that's not very relevant, but it might help to know). Hopefully this is enough context!
@Contract(pure = true)
private int setMinX(int x){ return (x == 0 ? 0:(x-1)); }
@Contract(pure = true)
private int setMinY(int y){ return (y == 0 ? 0:(y-1)); }
@Contract(pure = true)
private int setMaxX(int x){ return (x == this.width-1 ? this.width-1 : x+1); }
@Contract(pure = true)
private int setMaxY(int y){ return (y == this.height-1 ? this.height-1 : y+1);}
private void adjacents(int x, int y){
//calculate adjacents for the just placed mine
int minX = setMinX(x);
int minY = setMinY(y);
int maxX = setMaxX(x);
int maxY = setMaxY(y);
if (this.mineField[minX][minY] != -1){ this.mineField[minX][minY] += 1; } //left top corner
if (this.mineField[maxX][minY] != -1){ this.mineField[maxX][minY] += 1; } //right top corner
if (this.mineField[maxX][maxY] != -1){ this.mineField[maxX][maxY] += 1; } // bottom right corner
if (this.mineField[minX][maxY] != -1){ this.mineField[minX][maxY] += 1; } // bottom left corner
if(x > 0 && x < this.width-1){
if (this.mineField[x][minY] != -1){ this.mineField[x][minY] += 1; } // top-middle
if (this.mineField[x][maxY] != -1){ this.mineField[x][maxY] += 1; } //bottom-middle
}
if(y > 0 && y < this.height-1){
if (this.mineField[minX][y] != -1){ this.mineField[minX][y] += 1; } // left-middle
if (this.mineField[maxX][y] != -1){ this.mineField[maxX][y] += 1; } //right-middle
}
}
public void floodClear(int x, int y) {
int minX = setMinX(x);
int minY = setMinY(y);
int maxX = setMaxX(x);
int maxY = setMaxY(y);
if (this.mineField[x][y] >= 0 && !this.liveGame[x][y]) {
//IMPLEMENT WITH GUI
//show(x,y);
if (this.mineField[minX][minY] == 0) {
floodClear(minX, minY);
}
if (this.mineField[maxX][minY] == 0) {
floodClear(maxX, minY);
}
if (this.mineField[maxX][maxY] == 0) {
floodClear(maxX, maxY);
}
if (this.mineField[minX][maxY] == 0) {
floodClear(minX, maxY);
}
if (x > 0 && x < this.width - 1) {
if (this.mineField[x][minY] == 0) {
floodClear(x, minY);
} // top-middle
if (this.mineField[x][maxY] == 0) {
floodClear(x, maxY);
} //bottom-middle
}
if (y > 0 && y < this.height - 1) {
if (this.mineField[minX][y] == 0) {
floodClear(minX, y);
} // left-middle
if (this.mineField[maxX][y] == 0) {
floodClear(maxX, y);
} //right-middle
}
}
}
@Contract
annotations that you have added? \$\endgroup\$setMinY
when it seems more like a getter. \$\endgroup\$