My problem is the following, I have quite a long Getter, i.e.,
objectA.getObjectB().getObjectC().getObjectD().getObjectE().getName();
Due to "bad" database/entity design (some things were introduced later than others) it happens that getObjectB()
, getObjectC()
or getObjectD()
could return NULL
.
Usually we use null-checks all the time, but in this case, I'd have to use
ObjectB b = objectA.getObjectB();
if (b != null) {
ObjectC c = b.getObjectC();
if (c != null) {
ObjectD d = c.getObjectD();
if (d != null)
return d.getObjectE().getName();
}
}
return "";
Instead it would be much easier to simply use a try-catch block
try {
return objectA.getObjectB().getObjectC().getObjectD().getObjectE().getName();
} catch (NullPointerException e) {
return "";
}
In this case I don't really care which object returned NULL, it's either display a name or don't. Are there any complications or is it bad design to use try-catch instead of checks?
Thanks for your input.