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

前端 未结 11 467
失恋的感觉
失恋的感觉 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 10:14

    If you can use groovy for mapping it will clean up the syntax and codes looks cleaner. As Groovy co-exist with java you can leverage groovy for doing the mapping.

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

    instead you can do this

    if(family?.people?[0]?.address?.postalCode) {
       //do something
    }
    

    or if you need to map it to other object

    somobject.zip = family?.people?[0]?.address?.postalCode
    

提交回复
热议问题