0

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.

Sundar Rajan
  • 556
  • 4
  • 25
  • Why are you using `Objects.nonNull` instead of `!=null` ? – khelwood Jul 23 '20 at 07:57
  • Does [this](https://stackoverflow.com/questions/3458451/check-chains-of-get-calls-for-null) answer your question? – Sweeper Jul 23 '20 at 08:01
  • Why not use `Optional`? It's slightly more verbouse but still not THAT bad `Optional.ofNullable(obj1).map(o -> o.getObj2()).map(o -> getObj3()).ifPresent(o -> o.doSomething())` – VLAZ Jul 23 '20 at 08:01
  • @khelwood https://stackoverflow.com/questions/17302256/best-way-to-check-for-null-values-in-java – Sundar Rajan Jul 23 '20 at 08:01

1 Answers1

3

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);
                         });
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 1
    Just for completeness' sake - if a default value is needed, then `orElse` and `orElseGet` and `ifPresentOrElse` can work. If not having something is a problem, then `orElseThrow` can be used. – VLAZ Jul 23 '20 at 08:10