rspec/rules/S3553/java/rule.adoc
2022-02-04 16:28:24 +00:00

48 lines
1.5 KiB
Plaintext

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
[source,java]
----
public String sayHello(Optional<String> name) { // Noncompliant
if (name == null || !name.isPresent()) {
return "Hello World";
} else {
return "Hello " + name;
}
}
----
== Compliant Solution
[source,java]
----
public String sayHello(String name) {
if (name == null) {
return "Hello World";
} else {
return "Hello " + name;
}
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
include::highlighting.adoc[]
endif::env-github,rspecator-view[]