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
1
u/Away_Advisor3460 Feb 17 '26
IMO the main advantage of optionals is for legacy code where you need to convey the possibility of a null value occurring from some weird-ass legacy function, because time constraints prevent you properly rooting into why, preventing that null and adding proper test coverage.