When using Optional<T>
with a nullable field, is it more idiomatic to have the setter take
Optional<T>
T
and then have it as follows?public class Bar {
private Optional<T> foo;
public void setFoo(T foo) {
this.foo = Optional.<T>fromNullable(foo);
}
public Optional<T> getFoo() {
return foo;
}
}
What is the ofNullable() method of the Optional class? The ofNullable() method is used to get an instance of the Optional class with a specified value. If the value is null , then an empty Optional object is returned.
Why Do Developers Need Optional in Java? Optional is generally used as a return type for methods that might not always have a result to return. For example, a method that looks up a user by ID might not find a match, in which case it would return an empty Optional.
Making the getters return Optional can be a good practice for the fields where null is a valid value from a business point of view. Since this would help us enrich our domain model, we should not apply it to DTO objects. This way, we'll also avoid potential serialization issues.
getBar() can return Optional indicating to the developer that this value may reasonably be expected to be null and they should handle this. If the DB guarantees the value will not be null then the getter should not wrap this in an Optional . Foo. bar should be private and not be Optional .
As a general rule, I'd suggest:
public void setFoo(T foo) {
this.foo = checkNotNull(foo); // don't allow null at all!
}
Then, if a user has a value that they know may be null
, they can do:
if (foo != null) {
bar.setFoo(foo);
}
I'd consider doing neither and store the value internally as just T and only have the Optional at the API level.
public class Bar {
private T foo;
public Optional<T> getFoo() {
return Optional.<T>fromNullable(foo);
}
public void setFoo(T foo) {
this.foo = foo;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With