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
4
u/Ignisami Feb 17 '26 edited Feb 17 '26
imo using Optional to dodge nullities like this is kind of abusing it. It's goated for streams and the like, not to dodge
!= nullchecks.In this specific example
Optional.ofNullable(form.getCity()).orElse(defaultCity)can still result in an Optional of null (in case defaultCity is alsonullsomehow). In which case you're still fucked. Unwrapping anOptional.ofNullable(null)does give younulland if you use that with the expectation of not having to deal with NPE you're gonna unwrap the Optional and get bodied.(edit: and using
Optional.of(form.getCity()).orElse(defaultCity)instantly throws an NPE and does not proceed to the orElse if form.getCity() is null.)Meanwhile,
Objects.requireNonNullElse(form.getCity(), defaultCity)will throw an NPE if both form.getCity() and defaultCity are null. Fails fast, fails where you'd expect something like this to fail. Very nice.