Using SonarLint IntelliJ 4.3.0.3495 in IntelliJ IDEA Ultimate 2019.2.4 (Build #IU-192.7142.36).
SonarLint rule squid S3655: “Optional value should only be accessed after calling isPresent()” does not hold up.
Please see this code to reproduce:
import java.util.Optional;
import java.util.function.UnaryOperator;
public enum SonarLintBugDemonstration implements UnaryOperator<String> {
SONARLINT_PROBLEM_1(Optional.of(false)) {
@Override
public String apply(String str) {
if(SONARLINT_PROBLEM_1.stripWhitespaces.isPresent() && SONARLINT_PROBLEM_1.stripWhitespaces.get()) {
str = str.replaceAll("\\s", "");
}
return str;
}
},
SONARLINT_PROBLEM_2(Optional.of(true)) {
@Override
public String apply(String str) {
if(SONARLINT_PROBLEM_2.stripWhitespaces.isPresent()) {
if(SONARLINT_PROBLEM_2.stripWhitespaces.get()) str = str.replaceAll("\\s", "");
}
return str;
}
},
SONARLINT_PROBLEM_3(Optional.of(true)) {
@Override
public String apply(final String str) {
return (SONARLINT_PROBLEM_3.stripWhitespaces.isPresent() && SONARLINT_PROBLEM_3.stripWhitespaces.get() ? str.replaceAll("\\s", "") : str);
}
},
SONARLINT_PROBLEM_4(Optional.of(true)) {
@Override
public String apply(final String str) {
return (SONARLINT_PROBLEM_4.stripWhitespaces.isPresent() ?
(SONARLINT_PROBLEM_4.stripWhitespaces.get() ? str.replaceAll("\\s", "") : str) : str);
}
};
private Optional<Boolean> stripWhitespaces;
SonarLintBugDemonstration(final Optional<Boolean> stripWhitespaces) {
this.stripWhitespaces = Optional.ofNullable(stripWhitespaces).orElse(Optional.empty());
}
}
SonarLint will report the warning on all Optional#get() calls.
This is my first bug report, so I apologize if I’m missing anything.