
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.
56 lines
1.6 KiB
Plaintext
56 lines
1.6 KiB
Plaintext
== Why is this an issue?
|
|
|
|
No matter whether the optional value is present or not, ``++Optional::orElse++``'s argument will always be executed. This is usually not what the developer intended when the content of the ``++orElse()++`` call has side effects. Even when no side effect is involved, the unnecessary computation of the ``++orElse()++`` clause might be a waste of resources.
|
|
|
|
|
|
Calls to https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#orElse-T-[``++Optional::orElse++``] should be replaced with https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#orElseGet-java.util.function.Supplier-[``++Optional::orElseGet++``] whenever the alternative value is not a constant.
|
|
|
|
|
|
This rule raises an issue when ``++Optional::orElse++`` is called with an argument that doesn't evaluate to a constant value.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,java]
|
|
----
|
|
Optional<MyObj> opt = getOptMyObj();
|
|
MyObj myObj = opt.orElse(new MyObj()); // Noncompliant
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,java]
|
|
----
|
|
Optional<MyObj> opt = getOptMyObj();
|
|
MyObj myObj = opt.orElseGet(MyObj::new);
|
|
Optional<String> optString = getOptString();
|
|
String str = opt.orElse("hello");
|
|
----
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Use "orElseGet" here instead of "orElse".
|
|
|
|
|
|
=== Highlighting
|
|
|
|
``++orElse++``
|
|
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
=== on 27 Jun 2017, 17:33:18 Ann Campbell wrote:
|
|
https://groups.google.com/forum/?pli=1#!topic/sonarqube/b_DFJ2ual6E
|
|
|
|
endif::env-github,rspecator-view[]
|