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;
}
113
Upvotes
View all comments
Show parent comment
0
u/noswag15 Feb 18 '26
"Premature optimization" does get thrown around a lot and I'm not sure if it's applicable here but I don't fully understand your point either.
Are you suggesting that the person you're responding to is using the term optimization incorrectly in this context ?
I think they are commenting from the perspective that using optional is ok here and arguing against doing "more work" by removing it from the code to save the computer the work of "creating an unnecessary optional object" so their use of the word optimization makes sense here.
I don't have an opinion on whether or not it's "premature" in this context though.