Sonar detects bug but false positive

Hello,

    if (match && r.getCandidate().isPresent()) {

      // Durations are in nanoseconds, we don't need this kind of precision

      candidateTimer.record(r.getCandidate().get().getDuration(), TimeUnit.NANOSECONDS);

This is a transcript of the code.
Sonar asks me to call isPresent(), which is called one line before.

There is no “guarantee” that getCandidate() always returns the same object. You should store it in a local variable:

if (match) {
    Optional<SomeTypeWhichHasDurationField> candidate = r.getCandidate();
    if (candidate.isPresent()) {
       candidateTimer.record(candidate.get().getDuration(), TimeUnit.NANOSECONDS);
    }
}

Of course in your case it could be guaranteed, but SonarScanner doesn’t know enough context to accept it is as a valid code :wink:

1 Like

Alternatively:

if (match) {
    r.getCandidate()
        .map(SomeTypeWhichHasDurationField::getDuration)
        .ifPresent(duration -> candidateTimer.record(duration, TimeUnit.NANOSECONDS));
}
1 Like