Java: Optional.isPresent() is not the best usage of Optional


Using the Optional class from Guava or JDK8?

The TL;DR: If you’re using isPresent(), you’re not taking full advantage of Optional.

Optional allows one to explicitly state that a variable may not have a value rather than relying on comments/code convention and null values.

It provides a number of helpers for constructing Optional items. Optionals are basically a wrapper around an object, and can either be ‘absent’ or ‘present’.

Optional provides an ‘isPresent’ method, but if you’re using it, you aren’t taking full advantage of Optional. Using isPresent isn’t really any different than using {var} != null from a coding perspective.

The Guava Optional provides several methods for retrieving items. If you know it will always have a value (likely due to previous checks), you can use get().

If you’re not sure if it will have a value or not, and want the default returned to be null, use orNull(). There is also an or(defaultValue) that will return defaultValue if it isn’t defined and an or that will return a different Optional value.

The JDK8 version of this is more powerful, but this at least gets one started. Here’s a great post about the JDK8 Optional: