Monday, February 10, 2014

No Null Checks: Use Optional

I have a method that can return a null value.

Use the return type of Optional to let callers know they need to handle absent values.


In this example the null check is needed because the city code may not exist in the repository.

However, it is not clear from the findCity method that a null could be returned.  

When it is possible for a null to be returned from a method use an Optional wrapper class to let the caller know what to expect and that they need to handle the case where the value is absent.

The optional class contains the instance that can be null and offers several convenience methods to elegantly handle the null condition.  Java 8 users should use the java.util.Optional version - since it is integrated into the various Java 8 APIs.  For other users there is a version in the Google Guava framework. 

Refactoring the null check example results in the following new implementation.

By returning Optional from the findCity method we are explicitly letting callers know that we might not find the city based on the code. There are a lot of interesting methods you can use on Optional to deal with missing values - here are a couple to get you started.

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 Null Checks: Use firstNonNull method

When a reference is null I need to use a default value.
Use a common method to encapsulate selecting the first non null value.


In this example I am getting a package quantity for a product.  Since the data is not perfect, I use either the quantity, inner pack quantity or a default.  Since this method is in a domain object this is the only place this logic lives.

There are several firstNonNull methods you can use.  The one below is from apache commons and uses a variable argument parameter - so you can pick between many fields for the first non null value.  The one downside is that it returns null if all the values are null.  Be use to include a constant default in the group.


Another option is to roll your own utility method using lambdas.

The findFirst function returns an instance of Optional. The terminating get method call is on the Optional and throws a NoSuchElementException if all the arguments are null.

No Null Checks: Use Optional and supplier functions

I need to call a getter on an instance that might be null.
Use Optional and supplier functions to navigate an object chain that may contain nulls.

Here I am trying to return the Street portion of an Employee's address.  If anything is missing I will use an empty string as the Street name.  But I need to check for nulls at every turn.  This results in a nasty triple nested null check.

This is a common pattern, other languages have a null safe getter construct that can be used.  Groovy has the elvis operator - ?. that will simply return a null.

With Java 8 you can use the Optional class with the map method to navigate the object chain.

Simply chaining these map calls together and using the method literal you can safely navigate this object chain. The revised method is significantly less complicated - which is a good thing.

No Null Checks: Use Comparator null handling

I need to sort on a field that could be null in some object instances.  Use Comparator null handling to compare instances that can be null.

In this compareTo method I have some employees without middle names.  So, if the first and last name are the same the sort will take into account the middle name - which could be null :-(

I'm going to clean-up this method by using the Comparator class from Java 8.

The Comparator defines a fluent interface that is used to build a comparator for multiple members of a class.  The secret sauce is the easy way it sorts nulls before or after non-null values - when both instances are null they are considered equal.

This update creates a separate comparator instance that is then used in the compareTo method. The null check is tucked away neatly within the Comparator.nullsFirst method. Also note the use of method literals to define the members of the Employee classes used for the compare.

I'm a recovering null checker...

That is right, in the past I explicitly checked references to see if they are null…yea, I still have lapses, I try to avoid it - null checks are insidious in a Java code base; and by insidious I mean:
  1. Are harmful but enticing.
  2. Hey, I got a null pointer exception (NPE) when running this test. Hmm, not sure if the data is right…oh well I can just add a null check here. The check will ensure the problem will not occur again.

  3. Spread harmfully, in a subtle or stealthy manner.
  4. Similar to other types of broken windows in a code base one null check begets another. Everything starts to be confusing…
    This variable was checked for null in this method so if I pass it to this method I need to check for null here as well. Quickly you have the problem of accidental, not real complexity.

  5. Have a gradual and cumulative negative effect.
  6. Individually they are not a big deal. Sure, it is not clear if it is an expected condition or just a enticing precaution someone coded. But, at some point the complexity null checks add to a codebase are over-whelming and they are a common theme in many bugs.
So, are Java null checks evil? Often they are (or at least a bad idea) and you need an approach (or two) to dealing with null values in your coding efforts.

I've been seeking better ways to deal with nulls for a while. This series of blogs distills these ideas into a catalog of approaches.  Please leave feedback if you think I've missed one or you know a better way.


I have a instance of a class that might be missing, in which case the reference is null.

In this example when the employee's jobRole is unassigned we say he is not due for a raise.  So, jobRole can be null. Now, to not get into trouble, everywhere we reference jobRole it needs to include null check. Obviously it is not DRY and the business rules for an unknown jobRole is strewn all over your codebase.

Fix; create a instance of the object to use when you are missing the item - known as the NullObject pattern.

Use the NullObject pattern in place of null checks.



I have a method that can return a null value. 

In this case we simply might have bad data or the repository has not been updated with a new city.

It doesn't seem bad for a validate method to check for null but what about other calls to the findCity method?

Hopefully callers will know to check for null - I'll just put it in the java docs ;-)

Use the return type of Optional to let callers know they need to handle absent values.

I want to fail fast when arguments passed into my method are null. 

Yep, very common - let us fail quickly not 5 frames into this method where it could be difficult to see the employee was null from the start.

Of course there is a better way to encapsulate this idea.


When a reference is null I need to use a default value.

In this example I'm getting a package quantity for a product.  I need to use the first non-null value either quantity, inner pack quantity or a default value.

I need to call a getter on an instance that might be null.

Here I am trying to return the Street portion of an Employee's address.  If anything is missing I will use an empty string as the Street name.  But I need to check for nulls at every turn.  This results in a nasty triple nested null check.


I need to sort on a field that could be null in some object instances.

In this compareTo method I have some employees without middle names.  So, if the first and last name are the same the compare will take into account the middle name - which could be null :-(

Yes, this is an ugly compareTo implementation - there are various utility methods that can be used to improve it - I'm going to use the Java 8 API.