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

1

u/noswag15 Feb 18 '26

Thanks, I appreciate the rundown. I just said I didn't have an opinion, not that I didn't know/understand it :) was just trying to be diplomatic since I was talking about just the "optimization" part of that comment (since that's what you were commenting on) and not about whether or not it can be considered premature. In a vacuum I do agree with everything you said.

I guess the intent of my comment was to point out that even in your original reply to the other person saying "premature optimization", your definition of what constitutes optimization was correct in a vacuum but that it didn't apply to the other person's comment since the person was clearly talking about starting from using optional and that "removing optional for performance reasons" is premature optimization (according to that person).

That being said, I also prefer the Objects.requireNonNull* variations. but sometimes I also use the instanceOf form like so

var city = form.getCity() instanceOf City city ? city : defaultCity;