Created
November 8, 2016 15:36
-
-
Save pulse00/09332dd5f8df5878243b56465f3f330a to your computer and use it in GitHub Desktop.
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
// java < 8 | |
if (document != null && document.getOrder() != null && document.getOrder().getAddress() != null && document.getOrder().getAddress().getStreet() != null) { | |
// boom | |
) | |
// java >= 8 | |
Optional<Street> street = resolve(() -> document.getOrder().getAddress().getStreet()); | |
if (street.isPresent() { | |
street.get(); | |
} else { | |
// boom | |
} | |
public static <T> Optional<T> resolve(Supplier<T> resolver) { | |
try { | |
T result = resolver.get(); | |
return Optional.ofNullable(result); | |
} | |
catch (NullPointerException e) { | |
return Optional.empty(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks to http://winterbe.com/posts/2015/03/15/avoid-null-checks-in-java/