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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With