Java Optional

I’ve used the various @Nullable and @NotNull annotations available but I’ve never been thrilled with them. They are confused through the various competing versions and they a stopgap solution.  These warn you when you’re about to get yourself in trouble but they don’t offer any improvements on handling the possible situations, you still need to add the boilerplate code.

For my coding style, Optional implementations offer a much nicer solution.  The contract with an optional is as clear as any of the annotations, and they provide support methods that help reduce the boilerplate code.

That said, there are competing implementations of Optional too, and they are not all created equal.  Java 1.8 has a good one, as does Guava, and I’ve included one in almost-functional.

A good optional needs some variant of:

    Optional<T> filter(Predicate<? super T> predicate)
    
  • If a value is present, and the value matches the given predicate, return an Optional describing the value, otherwise return an empty Optional.
  • <T> orElseSupplier(Supplier<T> other)
    
  • Return the value if present, otherwise get the value from the Supplier.
  • <T> orElseThrow(String msg)
    
  • If optional is not empty return it’s value, if empty throw a NoSuchElementException with message. This gives the Optional some of the behavior of a Try.

These sorts of methods remove all the boilerplate code to handle non null comparisons, lookup a value on null, and throwing an exception when you get a null.

Consider:

String filename = args[0];
if (filename == null) {
   throw new NoSuchElementException("Requires filename");
}

Versus:

String filename = ofNullable(args[0]).orElseThrow("Requires filename");
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s