For a simple project, I represent a two-dimensional grid as a one-dimensional array, with both row and column indices between 1
and gridHeight
. When retrieving a cell from the grid, I first need to check if both row and column IDs are within allowed bounds.
public void checkIfAllowed(int row_or_column) {
if ((row_or_column < 1) || (row_or_column > gridHeight)) {
throw new IndexOutOfBoundsException("Row or column ID is not acceptable.");
}
}
public boolean getCellById(int row, int column) {
checkIfAllowed(row);
checkIfAllowed(column);
return grid[row * gridHeight + column];
}
Can it possibly be improved?
There are two things about this code that I don't particularly like:
- Somewhat repetitive code in
getCellById
. - It asks for permission instead of forgiveness: first checks everything, and then does the action. I would prefer a
try .. catch
construction (something like "try to return a value and then catchIndexOutOfBoundsException
), but would it really work for Java? The array dimension is defined during run time, and initial declaration for my grid is justprivate boolean[] grid;
.