rspec/rules/S4064/java/rule.adoc

46 lines
1.4 KiB
Plaintext
Raw Normal View History

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.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
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
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
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)
include::message.adoc[]
include::highlighting.adoc[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]