DEV Community

Discussion on: Better Null-Checking in Java

Collapse
 
evanoman profile image
Evan Oman • Edited

How is your Nullable example different than using Option.ofNullable?

String zipCode = Optional.ofNullable(user)
                   .map(User::addresses)
                   .map(UserAddresses::billingAddress)
                   .map(Address::zipCode)
                   .orElse("..."); // or .orElse(null) or .get() w/ exception handling
Collapse
 
evanoman profile image
Evan Oman

Ahh, I missed the intermediary null checks, this is more accurate:

String zipCode = Optional.ofNullable(user)
                   .flatMap(user -> Optional.ofNullable(user.addresses()))
                   .flatMap(addresses -> Optional.ofNullable(addresses.billingAddress())
                   .flatMap(address -> Optional.ofNullable(address.zipCode())
                   .orElse("...");
Collapse
 
goyo profile image
Grzegorz Ziemonski

No, you didn’t. You can do it exactly as in your first example.

Thread Thread
 
redaalaoui profile image
Réda Housni Alaoui

I confirm, the first example works.

But besidd that, this goes against rule of Demeter.

You should not have to access so many indirect attributes to get the zip code. User should expose a getZipCode method.