简体   繁体   English

如何避免嵌套空检查

[英]How to avoid Nested null check

I want to retrieve the field from API which present inside classes. 我想从API中检索出现在类内部的字段。 Yes I know this is against Law of Demeter but I don't have any option. 是的我知道这违反了德米特法,但我没有任何选择。

Example

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

So to add null check as its bad code smell so I come with below code: 所以要添加null检查作为它的坏代码气味所以我带来下面的代码:

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

or 要么

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

my question is which is best approach the above mentioned one or explicitly retrieve each class and check null and go to next level This is against Law of Demeter 我的问题是哪个是最好的方法上面提到的或显式检索每个类并检查null并转到下一级这是违反得墨忒耳法

Null Object design pattern is the way to which is being absorbed in Java 8 via Optional class which means you have a wrapper within which either you have the data or you have empty data. Null对象设计模式是通过Optional类在Java 8中被吸收的方式,这意味着您有一个包装器,您可以在其中拥有数据或者您拥有空数据。

Its something like 它的东西就像

             MyObject
      RealObject    NullObject

Where instead of passing null, you pass NullObject which provides the same interface as MyObject (which can be concrete/abstract/interface class) 而不是传递null,你传递NullObject,它提供与MyObject相同的接口(可以是具体/抽象/接口类)

This needs Java 8, you are right. 这需要Java 8,你是对的。 I think this will function in a similar way in 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;
                }
              }
          }
      }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM