How to trace a NullPointerException in a chain of getters

后端 未结 11 1541
谎友^
谎友^ 2020-12-03 06:46

If I get a NullPointerException in a call like this:

someObject.getSomething().getSomethingElse().
    getAnotherThing().getYetAnotherObject().getValue();
         


        
11条回答
  •  [愿得一人]
    2020-12-03 07:45

    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:

    • Your method can call other methods in its class directly
    • Your method can call methods on its own fields directly (but not on the fields' fields)
    • When your method takes parameters, your method can call methods on those parameters directly.
    • When your method creates local objects, that method can call methods on the local objects.

    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.

提交回复
热议问题