There are some patterns for checking whether a parameter to a method has been given a null
value.
First, the classic one. It is common in self-made code and obvious to understand.
public void method1(String arg) { if (arg == null) { throw new NullPointerException("arg"); } }
Second, you can use an existing framework. That code looks a little nicer because it only occupies a single line. The downside is that it potentially calls another method, which might make the code run a little slower, depending on the compiler.
public void method2(String arg) { Assert.notNull(arg, "arg"); }
Third, you can try to call a method without side effects on the object. This may look odd at first, but it has fewer tokens than the above versions.
public void method3(String arg) { arg.getClass(); }
I haven't seen the third pattern in wide use, and it feels almost as if I had invented it myself. I like it for its shortness, and because the compiler has a good chance of optimizing it away completely or converting it into a single machine instruction. I also compile my code with line number information, so if a NullPointerException
is thrown, I can trace it back to the exact variable, since I have only one such check per line.
Which check do you prefer, and why?
In order to check whether a Java object is Null or not, we can either use the isNull() method of the Objects class or comparison operator.
In Java, the java. lang. NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.
It is generally a bad practice to catch NullPointerException. Programmers typically catch NullPointerException under three circumstances: The program contains a null pointer dereference. Catching the resulting exception was easier than fixing the underlying problem.
It is a good idea to check for null explicitly because: You can catch the error earlier. You can provide a more descriptive error message.
Approach #3: arg.getClass();
is clever, but unless this idiom see widespread adoption, I'd prefer the clearer, more verbose methods as opposed to saving a few characters. I'm a "write once, read many" kind of programmer.
The other approaches are self-documenting: there's a log message you can use to clarify what happened - this log message is use when reading the code and also at run-time. arg.getClass()
, as it stands, is not self-documenting. You could use a comment at least o clarify to reviewers of the code:
arg.getClass(); // null check
But you still don't get a chance to put a specific message in the runtime like you can with the other methods.
Approach #1 vs #2 (null-check+NPE/IAE vs assert): I try to follow guidelines like this:
http://data.opengeo.org/GEOT-290810-1755-708.pdf
Use assert
to check parameters on private methodsassert param > 0;
Use null check + IllegalArgumentException
to check parameters on public methodsif (param == null) throw new IllegalArgumentException("param cannot be null");
Use null check + NullPointerException where neededif (getChild() == null) throw new NullPointerException("node must have children");
HOWEVER, since this is question may be about catching potential null
issues most efficiently, then I have to mention my preferred method for dealing with null
is using static analysis, e.g. type annotations (e.g. @NonNull
) a la JSR-305. My favorite tool for checking them is:
The Checker Framework:
Custom pluggable types for Java
https://checkerframework.org/manual/#checker-guarantees
If its my project (e.g. not a library with a public API) and if I can use the Checker Framework throughout:
I can document my intention more clearly in the API (e.g. this parameter may not be null (the default), but this one may be null (@Nullable
; the method may return null; etc). This annotation is right at the declaration, rather than further away in the Javadoc, so is much more likely to be maintained.
static analysis is more efficient than any runtime check
static analysis will flag potential logic flaws in advance (e.g. that I tried to pass a variable that may be null to a method that only accepts a non-null parameter) rather than depending on the issue occurring at runtime.
One other bonus is that the tool lets me put the annotations in a comment (e.g. `/@Nullable/), so my library code can compatible with type-annotated projects and non-type-annotated projects (not that I have any of these).
In case the link goes dead again, here's the section from GeoTools Developer Guide:
http://data.opengeo.org/GEOT-290810-1755-708.pdf
5.1.7 Use of Assertions, IllegalArgumentException and NPE
The Java language has for a couple of years now made an assert keyword available; this keyword can be used to perform debug only checks. While there are several uses of this facility, a common one is to check method parameters on private (not public) methods. Other uses are post-conditions and invariants.
Reference: Programming With Assertions
Pre-conditions (like argument checks in private methods) are typically easy targets for assertions. Post-conditions and invariants are sometime less straighforward but more valuable, since non-trivial conditions have more risks to be broken.
Use Assert to check Parameters on Private methods
private double scale( int scaleDenominator ){ assert scaleDenominator > 0; return 1 / (double) scaleDenominator; }
You can enable assertions with the following command line parameter:
java -ea MyApp
You can turn only GeoTools assertions with the following command line parameter:
java -ea:org.geotools MyApp
You can disable assertions for a specific package as shown here:
java -ea:org.geotools -da:org.geotools.referencing MyApp
Use IllegalArgumentExceptions to check Parameters on Public Methods
The use of asserts on public methods is strictly discouraged; because the mistake being reported has been made in client code - be honest and tell them up front with an IllegalArgumentException when they have screwed up.
public double toScale( int scaleDenominator ){ if( scaleDenominator > 0 ){ throw new IllegalArgumentException( "scaleDenominator must be greater than 0"); } return 1 / (double) scaleDenominator; }
Use NullPointerException where needed
If possible perform your own null checks; throwing a IllegalArgumentException or NullPointerException with detailed information about what has gone wrong.
public double toScale( Integer scaleDenominator ){ if( scaleDenominator == null ){ throw new NullPointerException( "scaleDenominator must be provided"); } if( scaleDenominator > 0 ){ throw new IllegalArgumentException( "scaleDenominator must be greater than 0"); } return 1 / (double) scaleDenominator; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With