cft

How to escape NullPointerExceptions in Java using Optional

How to escape NullPointerExceptions in Java using Optional


user

Abdulcelil Cercenazi

3 years ago | 2 min read

What is Optional? 🤔

According to Oracle: "A container object which may or may not contain a non-null value."

Why use it? 👀

it was introduced in Java 8 to enable us to elegantly handle the Null pointer exception problem.

How?

Let's first start by learning how variables in Java are handled in memory and what NullPointerException means.

In java variables can be one of two types:

  • Primitives
    • They are 8 types (int, char, etc...)
    • They are saved in the execution stack of the current method.
    • Fast info: each method call has its own execution stack.
  • Objects
    • They are instances of classes (User, Car, Integer)
    • They are saved in the Java Heap, however, references to them are saved in the execution stack of the current method as well.
    • Those references are saved into variables.

Where does null fit in the picture? 🖼️

If an object isn't referencing any value in the Heap, then its value is null.
When we try to do some operations using that variable we hit the famous NullPointerException.

How does the Optional help?

It wraps the objects we pass to the calling method, and it provides methods to handle the presence or absence of the null value in a clean code functional style.

Code time 🤖

As an example, let's say we have a Room class, which has a Desk, and that Desk has Pen Holder

First, let's look at some code that doesn't use the Optional class

Room 🏠

Desk 🗃

Pen Holder 🖊

A service that tells us what is the capacity of the Pen holder in a room, if exists. It has two methods, one that does a null check and another that doesn't

Now let's apply Optional and see the results

Room 🏠

Desk 🗃

Pen Holder 🖊

The service

The optional code is much more concise, clear, and clean. However, the most important side is that we got rid of the NullPointerException monster.

One thing to be careful of is to not return null instead of the Optional. 🔥

Where to use Optional?

There are a number of options for the place that we might use the Optional wrapper class, for example, wrap method parameters, local variables. However, the most suitable place is on method return types.

Conclusion

  • The Optional class is a wrapper that wraps objects that might not exist in the Heap (in other words that could be null).
  • It was created to reduce the possibility of facing a NullPointerException
  • This class has methods that help us write clean code.

Code 👩‍💻GitHub

Upvote


user
Created by

Abdulcelil Cercenazi

I love to learn and teach. Follow me for Software development/Clean coding topics :)


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles