
Inline adoc files when they are included exactly once. Also fix language tags because this inlining gives us better information on what language the code is written in.
72 lines
1.9 KiB
Plaintext
72 lines
1.9 KiB
Plaintext
== Why is this an issue?
|
|
|
|
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;
|
|
}
|
|
}
|
|
----
|
|
|
|
=== Exceptions
|
|
|
|
No issues will be raised if a method is overriding, as the developer has no control over the signature at this point.
|
|
|
|
[source,java]
|
|
----
|
|
@Override
|
|
public String sayHello(Optional<String> name) {
|
|
if (name == null || !name.isPresent()) {
|
|
return "Hello World";
|
|
} else {
|
|
return "Hello " + name;
|
|
}
|
|
}
|
|
----
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Specify a "xxx" parameter instead.
|
|
|
|
|
|
=== Highlighting
|
|
|
|
``++Optional<T>++``
|
|
|
|
|
|
endif::env-github,rspecator-view[]
|