In code we have got a lot of chain methods, for example obj.getA().getB().getC().getD()
. I want to create helper class which will check if method getD()
isn't null, but before that I need to check all previous getters. I can do it in this way:
try {
obj.getA().getB().getC().getD();
}
catch (NullPointerException e) {
// some getter is null
}
or (which is "silly")
if (obj!null && obj.getA()!=null && obj.getA().getB()!=null && ...) {
obj.getA().getB().getC().getD();
}
else {
// some getter is null
}
I don't want to check it every time using try{} catch()
in my code. What is the best solution for this purpose?
I think that the best will be:
obj.getA().getB().getC().getD().isNull()
- for this purpose I will need to change all of my getters, for example implement some interface which containsisNull()
method.NullObjectHelper.isNull(obj.getA().getB().getC().getD());
- this will be the best (I think so) but how to implement this?