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.