rspec/rules/S4064/java/rule.adoc

56 lines
1.6 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
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
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
Optional<MyObj> opt = getOptMyObj();
MyObj myObj = opt.orElse(new MyObj()); // Noncompliant
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
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[]