Better Null-Checking in Java

scottshipp on January 11, 2019

Photo by Estée Janssens on Unsplash Java runs some of the largest sites and platforms in the world but I’ve often struggled with its design as a l... [Read Full]
markdown guide

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

String zipCode = Optional.ofNullable(user)
                   .orElse("..."); // or .orElse(null) or .get() w/ exception handling

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())

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

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.


Tip: the first case, where null checks are used to handle resources, can usually be avoided by using a try-with-resources statement, available since Java 7. An example is available in the preceding section of the Java tutorial that is linked.


Nice post, mill is IMHO super useful library for Java programmers (for those who did not switch to Kotlin yet or maintaining legacy code written in Java :)).


I’m of the opinion that if you can’t sell switching to Haskell, then push for kotlin. It just makes writing JVM code more sane.

The only wackiness comes when you run into a library that is cheating with reflection to overcome the lack of sum or product types in Java. (I’M LOOKING AT YOU, GREMLIN!)


Ha, nice point, Jon,

to be fair, I have to admit that I'm Kotlin enthusiast...but still write much of my code in Java because of.....just because. I have a reasons for it.


And why not Groovy or Scala instead of Kotlin? TIOBE index shows Groovy(17 today used to be way below) getting way above Kotlin nowadays while the Kotlin gets lower (39 used to be about 35 I think).

Also I played with Kotiln and dislike it as do some other people that use JVM stuff not only me, so why would you assume Kotlin would be better choice?

I really need someone to explain to me what's so great about this language that Groovy or Scala couldn't provide. The only thing is Google and Android in my opinion.


Nice lib. I do miss ?. and ?? from C# in Java. But I also miss Micronaut/Spring in C# so it's a no brainer :D. Although good thing about JVM frameworks I can combine Groovy and Kotlin with Java to make some stuff have those operators :D.


Nice post!

I want to recommend you to look at Option<> monad in VAVR it's behavior is similar to the example of NullSafe.

code of conduct - report abuse