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

6

u/OwnBreakfast1114 Feb 18 '26 edited Feb 19 '26

overseeing teams of REALLY good devs

I've taught all the devs at my company switch expressions and sealed interfaces and there's plenty of business cases where a closed set of things is the right abstraction. I don't think we have a fairly abnormal cross section of engineers.

The goal, you make changes and if it compiles it works, is pretty easy to explain to people. Exhaustive compiler checks are good.

1

u/narrow-adventure Feb 18 '26

Maybe I’m wrong, I’ve seen people miss understand classes and variables and pass by value semantics over and over again in interviews, so I think they’ll misunderstand and misuse this too. But it’s like my opinion, if it works for you and all devs are using it right maybe I’m just wrong and that’s cool too.