How to avoid null pointer
The concept of Null Reference is sometimes referred to as “The Billion Dollar Mistake”. In keeping with modern best practices, you want to eliminate null
values from your code.
General rules about null and Option
We begin with the following general rules regarding the use of null values in Scala code:
- Ban
null
from any of your code. - If you’re using a Java library that returns
null
, convert the result to a Scala .
One important rule when working with an Option
:
- Never call the
get
method on anOption
. Always access Options usingmap
orflatMap
, thefor
expression, or pattern matching.
As you can infer by this statement, it’s important to note that Scala collection classes are created to work with Options. While using Option
with constructs like for comprehensions and match expressions are nice, an enormous benefit of using Option
is that they’re well supported by the methods of the collection classes.
Converting a null into an Option, or something else
The major place you’ll run into null
values is in working with legacy Java code. There is no magic formula here, other than to capture the null
value and return something else from your code. That may be an Option
, a Null Object, an empty list, or whatever else is appropriate for the problem at hand.
For instance, the following getName
method converts a result from a Java method that may be null
and returns an Option[String]
instead:
1 2 3 4 |
def getName: Option[String] = { var name = javaPerson.getName if (name == null) None else Some(name) } |
Following these guidelines leads to these benefits:
- You’ll eliminate
NullPointerException
s. - Your code will be safer.
- You won’t have to write
if
statements to check fornull
values. - Adding an
Option[T]
return type declaration to a method is a terrific way to indicate that something is happening in the method such that the caller may receive aNone
instead of aSome[T]
. This is a much better approach than returningnull
from a method that is expected to return an object. - You’ll become more comfortable using
Option
, and as a result, you’ll be able to take advantage of how it’s used in the collection libraries and other frameworks.