r/java • • Feb 17 '26

Objects.requireNonNullElse

I must have been living in a cave. I just discovered that this exists.
I can code

City city = Objects.requireNonNullElse(form.getCity(), defaultCity);

... instead of:

City city = form.getCity();

if(city == null){

city = defaultCity;

}

113 Upvotes

136 comments sorted by

View all comments

Show parent comment

1

u/nlisker Feb 18 '26

The way you phrased it, it sounds suicidal from the project's perspective. "the dev and the reviewers should know to check" is a bad idea. Maybe he meant that nulls should only be checked at the boundary (entry points), and then all the code that is the implementation doesn't need to check nulls again.

For example:

public int sumTrace(Matrix m1, Matrix m2) {
    // require non-null check here
    int trace1 = tr(m1);
    int trace2 = tr(m1);
    return trace1 + trace2;
}

private int tr(Matrix m) {
    // no need to check null since the input was sanitized
    // ...
}

Static imports can cause readability issues because it's not clear where the method comes from. There are some cases, like the Collectors class where it's not too ambiguous.