How to avoid null pointer

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 an Option. Always access Options using map or flatMap, the for 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:

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 NullPointerExceptions.
  • Your code will be safer.
  • You won’t have to write if statements to check for null 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 a None instead of a Some[T]. This is a much better approach than returning null 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.

Leave a Reply

Your email address will not be published. Required fields are marked *