If a variable with
null value gets used in your program causing a
NullPointerException, this is clearly a situation in your program which you did not expect. You must ask yourself the question: "Did I not expect it because I didn't take into consideration the possibility of a
null value or did I assume the value could never be
If the answer is the latter, the problem isn't because you didn't handle the
null value. The problem happened earlier, and you're only seeing the consequence of that error on the particular line it's used. In this case, simply adding a
if (variable != null) isn't going to cut it. You'll wind up skipping lines you were supposed to execute because the variable was
null, and you'll ultimately hit a line further on where you again assumed it wouldn't be
null should be used
As a general rule, return null only when "absent" is a possible return value. In other words, your data layer may search for a record with a specific id. If that record isn't found, you can either throw an exception or simply return null. You may do either, but I prefer not to throw exceptions in situations where the strong possibility exists. So you return
null instead of a value.
The caller of this method, presumably written by you, knows the possibility exists that the record may not exist and checks for
null accordingly. There is nothing wrong with this in this case, though you should handle this possibility as soon as possible as otherwise everywhere in your program you will need to deal with the possibility of a
In other words, treat
null as a legitimate value, but deal with it immediately rather than wait. Ideally in your program, you should ever only have to check if it is
null once in your program and only in the place where such a
null value is handled.
For every value you expect to be non-null, you need not add a check. If it is
null, accept that there is an error in your program when it was instantiated. In essence, favor fail fast over fail safe.