Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is using libraries checking nulls better than getting NPE? [duplicate]

Sometimes I see developers using libraries like Guava’s Preconditions to validate the parameters for nulls in the beginning of a method. How is that different than getting NPE during runtime since a runtime exception occurs in either way?

EDIT: If there are good reasons, then shouldn't developers use libraries for null-check on all methods?

like image 733
Glide Avatar asked Jan 22 '15 19:01

Glide


2 Answers

Some reasons are:

  • Prevents code from being run prior to the first time the variable (which could be null) is de-referenced.
  • You can have custom error messages, such as "myVar was null, I can't proceed further", or any relevant message which will look better in logs and more easily traceable. A normal NPE would be less readable in logs.
  • Readability of code is better (arguably) because a programmer reading this code will realize immediately that these values are expected to be non-null.

Ultimately it's a matter of taste IMO. I have seen programs that are inherently null safe and don't require pre-conditions at all.

like image 146
Invisible Arrow Avatar answered Sep 28 '22 07:09

Invisible Arrow


There are various reasons. One big one, as mentioned in the comments, is to get the checking done up front before any work is done. It's also not uncommon for a method to have a code path in which a specific parameter is never dereferenced, in which case without upfront checking, invalid calls to the method may sometimes not produce an exception. The goal is to ensure they always produce an exception so that the bug is caught immediately. That said, I don't necessarily use checkNotNull if I'm going to immediately dereference the parameter on the next line or something.

There's also the case of constructors, where you want to checkNotNull before assigning a parameter to a field, but I don't think that's what you're talking about since you're talking about methods where the parameter will be used anyway.

like image 25
ColinD Avatar answered Sep 28 '22 08:09

ColinD