Java : When to skip null checks on an object?

Harshit :

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

  1. 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.)
  2. If not, why?
yshavit :

In cases like you posted, there's no benefit to the check. You're replacing one RuntimeException with another one, which has no extra information or value (and arguably a bit less to someone who's not familiar with your code, since everyone knows what an NPE is, and not everyone knows what your SomeRuntimeException is).

The main two times I'd consider an explicit check are:

  1. When I want to throw a checked exception instead of unchecked.
  2. When I want to check for the null before I actually use the reference.

The second case is especially important when I'm only going to be storing the reference for later: in a constructor, for instance. In that case, by the time somebody uses the reference and triggers the NPE, it may be difficult to find how that null got there in the first place. By checking for it right before you save it in a field, you stand a better chance of finding the root cause. In fact, this is a common enough pattern that the JDK even has a requireNonNull helper for it.

If you look at a lot of well-established, high-reputation projects, I think you'll find that the "just use it, and let an NPE happen if it happens" pattern is common. To take one example off the top of my head, the code for the JDK's Collections.sort is simply list.sort(null), where list is the method argument. If it's null, that line will throw an NPE.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=439344&siteId=1