I have been using a lot of defensive null checks within my Java code. Though they serve their purpose well (most of the time), they come a with a huge trade off with 'ugly' looking code.
Does it really make sense to put these null checks in all the time? For example:
if(object == null){
log.error("...")
throw new SomeRuntimeException("");
} else{
object.someMethod();
}
Practically speaking, the above piece of code is equivalent to the statement object.someMethod();
If object's value is null, an exception would have been thrown in both cases (NullpointerException in the later).
Does it really make sense to mask the NullpointerExcetion (NPE) and throw some custom RunTimeException (as in the above snippet)? I have observed some developers treating NPE as evil, often trying to find out defensive ways to mask it and cover it up with some custom exception. Is this masking really required ?
Question
- Doesn't it makes sense to allow our code to fail through an NPE if we cannot recover from that null state? (In the example above, it's an irrecoverable scenario it seems.)
- If not, why?