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.
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.
 
No comments:
Post a Comment