MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/java/comments/1r7iv5p/objectsrequirenonnullelse/o60nxw3/?context=3
r/java • u/edurbs • Feb 17 '26
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;
}
136 comments sorted by
View all comments
Show parent comment
1
I do from.hasCity() ? from.getCity() : defaultCity
from.hasCity() ? from.getCity() : defaultCity
or if the code gets repetitive, I create a helper function inside from
City getCityOr(City city){ return hasCity() ? getCity(): city}
then just call it a million times
from.getCityOr(defaultCity)
View all comments
Show parent comment
1
u/unknowinm Feb 18 '26
I do
from.hasCity() ? from.getCity() : defaultCityor if the code gets repetitive, I create a helper function inside from
City getCityOr(City city){ return hasCity() ? getCity(): city}then just call it a million times