Monday, February 10, 2014

No Null Checks: Common Null Argument Checker

I want to fail fast when arguments passed into my method are null.
Use a common null check method to fail fast when input arguments are null.


This example is explicitly checking if the employee instance and throwing the NullPointerException to quickly fail the method call.

There are several utility classes that can implement this logic for you.  Both Java 8 and Google Guava include an Objects class that encapsulates and exposes this logic in different ways.

However, my preferred solution is to use the Lombok framework's @NonNull annotation. If you are not using Lombok get on-board…and stop bellyaching about how Java is so verbose!

This is what it looks like:

With this annotation if the generatePaycheck is invoked with a null employee reference a NullPointerException is thrown.

With the Java 8 Objects class the following checks are possible. Note, I did a static import on the Objects class - I believe this improves the readability of the code.

Don't make these checks a default for every method. Review where you put these types of checks in your code. I have seen teams go overboard, checking for nulls at every turn.

If it is a private method do you really need the null check?
Why are you processing null references in the first place?

No comments:

Post a Comment