Java Reference
In-Depth Information
It creates a hole in the type system. null carries no type or other information, meaning it can be
assigned to any reference type. This is a problem because, when it's propagated to another part of the
system, you have no idea what that null was initially supposed to be.
To provide some context for what other solutions are out there for this problem, let's briefly look
at what other programming languages have to offer.
10.1.3. What are the alternatives to null in other languages?
In recent years other languages like Groovy worked around this problem by introducing a safe
navigation operator , represented by ?., to safely navigate through potentially null values. To
understand how this works, consider the following Groovy code to retrieve the name of the
insurance company used by a given person to insure their car:
def carInsuranceName = person?.car?.insurance?.name
What this statement does should be pretty clear. A person might not have a car and you tend to
model this possibility by assigning a null to the car reference of the Person object. Similarly, a
car might not have insurance. The Groovy safe navigation operator allows you to safely navigate
through these potentially null references without throwing a NullPointerException, by just
propagating the null reference through the invocations chain, returning a null in the event that
any value in the chain is a null.
A similar feature was proposed and then discarded for Java 7. Somehow, though, we don't seem
to miss a safe navigation operator in Java; the first temptation of all Java developers when
confronted with a NullPointerException is to quickly fix it by adding an if statement, checking
that a value is not null before invoking a method on it. If you solve this problem in this way,
without wondering if it's correct that your algorithm or your data model could present a null
value in that specific situation, you're not fixing a bug but hiding it, making its discovery and fix
far more difficult for whoever will be called to work on it next time; it very likely will be you in
the next week or month. You're just sweeping the dirt under the carpet. Groovy's null-safe
dereferencing operator is only a bigger and more powerful broom for making this mistake,
without worrying too much about its consequences.
Other functional languages, such as Haskell and Scala, take a different view. Haskell includes a
Maybe type, which essentially encapsulates an optional value. A value of type Maybe can contain
either a value of a given type or nothing. There's no concept of a null reference. Scala has a
similar construct called Option[T] to encapsulate the presence or absence of a value of type T,
which we discuss in chapter 15 . You then have to explicitly check whether a value is present or
 
Search WWH ::




Custom Search