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.
And for that, it’s valuable but using Optional
on the input side increases the work you have to do in the method without really
increasing the value. With an Optional
parameter, you go from having 2 possible inputs: null and not-null, to three: null,
non-null-without-value, and non-null-with-value. Add to that the fact that overloading has long been available to convey that some parameters are
optional, and there’s really no reason to have Optional
parameters.
The rule also checks for Guava’s Optional
, as it was the inspiration for the JDK Optional
. Although it is different in
some aspects (serialization, being recommended for use as collection elements), using it as a parameter type causes exactly the same problems as for
JDK Optional
.
Noncompliant code example
public String sayHello(Optional<String> name) { // Noncompliant
if (name == null || !name.isPresent()) {
return "Hello World";
} else {
return "Hello " + name;
}
}
Compliant solution
public String sayHello(String name) {
if (name == null) {
return "Hello World";
} else {
return "Hello " + name;
}
}
Exceptions
No issues will be raised if a method is overriding, as the developer has no control over the signature at this point.
@Override
public String sayHello(Optional<String> name) {
if (name == null || !name.isPresent()) {
return "Hello World";
} else {
return "Hello " + name;
}
}