@Contract annotation is not taken into account for Optional#isPresent check

  • What language is this for? => Java
  • Which rule? => java:s3655
  • Why do you believe it’s a false-positive/false-negative? => Optional#isPresent is called and fails if false. Yet calling Optional#get after is reported as a bug.
  • Are you using
    • SonarCloud? => no
    • SonarQube - which version? => Community Edition 10.0.0.68432
    • SonarLint - which IDE/version? => no
      • in connected mode with SonarQube or SonarCloud?
  • How can we reproduce the problem? Give us a self-contained snippet of code (formatted text, no screenshots)
import java.util.Optional;

import static org.junit.jupiter.api.Assertions.*;

public class Main {
    public void example(Optional<Object> optional) {
        assertTrue(optional.isPresent());
        optional.get();
    }
}

According to assertTrue’s contract (Contract(value = “false → fail”, pure = true)), Optional#get is only called if Optional#isPresent is true.

Note: If the Contract annotation is not supposed to be taken into account this topic should be closed.

Thank you @Geert for reporting this false positive.

The resolution progress is tracked in SONARJAVA-4520.

A small general remark is to avoid assertions in production code. See S5960 for more details.

Cheers,
Angelo