Also, after reading a bit of documentation on the topic, it also important to understand where not to use Optional.
In the sample bellow, the first class presents some Optional anti-pattern. Where some alternatives are obviously better, I’m not sure if exposing Optional in the method and constructor parameters is always the best solution.
class FooWrong {
private Optional<Bar> baz; // double indirection
// makes the interface more (too?) complicated
public FooWrong(Optional<Bar> baz) { this.baz = baz; }
public Optional<Bar> getBaz() { return this.baz; }
// makes the interface more complicated
public void setBaz(Optional<Bar> baz) { this.baz = baz; }
}
class FooOk1 {
private Bar baz;
public FooOk1(Bar baz) { this.baz = baz; }
// re-mapping to optional
public Optional<Bar> getBaz() { return Optional.ofNullable(this.baz); }
public void setBaz(Bar baz) { this.baz = baz; }
}
class FooOk2 {
private Bar baz;
public FooOk2(Optional<Bar> baz) { this.baz = baz.orElse(null); }
public Optional<Bar> getBaz() { return Optional.ofNullable(this.baz); }
public void setBaz(Optional<Bar> baz) { this.baz = baz.orElse(null); }
}