Which is more idiomatic: setters taking an optional <T>, or just T?

When used Optional<T>

with a null field, it is more leadiomatic that the receiving setter

  • a Optional<T>


    or
  • just a T

    and then do this:
public class Bar {
    private Optional<T> foo;

    public void setFoo(T foo) {
        this.foo = Optional.<T>fromNullable(foo);
    }

    public Optional<T> getFoo() {
        return foo;
    }
}

      

+3


source to share


3 answers


I would consider not to do and store the value internally as soon as T and only have an option 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;
    }
}

      

+5


source


Generally, I suggest:

public void setFoo(T foo) {
  this.foo = checkNotNull(foo); // don't allow null at all!
}

      



Then, if the user has a value that they know, maybe null

they can do:

if (foo != null) {
  bar.setFoo(foo);
}

      

+3


source


The latter will be my suggestion. But he is objective, which is more idiomatic.

public class Bar {
    private T foo;

    public void setFoo(T foo) {
        this.foo = Optional.<T>fromNullable(foo);
    }
}

      

0


source







All Articles