3

In java is there a way to avoid having to nest null checks on each level of the call to ensure there were no nulls along the way which prevent the next call. Is there an elegant way to do this?

for example:

objOne.objTwo.objThree.objFour.objFive

if(objOne.objTwo!=null){
    if(objOne.objTwo.objThree!=null){
      if(objOne.objTwo.objThree.objFour!=null){
            ...
   }
  }
}
  • Do you know about class [Optional](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html)? – Abra Dec 08 '19 at 07:40
  • @Abra, and how is `Optional` suppose to help in this context? – Sharon Ben Asher Dec 08 '19 at 07:41
  • This [article](https://www.oracle.com/technical-resources/articles/java/java8-optional.html) may be relevant. – Abra Dec 08 '19 at 07:46
  • @Abra, that doesn't help at all. `Optional` is **not** meant to replace every not null condition in Java. I guess you could create an `Optional.ofNullable()` out of every nested object. that would make the code much less comprehensible . – Sharon Ben Asher Dec 08 '19 at 07:50
  • It is a matter of debate as to whether `Optional` helps or not. But it is the only thing that could help ... apart from redesigning the data structure to eliminate the nulls as acceptable values. – Stephen C Dec 08 '19 at 07:53

2 Answers2

3

you can collapse the nested if statements into one, using short circuit logic. the first false condition will exit the if statement

if (objOne.objTwo != null && objOne.objTwo.objThree != null && objOne.objTwo.objThree.objFour != null) {
           ...
}
Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47
0

Invert them. (Replace Object with actual types.)

Object item1 = objOne.objTwo;
if (item1 == null)
   return; // continue if in a loop

Object item2 = item1.objThree;
if (item2 == null)
   return;

Object item3 = item2.objFour;
if (item3 == null)
   return;

// perform the action

This assumes there is no further action required beyond the end of your example. In that case you may have to extract a method or some other modification, but there is no such additional code given at the moment.

Dave Cousineau
  • 12,154
  • 8
  • 64
  • 80