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?
@Nonnullannotations on the parameters that I expect not to benullor methods if they do not returnnull. The@Nonnullannotation is not available by default, but supported by many IDEs (e.g., intelliJ). You have to addcom.google.code.findbugs.annotationsto your dependencies though. With that, the IDE is able to warn you, e.g., if there is a chance that you pass innullinto a method which is annotated. It also helps others to understand that you don't expect anullat this point.