rspec/rules/S4064/java/rule.adoc

27 lines
1.1 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
----
Optional<MyObj> opt = getOptMyObj();
MyObj myObj = opt.orElse(new MyObj()); // Noncompliant
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
----
Optional<MyObj> opt = getOptMyObj();
MyObj myObj = opt.orElseGet(MyObj::new);
Optional<String> optString = getOptString();
String str = opt.orElse("hello");
----