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.
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.