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
Describe the bug
GCI94 suggests replacing
Optional.of("creedengo").orElse(getUnpredictedMethod());withOptional.of("creedengo").orElseGet(() -> getUnpredictedMethod());There are however false positives:
Optional.of(myValue).orElse(MY_DEFAULT_VALUE)will be more efficient than the.orElseGetequivalent.Side notes:
Optional.of("creedengo").orElseGet(this::getUnpredictedMethod());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
orElsewas already defined (typically constant, ornull).Screenshots
N/A
Software Versions
Additional context
N/A