Sundar Rajan
Sundar Rajan

Reputation: 596

Is there any Java Functional approach to avoid cascaded NonNull Checks

I have gone through several null check related questions in Java and the best practices around it. After long search , I can see Objects.nonNull () serves the purpose though it looks Orange instead of Apple.

Now i have a following check using Objects.nonNull() and short-circuiting logical AND.

if (Objects.nonNull (obj1) &&
    Objects.nonNull (obj1.getObj2()) &&
    Objects.nonNull (obj1.getObj2().getObj3 ())
{
    obj1.getObj2().getObj3().doSomething();
}

I find it is more redundant and less readable when i clearly know my intention.

Is there any other approach to handle it in functional way to assert the non null state of the deeper object without facing Null pointer exception.

Upvotes: 0

Views: 489

Answers (1)

khelwood
khelwood

Reputation: 59112

Using !=null is the normal way to do null-checks, but here's an alternative way that allows you to chain them using Optional.

Optional.ofNullable(obj1).map(class1::getObj2)
                         .map(class2::getObj3)
                         .ifPresent(class3::doSomething);

and you can use a lambda expression in place of any of the method references if the code you want to execute is not a simple function call.

Optional.ofNullable(obj1).map(x -> x.getObj2())
                         .map(x -> x.getObj3())
                         .ifPresent(x -> {
                             System.out.println("Now I can use my obj3 "+x);
                         });

Upvotes: 3

Related Questions