Skip to content

GCI94 systematically suggests orElseGet, but could be further optimized #119

@cyChop

Description

@cyChop

Describe the bug
GCI94 suggests replacing Optional.of("creedengo").orElse(getUnpredictedMethod()); with Optional.of("creedengo").orElseGet(() -> getUnpredictedMethod());

There are however false positives:

  • If I already have a constant, creating a lambda will add unnecessary operations: Optional.of(myValue).orElse(MY_DEFAULT_VALUE) will be more efficient than the .orElseGet equivalent.

Side notes:

  • The example used as a compliant code example could use a reference rather than a lambda, as it is more efficient, too: Optional.of("creedengo").orElseGet(this::getUnpredictedMethod());
  • There is one example of compliant code which isn't clear in its usage: randomClass.orElse(getUnpredictedMethod()); => if this is to show that this rule only applies to Optional, I don't see an added value here.

To Reproduce
Steps to reproduce the behavior:

Analyze code containing Optional.ofNullable(aBooleanWrapper).orElse(Boolean.FALSE);

Expected behavior
Don't raise an issue if the value supplied to orElse was already defined (typically constant, or null).

Screenshots
N/A

Software Versions

  • SonarQube Version: 2025.1
  • Plugin Version: ?

Additional context
N/A

Metadata

Metadata

Assignees

Labels

🗃️ rulerule improvment or rule development or bug🚀 enhancementNew feature or request

Type

No fields configured for Bug.

Projects

Status
Ready

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions