"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > ## Are Optional Chains the Key to Eliminating NullPointerExceptions in Chained \"Get\" Calls?

## Are Optional Chains the Key to Eliminating NullPointerExceptions in Chained \"Get\" Calls?

Published on 2024-11-15
Browse:844

## Are Optional Chains the Key to Eliminating NullPointerExceptions in Chained \

Safely Navigating Chains of Null-Prone "Get" Calls

In complex codebases, chaining multiple "get" calls can become a breeding ground for NullPointerExceptions. To safeguard against potential null values, developers often resort to verbose null checks for each intermediate object.

But is there a more elegant and efficient way to handle such scenarios?

Optional Chains

With Java 8's Optional class, we have an elegant solution known as optional chains. Optional wrapping allows us to gracefully handle nulls by returning an Optional value instead of a raw T.

Optional chains allow you to seamlessly execute a series of get calls, mapping each to an optional value. Null checks are handled internally, ensuring that subsequent operations are performed only if the previous ones return non-null values.

For instance, consider the following chain of "get" calls:

house.getFloor(0).getWall(WEST).getDoor().getDoorknob();

To avoid NullPointerExceptions, you can use the following null checks:

if (house != null && house.getFloor(0) != null && house.getFloor(0).getWall(WEST) != null && house.getFloor(0).getWall(WEST).getDoor() != null) ...

However, using optional chains, you can simplify this to:

Optional.ofNullable(house)
    .map(h -> h.getFloor(0))
    .map(floor -> floor.getWall(WEST))
    .map(wall -> wall.getDoor())
    .map(door -> door.getDoorknob());

Sample Usage

Let's illustrate the power of optional chains with an example:

System.out.println("----- Not Initialized! -----");

Optional.ofNullable(new Outer())
    ... // Omitted chain of optional maps
    .ifPresent(foo -> System.out.println("foo: "   foo)); //no print

System.out.println("----- Let's Initialize! -----");

Optional.ofNullable(new OuterInit())
    ... // Omitted chain of optional maps
    .ifPresent(foo -> System.out.println("foo: "   foo)); //will print!

In this example, when objects are initialized, the optional chain gracefully handles nulls, resulting in a successful print. Without optional chains, a NullPointerException would have occurred.

Optional chains not only simplify null handling but also improve code readability and maintainability. By leveraging Optional, you can safely navigate chains of "get" calls, reducing the burden of explicit null checks and enhancing the overall robustness of your codebase.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3