Search code examples
javaexceptionnullpointerexceptionnull

How to avoid checking for null values in method chaining?


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 about directly checking variable and ignoring NullpointerException. Is this a good practice?

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

Solution

  • 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.