Yamen Nassif
Yamen Nassif

Reputation: 2476

Nested objects null checking

I know many ways how to check on nested objects for a NullPointerException, as for Java 8 the simplest is to apply the Optional<param>. or to use a simple if code such as

if(foo.bar() != null && foo.getBar().getObject()!=null){
    foo.getBar().getObject().getWhatever();
}

well my question is is there an easy way to do so in one method without knowing the names of the inner classes/methods

to be more clear i have a code which is like this

contract.getContactInfo().getPosition()
contract.getEntitledPerson().getEmail()

and i want to do something like this for an example

excel.setCell(name1,contract.getContactInfo().getPosition());
excel.setCell(name2,contract.getEntitledPerson().getEmail());

if its for only 2 nested objects or only 2 setters that's fine but get it for a 50 excel cells with sometimes 5 or 6 nested objects its a real nightmare to do so

something lets say like the setCell method

public setCell(String name,Object object){
     return object; // make sure no nested object is null
}

i hope my question is clear enough. keep in mind i cant simply change the nested objects since its legacy code and being used in a lot of places! any ideas ?

Upvotes: 2

Views: 8436

Answers (1)

Andreas
Andreas

Reputation: 159106

As you mentioned yourself in the question, use Optional, but it's more lenghty.

excel.setCell(name1, Optional.of(contract).map(Contract::getContactInfo).map(ContactInfo::getPosition).orElse(null));
excel.setCell(name2, Optional.of(contract).map(Contract::getEntitledPerson).map(Person::getEmail).orElse(null));

Which is more easily read when formatted like this:

excel.setCell(name1, Optional.of(contract)
                             .map(Contract::getContactInfo)
                             .map(ContactInfo::getPosition)
                             .orElse(null));
excel.setCell(name2, Optional.of(contract)
                             .map(Contract::getEntitledPerson)
                             .map(Person::getEmail)
                             .orElse(null));

If your goal is smallest code, you could just catch the NullPointerException. It's a bit of a hack, in my opinion, but it'll do the trick.

First, a helper method:

public static <T> T nullGuard(Supplier<T> supplier) {
    try {
        return supplier.get();
    } catch (@SuppressWarnings("unused") NullPointerException ignored) {
        return null;
    }
}

Then you wrapper the expression in question:

excel.setCell(name1, nullGuard(() -> contract.getContactInfo().getPosition()));
excel.setCell(name2, nullGuard(() -> contract.getEntitledPerson().getEmail()));

Upvotes: 8

Related Questions