Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid Nested null check

I want to retrieve the field from API which present inside classes. Yes I know this is against Law of Demeter but I don't have any option.

Example

getClassA().getClassB().getClassC().getClassD().getAccountId();

So to add null check as its bad code smell so I come with below code:

try{
getClassA().getClassB().getClassC().getClassD().getAccountId();
}catch(NullPointerException ex){
 S.O.P("Null Found");
}

or

ClassA a = getClassA();
if(a!=null){
ClassB b = a.getClassB();
So on.....
}

my question is which is best approach the above mentioned one or explicitly retrieve each class and check null and go to next level This is against Law of Demeter

like image 308
user2387280 Avatar asked Sep 18 '26 06:09

user2387280


1 Answers

Null Object design pattern is the way to which is being absorbed in Java 8 via Optional class which means you have a wrapper within which either you have the data or you have empty data.

Its something like

             MyObject
      RealObject    NullObject

Where instead of passing null, you pass NullObject which provides the same interface as MyObject (which can be concrete/abstract/interface class)

like image 87
SMA Avatar answered Sep 20 '26 19:09

SMA



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!