Closed laktak closed 3 years ago
I've had some success using Optional as a null replacement and discouraging the use of null. I agree that the section on Optionals in the guide needs to be rewritten, but I'm not so sure I want to go as far as saying it should be return only.
I'd like to hear other views on this.
Could you mention that there is some controversy and present both approaches?
Also interesting: https://www.linkedin.com/pulse/java-8-obliged-do-optional-siegfried-steiner
I think that's a good plan.
The section about "Avoid Nulls" has the same issue: https://github.com/cxxr/better-java#avoid-nulls
Using Optional as method param or class field is awkward. Look at the JDK code itself: Optional only exists as a return type. And in very few cases as an if-else-throw or if-else-supplier replacement.
The "Avoid Nulls" code should look like this:
public class FooWidget {
private final String data;
private final Bar bar;
public FooWidget(String data, Bar bar) {
this.data = data;
this.bar = bar;
}
public Optional<Bar> getBar() {
return Optional.ofNullable(bar);
}
}
(Or if you really really want the small performance optimizations create the Optional.ofNullable in the constructor.)
Any thoughts on this?