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;
}
112
Upvotes
View all comments
Show parent comment
1
u/Least_Bee4074 Feb 18 '26
I started doing this when another senior colleague would always flag it in my PR and say “don’t let your objects get into an invalid state.”
Now I’m in a project where we’ve adopted this practice and the new engineering manager has come in and ordered us all to remove them claiming it adds to cognitive load. His reasoning is that we can look at all the call sites and confirm that as of now, none will produce nulls. And if in the future we call into something, the dev and the reviewers should know to check that no nulls happen in whatever spots (which sounds very error prone to me).
He also ordered us to remove static imports.