green-code-initiative / ecoCode-challenge

Emboard in the hackhatons serie for improving ecoCode
3 stars 4 forks source link

[WEB][42108]Optimized use of Java Optional Else #77

Open JulienBertrand opened 1 year ago

JulienBertrand commented 1 year ago

\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

References

https://www.baeldung.com/java-optional-or-else-vs-or-else-get

jhertout commented 5 months ago

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.

dedece35 commented 3 months ago

Hi @jhertout @glalloue second review OK for this issue. first ecocode PR (rule specification) merged and updated with real rule ID - see https://github.com/green-code-initiative/ecoCode/pull/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 ?