Is it acceptable to use exceptions instead of verbose null-checks?

前端 未结 9 2445
刺人心
刺人心 2020-12-28 21:51

I recenly encountered this problem in a project: There\'s a chain of nested objects, e.g.: class A contains an instance variable of class B, which in turns has an instance v

9条回答
  •  灰色年华
    2020-12-28 22:22

    Using exceptions seem a poor fit here. What if one of the getters contained non-trivial logic, and threw a NullPointerException? Your code would swallow that exception without intending to. On a related note, your code samples exhibit different behaviour if parentObject is null.

    Also, there really is no need to "telescope":

    public Z findZ(A a) {
        if (a == null) return null;
        B b = a.getB();
        if (b == null) return null;
        C c = b.getC();
        if (c == null) return null;
        D d = c.getD();
        if (d == null) return null;
        return d.getZ();
    }
    

提交回复
热议问题