If I get a NullPointerException in a call like this:
someObject.getSomething().getSomethingElse().
getAnotherThing().getYetAnotherObject().getValue();
If you find yourself often writing:
a.getB().getC().getD().getE();
this is probably a code smell and should be avoided. You can refactor, for example, into a.getE()
which calls b.getE()
which calls c.getE()
which calls d.getE()
. (This example may not make sense for your particular use case, but it's one pattern for fixing this code smell.)
See also the Law of Demeter, which says:
Therefore, one should not have a chain of messages, e.g. a.getB().getC().doSomething()
. Following this "law" has many more benefits apart from making NullPointerExceptions easier to debug.