Monday, February 10, 2014

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.

private String getEmployeeStreet(Long employeeId) {
Optional<Employee> employee = Optional.of(findEmployeeById(employeeId));
return employee.map(Employee::getAddress)
.map(Address::getStreet)
.orElse(EMPTY);
}
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 comments:

Post a Comment