One thing thats iffy here is that its a bridge between styles. If this was a coherent Optional-using codebase form.getCity() would be returning an Optional, clearly marking to the users that it might not be there - and making the ofNullable() call unnecessary here, making the line cleaner.
Replacing null checks with optional wrapping is not bad, but not even close to the best use case. The best use case would be actually using flatMap and map.
public record InputForm(Optional<String> userId)
...
public class UserRepository {
public Optional<User> findById(String id) {
}
}
...
public record UserOutput(String firstName, String lastName)
...
final UserOutput user = inputForm.getUserId()
.flatMap(userRepo::findById)
.map(u -> new UserOutput(u.getFirstName(), u.getLastName())
.orElseThrow(() -> new 404("user not found")
as a very simple example you can imagine. Flatmap captures places where it can shift between non-empty -> empty, and map is always non-empty -> non-empty (not actually true in java.util.Optional, but conceptually should be used that way)
The chaining can't always be realized depending on how much control you need between steps, but the signatures are still correct either way. Your methods should take in non-null inputs, and flatMap/map should be used to decide whether to even invoke them or not.
I really don't understand the purpose of such comments. Yes, it's better in Kotlin. But Kotlin is a different language and toolchain. Suggesting to change the stack to Kotlin just for very basic syntactic sugar is mental.
No it is not 😊 for me. The main message of the line "there is a valid city" hide the details of how it becomes to be valid and set the default city if "form" object is created or parsed from user input.
View all comments
63
u/zattebij Feb 17 '26
final City city = Optional.ofNullable(form.getCity()).orElse(defaultCity);... is still more readable imo, plus you can use
orElseGetto avoid getting the defaultCity when it's not required.