I'm writing a Matrix class and I wrote a getNumber method which returns the number in a specific slot in the matrix. If the specific slot does not exists, what can I do? I got stuck here:
public int getNumber(int row, int column)
{
if (row < matrix.length && column < matrix[0].length) {
return data[row][column];
} else {
//what now then?
}
}
I don't want to return null after making the return type Integer because it doesn't feel like a nice design. What is the best way to do this? I considered ducking the IndexOutOfBoundsException but decided it is not a good idea because it doesn't change anything.
Since your code checks bounds on the input, you should throw, rather than returning:
public int getNumber(int row, int column) {
if (row >= matrix.length || column >= matrix[0].length) {
throw new IndexOutOfBoundsException("("+row+", "+column+") is not a valid pair of indexes.");
}
return data[row][column];
}
The reason you should throw, rather than returning silently, is that exceeding bounds is a programming error. The caller should fix it by not making the call in the first place, not by checking the return value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With