If the specific conditions are incorrect, I can’t return anything

I'm writing a matrix class. I've written a getnumber method that returns the number in a specific slot in the matrix What should I do if a particular slot does not exist? I'm 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?
    }
}

After returning the type integer, I don't want to return null because it's not a good design What's the best way to do this? I've considered abandoning the index out of boundary exception, but I don't think it's a good idea because it won't change anything

Solution

Since your code checks the boundaries of the input, you should throw instead of return:

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 instead of silently return is that going beyond the boundary is a programming error The caller should fix it by not calling first, not by checking the return value

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>