Thursday 16 January 2020

Do not use Optional in method parameters

The Java language authors have been quite frank that Optional was intended for use only as a return type, as a way to convey that a method may or may not return a value.

At work there are some cases where providing an Optional as a method parameter is a good idea, because QueryDSL has been configured to automatically return an empty resultset if the optional is not present.

But an Optional as a method parameter seems to be a disputed design choice1.

A lot of Java tooling complains about it (SonarLint, Findbugs, etc).

A lot of people mention that method overloading might be a better and clearer choice.

For example:

I took a stab at it:

Than I had to go and throw up, this is ugly as sin!

The best answer I found on StackOverflow3 without Java 9 so far:

Now this seems very interesting, but they needed to invent something better. And they did. In Java 9.

Optional.ifPresentOrElse​

Perhaps this is why in Java 92 there is a new method in the Optional class called ifPresentOrElse​.

References

[1] StackOverflow - Should Java 8 getters return optional type?
https://stackoverflow.com/questions/26327957/should-java-8-getters-return-optional-type
[2] JavaDoc - Optional (Java SE 9 & JDK 9)
https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html
[3] StackOverflow - Functional style of Java 8's Optional.ifPresent and if-not-Present?
https://stackoverflow.com/questions/23773024/functional-style-of-java-8s-optional-ifpresent-and-if-not-present
IntelliJ Idea Blog - Java 8 Top Tips
https://blog.jetbrains.com/idea/2016/07/java-8-top-tips/
SonarSource rules - "Optional" should not be used for parameters
https://rules.sonarsource.com/java/RSPEC-3553
DZone - Optional Method Parameters
https://dzone.com/articles/optional-method-parameters

No comments:

Post a Comment