[WEB][42108]Optimized use of Java Optional Else
JulienBertrand opened this issue · 2 comments
\newpage
Optimized use of Java Optional Else
Platform
OS | OS Version | Language |
---|---|---|
Java |
Main characteristics
ID | Title | Category | Sub-category |
---|---|---|---|
CRJVM001 | Optimized use of Java Optional Else |
Severity / Remediation Cost
Severity | Remediation Cost |
---|---|
Minor | Minor |
Rule short description
The Optional orElse method always evaluate the "other" argument, whereas the orElseGet only call the given Supplier method passed as an argument when the Optional value isn't present. Evaluate orElse
can be inefficient.
Rule short description
Text
Remember (from the Javadoc) that the Supplier method passed as an argument is only executed when an Optional value isn't present.
To avoid unneeded argument evaluation, check that "other" argument of orElse method is never a method call, but simply an object or a static value.
HTML
// Uncompliant code:
String name = Optional.of("ecoCode")
.orElse(getUnpredictedMethod());
// Compliant code:
String name = Optional.of("ecoCode")
.orElseGet(() -> getUnpredictedMethod());
Implementation principle
- Search
orElse
method - Check if
orElse
method argument is a call of method - If true report the Line as uncompliant
References
https://www.baeldung.com/java-optional-or-else-vs-or-else-get
Reading the link in the description (https://www.baeldung.com/java-optional-or-else-vs-or-else-get) I think we can implement this rule. There is a beginning of measure in the document that is relevant with the rule.
I think the description wording of the rule should be reworked and may be we can perform more measure but the rule seems good to me. May be a good exemple to perform energy measures.
Hi @jhertout @glalloue
second review OK for this issue.
first ecocode
PR (rule specification) merged and updated with real rule ID - see green-code-initiative/creedengo-rules-specifications#323
the 2 nexts PRs will be merged soon once a release of specifications will be done and referenced on ecoCode-java plugin.
What is the process for actual kind of issue ? do we simply close it ?