If you already use Option, Maybe or Optional in your code then move along please – nothing to see here. Otherwise here’s a neat trick you have been missing out on…
The Null Object Refactoring / Pattern
Examine the code below. All seems fine, unless the call to ‘buildPaycheck’ can return null, in which case we need to insert a conditional to check the return value.
Some code which may require a check for null
We can avoid this by applying Null Object. Specifically we define a class that extends from Paycheck and define its behaviour so that it will pass through our code without causing any side-effects:
A ‘NullPaycheck’ implementation
This works well in some scenarios, but in practice we cant define a null type for every hierarchy that is guaranteed to have no effect on the calling code. For example a printPaychecks method would still print a wage of 0.0 for certain Employees.
The solution is to return a collection, where that collection is a set of zero or one Paycheck objects. We refer to a set of size 1 as a Some and a set of size zero as a None. This is known as the Option Monad.
To get a handle on Option examine the Scala classes below. We have a Person class with a findAddress method, an Address class with a findPostcode method and a Postcode class with a findValue method. Instead of these methods returning null they return an Option of T.
As mentioned above Option is best thought of as a set of size 0 or 1. The None type represents an Option of size 0, whereas a Some(T) represents an Option of size 1.
Simple Scala classes with methods returning Option
Because the methods all use Option we can chain the calls together using the syntax below, knowing that the chain will halt if any call returns None. Note the same syntax can be used to combine other constructs that count as Monads.
How to chain Scala methods that return an Option
Simulating the Option Monad in C# via LINQ
In the .NET world F# developers have the same feature, but under the name of the Maybe Monad. It is not natively supported in C#, but you can define your own Option hierarchy and then integrate it with the LINQ syntax (as below). For more details see Mike Hadlow’s excellent series of blog posts.
Implementing a Class Hierarchy for Option in C
Scary infrastructure required to make the Option type work with LINQ
Chaining C# method calls that return an Option via LINQ
The Optional Type in Java 8
Historically Java has not had an option-like concept, although libraries like Guava have tried to provide one. However Java 8 includes an Optional class similar to those discussed. Lets look at an example.
The fetchSystemProperty method below attempts to find the JVM property with the provided name. If the property exists we return an Optional of 1 and an empty Optional otherwise. The caller can:
Execute arbitrary code by invoking isPresent with a lambda or method reference
Supply a default value by invoking orElse
It’s great to now have a standardised Option type in the language, but without language support for Monads or an (official) LINQ-like library its not as useful. But that doesn’t mean you shouldn’t be using it. For example we can integrate it easily into the initial example:
Of course what we would really like to be able to do is something like:
But sadly this is not possible since, as with inner and anonymous inner classes, only final or ‘effectively final’ variables can be used in lambdas.
The Option(al) concept is more versatile than the Null Object Pattern / Refactoring and ‘surfaces’ the problem of null values in your code. Used correctly it can drastically reduce the number of NullPointerExceptions in your code, which has to be a good thing :-)