Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is more idiomatic: setters taking an Optional<T> or just T?

Tags:

java

guava

When using Optional<T> with a nullable field, is it more idiomatic to have the setter take

  • an Optional<T>
    or
  • just a 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;
    }
}
like image 255
Saulo Silva Avatar asked Oct 31 '14 18:10

Saulo Silva


People also ask

Where is optional ofNullable used?

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.

Should we use optional Java?

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.

Is it good practice to return 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.

Should Java 8 getters return optional type?

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 .


2 Answers

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);
}
like image 35
ColinD Avatar answered Sep 25 '22 15:09

ColinD


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;
    }
}
like image 68
Paul Blessing Avatar answered Sep 24 '22 15:09

Paul Blessing