简体   繁体   中英

How to avoid Nested null check

I want to retrieve the field from API which present inside classes. 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:

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 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.

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)

This needs Java 8, you are right. 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;
                }
              }
          }
      }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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