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 comments:

Post a Comment