Tom McAdam

minimalist java: maybe is optional

A while back I talked about Minimalist Java and touched on the functional aspects of Guava we use. Today I’m going to write about another feature we’ve borrowed from a functional language.

to null or not to null

Say I’m calling someone else’s code in Java, which has a method with this signature:-

public Foo getFoo();

As a caller of this method I know that it may return a reference to an instance of a Foo object. It could, of course, also return null. So we may need to cope with that eventuality in our code, or deal with the consequences of a NullPointerException.

The author of the method may have been kind enough to document whether I can expect a null to be returned but that may give a false sense of security: what if they document it then change the behaviour (and maybe the documentation) later on?

maybe, just maybe

So, a couple of years ago, John added the Maybe class to our codebase, inspired by Maybe in Haskell and Nat Pryce’s implementation in Java. It fixes all my problems above by being able to declare whether to expect null values returned.

another option

I’ll not waste any time talking about our implementation in detail because in Guava 10, the Optional type was born. It has a couple of small advantages over our implementation so we’re gradually moving over to it within our codebase.

So, without further ado, let’s rewrite that example above:-

import com.google.common.base.Optional;
...
public Optional<Foo> getFoo();

Of course, there’s nothing stopping getFoo from returning null, but it would be very antisocial of it to do so!

I now know that getFoo() may or may not return Foo, and I’m forced to think about it when using the return value:-

    Optional<Foo> possibleFoo = f.getFoo();
    if(possibleFoo.isPresent()) {
       Foo foo = possibleFoo.get()
       ...
    }
    else {
        // handle no value
    }

I can make the above simpler by using Optional.or() to use a default value, e.g.

    Optional<Foo> possibleFoo = f.getFoo();
    Foo foo = possibleFoo.or(new Foo())

And I can chain Optionals together with or to get the first Optional that is set in a chain.

growing guava


We keep a close eye on what’s coming up in the near future in Guava. There are lots of new features in every release, the RateLimiter and Striped will be welcome additions in Guava 13!

blog comments powered by Disqus