I have a function that returns an id number if the argument exists in the database. If not, it returns null. Is this begging for a null pointer exception? Negative id numbers are not permitted, but I thought it would be clearer to have non-existent arguments returning null instead of an error code like -1. What do you think?
private Integer tidOfTerm(String name) throws SQLException {
String sql = "SELECT tid FROM term_data WHERE name = ?";
PreparedStatement prep = conn.prepareStatement(sql);
prep.setString(1, name);
ResultSet result = prep.getResultSet();
if (result.next()) {
return result.getInt("tid");
}
return null; // TODO: is this begging for a null pointer exception?
}
As you know, a value type cannot be assigned a null value. For example, int i = null will give you a compile time error.
Yes this is valid because Integer is the class representing int. This is the reason why Integer can hold a null value.
Null values in a Set object As per the definition a set object does not allow duplicate values but it does allow at most one null value. Null values in HashSet − The HashSet object allows null values but, you can add only one null element to it.
This is perfectly legal. If you want to avoid a NPE, throw a custom exception. But don't return a negative number. If the caller doesn't check the return value, you will always have a problem. But doing false calculation (because the result is for instance multiplied by -1) is definitely harder to debug than an uncatched exception.
Returning a null
in the case of a lookup that does not give a result is a normal method of representing non-existance. I would choose it in this case. (Lookup methods for the standard Java Map classes are an example for use of null
in case the map does not contain a key.)
As for returning a special value for the ID, I would only propose to do that if your system already contains special values repesenting special ID's.
Another often heard possibility is throwing an exception in this case. It is not wise however to use exceptions to pass state, so I would not do that either.
I think it is legitimate to return null in this case. Just make sure that the intention is documented properly.
Returning a negative value in this case would be ok, but it is not an all-around solution. What if negative values were allowed in the db?
EDIT: I want to add a word about the related discussions on SO regarding returning nulls or empty lists (or arrays). I am in favor of returning empty lists or arrays instead of null, but the context is different. When trying to obtain a list, it is typically part of a parent object, and it actually makes sense for the parent object to have an empty list instead of a null reference. In this case, null has a meaning (= not found) and there is no reason to avoid returning it.
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