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;

}

114 Upvotes

136 comments sorted by

View all comments

Show parent comment

0

u/rzwitserloot Feb 21 '26

That's a clash of concerns - equals is specced to never throw. And removing that now is an issue. But yes, that was a mistake too. It's not the only aspect of java that is a mistake, but fixing it in a backwards compatible way would be a cure that is worse than the disease so it isn't done.

Objects.equals is pointless if 'null should throw' is the mindset. Just call a.equals(b) instead of Objects.equals(a, b) then.

At best a sane equals can be written that does a.equals(b) if both are non-null and throws NPE if either (or both) are, but, 'make a utility method' is a shitty solution to these problems.