Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid nested null checks [duplicate]

Tags:

java

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){
            ...
   }
  }
}
like image 790
Bilal Shehata Avatar asked Oct 16 '25 14:10

Bilal Shehata


1 Answers

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) {
           ...
}
like image 169
Sharon Ben Asher Avatar answered Oct 18 '25 02:10

Sharon Ben Asher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!