Eliminating NullPointerExceptions in Method Chains

How to avoid NullPointerException in chained get calls? If you are looking for an answer to this question, you are in the right place.

Uğur Taş
Codimis

--

Chained Method Calls in Java: Navigating the Null Pointer Minefield

If you want to have a reliable code base, the first thing you need to do is try to avoid NullPointerException and handle possible NullPointerExceptions gracefully. Sometimes this is difficult to do because avoiding NullPointerException can make your code base ugly, decrease the reliability of the code, etc.

In this article, I will mention the ways to avoid and handle possible NullPointerExceptions in chained method calls. I hope this article helps you to increase the code quality of your project.

If you don’t have a medium membership, you can use this link to reach the article without a paywall.

Let's first identify the issue. When we have lots of nested objects and want to reach a specific value, we need to make many get calls to retrieve the value. Consider below example,

--

--

Uğur Taş
Codimis

A software developer with a high passion for learning, improving skills, and sharing knowledge. My motto is “fail million times if you take lessons every time”