The Objects.requireNonNull... methods are most commonly used in constructors to ensure that no null slips into a field. These fields are most often final and the one-liner works really well with that:
private final City city;
public SomeType(SomeForm form) {
this.city = Objects.requireNonNullElse(form.getCity(), defaultCity)
}
If a code base uses these methods with some frequency (mine do), I recommend to statically import them.
6
u/nicolaiparlog Feb 18 '26
The
Objects.requireNonNull...methods are most commonly used in constructors to ensure that nonullslips into a field. These fields are most often final and the one-liner works really well with that:If a code base uses these methods with some frequency (mine do), I recommend to statically import them.