20.5. Eliminate null Values from Your Code

Problem

Tony Hoare, inventor of the null reference way back in 1965, refers to the creation of the null value as his “billion dollar mistake.” In keeping with modern best practices, you want to eliminate null values from your code.

Solution

David Pollak, author of the book Beginning Scala, offers a wonderfully simple rule about null values:

“Ban null from any of your code. Period.”

Although I’ve used null values in this book to make some examples easier, in my own practice, I no longer use them. I just imagine that there is no such thing as a null, and write my code in other ways.

There are several common situations where you may be tempted to use null values, so this recipe demonstrates how not to use null values in those situations:

  • When a var field in a class or method doesn’t have an initial default value, initialize it with Option instead of null.

  • When a method doesn’t produce the intended result, you may be tempted to return null. Use an Option or Try instead.

  • If you’re working with a Java library that returns null, convert it to an Option, or something else.

Let’s look at each of these techniques.

Initialize var fields with Option, not null

Possibly the most tempting time to use a null value is when a field in a class or method won’t be initialized immediately. For instance, imagine that you’re writing code for the next great social network app. To encourage people to sign up, during the registration process, the only information you ask for ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.