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.

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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private String getEmployeeStreet(Long employeeId) { | |
Optional<Employee> employee = Optional.of(findEmployeeById(employeeId)); | |
return employee.map(Employee::getAddress) | |
.map(Address::getStreet) | |
.orElse(EMPTY); | |
} |
No comments:
Post a Comment