I'm working with a legacy application where I often have to access properties deeply nested like that:
a.getB().getC().getD().getE().getF()
The problem is that it's possible that in any depth, the value could be null. Of course I could check each depth like that:
public Optional<F> retrieveValue(A a) {
if(a != null && a.getB() != null && a.getB().getC() != null &&
a.getB().getC().getD() != null &&
a.getB().getC().getD().getE() != null &&
a.getB().getC().getD().getE().getF() != null) {
return Optional.of(a.getB().getC().getD().getE().getF());
} else {
return Optional.empty();
}
}
F existingOrCreated = retrieveValue(a).orElse(new F());
But I have to do this in many places for many different objects so the code gets bloated with these checks. Mostly the objects are non null but there are some rare cases where objects are null. Is there a way to do it in a more concise way? I'm using Java 8 but I can't update the legacy code provided.