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()>
As already stated, the true solution is refactoring.
In the meantime, you could just wrap your first workaround in a function:
static D getD(MyClass obj) {
try {
return obj.getA().getB().getC().getD();
}
catch (NullPointerException e) {
return null; // Or even better, some default D
}
}
At the caller site:
D d = getD(obj);
At least you don't have to trash the caller with try-catch blocks. You still need to handle the errors somehow, when some of the intermediate getX()
call returns a null
and so d
becomes null.
The best would be to return some default D
in the wrapper function.
I don't see how the two options you list at the end of your question would help if any of the intermediate getX()
returns a null; you will get a NullPointerException
.