FP checking presence of optional inside loop

SQ Community Edition, Version 7.3 (build 15553)
SonarLint version 3.5.1.2759
IntelliJ IDEA 2018.1.6 (Ultimate Edition), Build #IU-181.5540.7

    Optional<String> opt = Optional.of("");
    final boolean alwaysTrue = opt.filter(s -> s.equals("")).isPresent();
    while (true) {
      final boolean alwaysFalse = opt.filter(s -> s.equals("a")).isPresent();
      if (alwaysFalse) {
        System.out.println("nay");
      } else if (alwaysTrue) {
        System.out.println("yay");
      }
    }

SQ says the alwaysFalse value is always true.

  • It also happens if I change the while to a for
  • It does not happen if I change the while to an if
  • It does not happen if I assign alwaysFalse outside the loop

Hello Even,

Thank you for feedback.
Indeed, it seems to be a wrong behavior of the rule.

There is a known FP related to optional when filtering is involved. This problem has been addressed in ticket SONARJAVA-2873 and will be fixed in the next sonar-java version.

I will investigate further the changes in behavior depending on the cases you mentioned, it seems to be another problem altogether.

Hello @e.lislebo,

There is indeed another issue regarding the current behavior of the rule. It comes from the fact that some variables (and constraints in the symbolic execution engine) are sometimes not considered alive when they still should.
A ticket has been created to tackle this: SONARJAVA-2951

Best,
Chris

Cool, cheers

Hi @czurn,

I saw that the linked jira ticket (SONARJAVA-2873) has been fixed, so I marked the comment where you linked it as a solution. Is that the correct usage of “solutions”?

Cheers,
Even

Hello,

Yes, that’s a correct way to use the “Solution” check box if your confirm that the implemented ticket resolved your problem.

Regards