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

前端 未结 11 480
失恋的感觉
失恋的感觉 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

    The closest you can get is to take advantage of the short-cut rules in conditionals:

    if(family != null && family.getPeople() != null && family.people.get(0) != null  && family.people.get(0).getAddress() != null && family.people.get(0).getAddress().getPostalCode() != null) {
                        //FINALLY MADE IT TO DO SOMETHING!!!
    
    }
    

    By the way, catching an exception instead of testing the condition in advance is a horrible idea.

提交回复
热议问题