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;

}

112 Upvotes

136 comments sorted by

View all comments

Show parent comment

3

u/j4ckbauer Feb 18 '26

Ugh, if your senior is so confident that a thing will never be allowed to happen, the way you'd confirm this is not by having to look at call sites. Does this not increase cognitive load?

I would think this is what usage of @ NonNull with static analysis is for, now you don't need to distract yourself by checking any call sites.

I get the idea of reducing complexity by never allowing something to happen (so it never needs to be checked for), but if the method for avoiding the bad thing is 'everybody try really hard not to make the mistake', I feel that person learned some of the wrong lessons in their career. You don't avoid having bugs by trying really hard not to have bugs....

Curious what others think.