r/java • u/edurbs • 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;
}
115
Upvotes
View all comments
Show parent comment
5
u/ryan_the_leach Feb 18 '26
It's the length of method name tbh.
If it was in the language since day 1, everyone would be static importing def(nullable, defaultValue) and not debating about readability because "of course everyone knows the default value function"
You can debate about the readability to people outside the skill niche, or how accessible it is for newcomers, but Objects.requireBlahBlah is just too much visual noise for something so simple.