cxxr / better-java

Resources for writing modern Java
Other
5.79k stars 730 forks source link

Optional should only be used as a Return Type #36

Closed laktak closed 3 years ago

laktak commented 8 years ago

The JSR-335 EG felt fairly strongly that Optional should not be on any more than needed to support the optional-return idiom only. Someone suggested maybe even renaming it to OptionalReturn"

Any thoughts on this?

cxxr commented 8 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.

laktak commented 8 years ago

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

cxxr commented 8 years ago

I think that's a good plan.

benneq commented 4 years ago

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.)