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
7
u/BeautifulTaeng Feb 17 '26
I also think they're ugly, but they force developers to handle nulls properly. Verbosity > having to deal with a NPE on production.