I have some (simplified) code that uses Java Optionals:
Optional<User> maybeTarget = userRepository.findById(id1); Optional<String> maybeSourceName = userRepository.findById(id2).map(User::getName); Optional<String> maybeEventName = eventRepository.findById(id3).map(Event::getName); maybeTarget.ifPresent(target -> { maybeSourceName.ifPresent(sourceName -> { maybeEventName.ifPresent(eventName -> { sendInvite(target.getEmail(), String.format("Hi %s, $s has invited you to $s", target.getName(), sourceName, meetingName)); } } }
Needless to say, this looks and feels bad. But I can't think of another way to do this in a less-nested and more readable way. I considered streaming the 3 Optionals, but discarded the idea as doing a .filter(Optional::isPresent)
then a .map(Optional::get)
feels even worse.
So is there a better, more 'Java 8' or 'Optional-literate' way of dealing with this situation (essentially multiple Optionals all needed to compute a final operation)?
Optional is a container object used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values.
Java 8 Optional ExampleOptional can minimize the number of null checks you do in your code by explicitly saying that value can be null and setting proper default values. If you're going to use null, consider the @Nullable annotation.
Accepting Optional as parameters causes unnecessary wrapping at caller level.
I think to stream the three Optional
s is an overkill, why not the simple
if (maybeTarget.isPresent() && maybeSourceName.isPresent() && maybeEventName.isPresent()) { ... }
In my eyes, this states the conditional logic more clearly compared to the use of the stream API.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With