imo using Optional to dodge nullities like this is kind of abusing it. It's goated for streams and the like, not to dodge != null checks. In this specific example Optional.ofNullable(form.getCity()).orElse(defaultCity) can still result in an Optional of null (in case defaultCity is also null somehow). In which case you're still fucked. Unwrapping an Optional.ofNullable(null) does give you null and 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.
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.