Lately, I’ve seen a lot of talk about null come across my radar - mainly how it’s a big mistake (the “billion dollar mistake”) and should be avoided.
I saw this article on hacker-news today called “The Definitive Reference to why Maybe is better than Null.” The point is that using a “Maybe” construct requires the developer to think about what happens when there is no value. In languages that have null (like Java, Groovy and Scala), it makes it harder to have NullPointerException’s, but not impossible.
Maybe is much like Scala’s Option. It has two implementations (accessed using static methods); one representing an absence of value (Maybe.nothing()), and one wrapping a non-null value (Maybe.defititely(value)).
There is at least one implementation of Maybe in Java (by Nat Pryce). This Maybe also implements the Iterable interface so that multiple Maybe’s can be joined (using Guava’s concat method for example). This also allows for the following construct:
for (String value : maybeValue) doSomethingWith(value);
If you’re interested, I’ve made my own fork of Nat Pryce’s Maybe and deployed it to Maven central.
Guava also has the similar class, Optional. Optional also has static methods to create “absence” or “presence” of a value (Optional.absent() and Optional.of(value)).
The Java 8 standard lib will have a similar built-in Optional class that seems to take inspiration from both Maybe and guava.
As _why says somewhere is his recently “printed” manuscript, he was tired of “constantly fighting null.” Well, with Maybe, maybe you don’t have to ;-)