如何避免嵌套空检查

时间:2015-02-27 12:22:21

标签: java nullpointerexception

我想从API中检索出现在类内的字段。 是的我知道这违反了得墨忒耳法,但我没有任何选择。

实施例

getClassA().getClassB().getClassC().getClassD().getAccountId();

所以要添加null check作为它的坏代码味道,所以我带来下面的代码:

try{
getClassA().getClassB().getClassC().getClassD().getAccountId();
}catch(NullPointerException ex){
 S.O.P("Null Found");
}

ClassA a = getClassA();
if(a!=null){
ClassB b = a.getClassB();
So on.....
}

我的问题是最好的方法是上面提到的或者显式检索每个类并检查null并转到下一级 这违反了德米特法则

2 个答案:

答案 0 :(得分:2)

Null对象设计模式是通过Optional类在Java 8中被吸收的方式,这意味着你有一个包装器,你可以在其中拥有数据或者你有空数据。

类似

             MyObject
      RealObject    NullObject

在不传递null的情况下,传递NullObject,它提供与MyObject相同的接口(可以是具体/抽象/接口类)

答案 1 :(得分:2)

这需要Java 8,你是对的。我认为这将在Guava中以类似的方式发挥作用。

public class OptionalTest {

  public static void main(String[] args) {
    A a = new A();
    Optional<A> opa = Optional.ofNullable(a);
    int accid = opa.map(A::getClassB).map(A.B::getClassC).map(A.B.C::getClassD).map(A.B.C.D::getAccountID).orElse(-1);

    if (accid > -1) {
      System.out.println("The account id is: " + accid);
    } else {
      System.out.println("One of them was null. Please play with commenting.");
    }
  }

    static class A {
      B b = new B();
      //B b = null;
      B getClassB() {
        return b;
      }

      static class B {
        //C c = new C();
        C c = null;
        C getClassC() {
          return c;
        }

          static class C {
            D d = new D();
            //D d = null;
            D getClassD() {
              return d;
            }

              static class D {
                private final int accountId = 2;
                int getAccountID() {
                  return accountId;
                }
              }
          }
      }
    }
}
相关问题