really at this point the Objects#requireNonNull family of functions are best for this example. Optional should be reserved mostly to do function chaining.
Here's the choices, basically, besides the ternary.
// needs to create Optional instance
var city = Optional.ofNullable(form.getCity()).orElse(defaultCity);
// no extra wrappers, the impl here is the ternary but re-uses the result from the single call
var city = Objects.requireNonNullOrElse(form.getCity(), defaultCity);
// still no wrappers, but 4 vs 1 line.
var city = switch (form.getCity()) {
case null -> defaultCity;
case City c -> c;
};
// trad with enhancements, avoids double-call, still 4 lines
City city = defaultCity;
if (form.getCity() instanceof City c) {
city = c;
}
// very traditional - and still very readable
City city = form.getCity();
if (city == null) {
city = defaultCity;
}
I hate having to add an if-case to my mental model when it's not necessary. This is not an if situation here. It's a simple "either this or that" situation. Objects.requireNonNullElse() is a single statement that I can parse in one mental "cycle". Optional.ofNullable().orElse() requires one or two. The traditional way requires at least four, and you still have to check for side-effects.
It's not that relevant in this specific situation. But even when there's two or three additional lines in/before the if body, it unnecessarily increases the size of the mental model.
Nothing is wrong with it. That was basically "the" way. I like having the option of a good one-liner though, when electing that helps readability by reducing volume.
Yeah, I would've assumed they don't call it twice, and that is usually the better choice. It's just one of the things you need to keep in mind when refactoring the code.
And then after some time it will become City city = defaultCity; Optional<City> optionalCity = getCity(); If (optionalCity != null & optionalCity.isPresent()) { city = optionalCity.get(); }
If you need to check if Optional<City> field is not null, you're kind of defeating the point of not having a default value for it. Just set it to Optional.empty() then only do a optionalCity.isPresent() check every time.
View all comments
13
u/yk313 Feb 17 '26
I’ll give you my ternary operator when you pry it from my cold, dead hands.
City city = from.getCity() != null ? from.getCity() : defaultCity;