FP on squid:S3655 when optional.isEmpty() is used instead of !optional.isPresent()

Version: SonarLint SolarSource 4.4.0.14142

package foo.bar;

import java.util.Optional;

public class Main {
  Object fp() {
    Optional<Object> opt = Optional.ofNullable(System.getenv("foo"));
    if (opt.isEmpty()) {
      return null;
    }
    return opt.get(); // FP on squid:S3655
  }
}

Optional.isEmpty() is !Optional.isPresent(), so the “Call opt.isPresent() before accessing the value” warning should not be triggered here.

Hi Péter,

I tried to reproduce the above S3655 FP using Intellij Idea 2019.3 (with it’s embedded openjdk version 11.0.5) and SonarLint 4.4.0.14142, but I failed. The rule S3655 supports both isPresent() and isEmpty() of my java 11 project.
Then I cheated to force Intellij Idea to use AdoptOpenJDK 8.0.242, and I was able to reproduce the above FP.

Can you confirm that your project requires java >= 11 and you use a java version < 11 for your IDE?
If it’s the case, is there a specific reason that prevents you from using java >= 11 for your IDE?

1 Like

Hello,

Thanks for the reply. Indeed I was running the IDE on java-8 and developing java-11 project. There is no hard reason to not use jdk-11 for the IDE, too, so I’ll just switch :slight_smile: Strange though that this constellation causes such an issue.

(My system default was jdk-8 for stability reasons for other applications)

Again, thanks for the reply. I consider this user-error then on my part :wink: