Java: avoid checking for null in nested classes (Deep Null checking)

前端 未结 11 469
失恋的感觉
失恋的感觉 2020-12-05 09:12

Imagine I have a class Family. It contains a List of Person. Each (class) Person contains a (class) Address. Each (class) Address contains a (class) PostalCode. Any "i

11条回答
  •  春和景丽
    2020-12-05 09:58

    Your code behaves the same as

    if(family != null &&
      family.getPeople() != null &&
      family.people.get(0) != null && 
      family.people.get(0).getAddress() != null &&
      family.people.get(0).getAddress().getPostalCode() != null) { 
           //My Code
    }
    

    Thanks to short circuiting evaluation, this is also safe, since the second condition will not be evaluated if the first is false, the 3rd won't be evaluated if the 2nd is false,.... and you will not get NPE because if it.

提交回复
热议问题