6

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;
    }
}
Saulo Silva
  • 1,219
  • 1
  • 20
  • 37

3 Answers3

7

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;
    }
}
Paul Blessing
  • 3,815
  • 2
  • 24
  • 25
  • 1
    My only comment is it might be more idiomatic to do `this.foo = Preconditions.checkNotNull(foo)`, and have a separate `clearFoo()` method. You could additionally have `setFoo(Optional foo)` which does `this.foo = foo.orNull()`. – Tavian Barnes Oct 31 '14 at 19:29
  • Are there any benefits to storing it just as T or it just Smells Better? – Saulo Silva Oct 31 '14 at 20:52
  • 2
    @SauloSilva Some benefits are discussed (in the context of Java 8's `Optional` which is similar) in [this answer](http://stackoverflow.com/a/24564612/502399). – Tavian Barnes Oct 31 '14 at 21:02
3

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);
}
ColinD
  • 108,630
  • 30
  • 201
  • 202
0

The latter would be my suggestion. But it is objective as to which is more idiomatic.

public class Bar {
    private T foo;

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