Scala’s simple strategy to reduce debugging costs: “Some” and “None”
Null Pointer Exceptions (NPEs) are most common runtime errors in Java (more than 500.000 results in Google). Most Java libraries are interspersed with methods returning null if the computation could not be finished. Invoking method calls on null raises Null Pointer Exceptions.
The best practice in Java to avoid such errors is a test against null.
if(aObject == null) {...
or pass the null test to another function.
For example, Instead of writing:
if(aResultString.equals(“literal”)) {
...
you write:
if(“literal”.equals(aResultString)) {
...
More than eleven years ago (beginning with the java era) a data type existed, avoiding the NPE problem:
data Maybe a = Nothing | Just a deriving (Eq, Ord, Read, Show)
A Haskell one-liner ported to Java could have prevented thousands of errors.
Why?
You cannot forget to test against None (unlike the null check) because this would raise a compile time error. Based on Haskells Maybe-Type, Scala defines the Some and None Type with:
final case class Some[+A](x: A) extends Option[A] ...
and
case object None extends Option[Nothing] ...
To test an Option Type against None you write:
val result = a getOrElse b..
If a is Some(_) than result is _. If result is None, than result is b. The value of result is therefore always defined!
Runtime Errors on my News Page Kungle.de so far
To Keep it short:
None
Tags: Kungle.de, Lift, Programming, Scala
August 10th, 2009 at 2:45 pm
If you’re curious, Scala’s “Option, Some, None” comes from the ML family which uses “option, SOME, NONE” (http://www.standardml.org/Basis/option.html). Haskell is actually the odd one out by using Maybe, Just, Nothing.
August 11th, 2009 at 8:46 pm
There are multiple interesting ways to attack this problem. Scala’s is elegant. Groovy handles this in part with an interesting solution: the ?. operator for dereferencing. It performs the dereference only if the element is not null.