How to avoid checking for null values in method chaining?

user9521067 :

I need to check if some value is null or not. And if its not null then just set some variable to true. There is no else statement here. I got too many condition checks like this.

Is there any way to handle this null checks without checking all method return values?

if(country != null && country.getCity() != null && country.getCity().getSchool() != null && country.getCity().getSchool().getStudent() != null .....) {
    isValid = true;
}

I thought directly checking variable and ignore NullpointerException. Is this a good practice?

try{
    if(country.getCity().getSchool().getStudent().getInfo().... != null)
} catch(NullPointerException ex){
    //dont do anything.
}
khelwood :

No, it is generally not good practice in Java to catch a NPE instead of null-checking your references.

You can use Optional for this kind of thing if you prefer:

if (Optional.ofNullable(country)
            .map(Country::getCity)
            .map(City::getSchool)
            .map(School::getStudent)
            .isPresent()) {
    isValid = true;
}

or simply

boolean isValid = Optional.ofNullable(country)
                          .map(Country::getCity)
                          .map(City::getSchool)
                          .map(School::getStudent)
                          .isPresent();

if that is all that isValid is supposed to be checking.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=427265&siteId=1
Recommended