java:S3655 Optional#isPresent()

Hi

SonarQube doesn’t recognize check for “Optional#isPresent()” if it is accessed via intermediate:

While if get directly from Optional variable it is recognized

I expect the first case to pass SonarQube check as well.

Hey there.

I’ve moved your post to the section on reporting false-positives.

Please take a look and come back with some more information, including a text-based sample of code (no screenshots!)

Here is Java code sample related to the issue

public class Demo {

    public String getUserEmailOrThrowError(User user) throws NoSuchFieldException {
        if (user.getEmail()
                .isPresent()) {
            // gives sonar qube error
            return user.getEmail()
                    .get();
        }
        throw new NoSuchFieldException("No email for user: " + user.getId());
    }

    public String getUserEmailOrThrowErrorV2(User user) throws NoSuchFieldException {
        Optional<String> emailOptional = user.getEmail();
        if (emailOptional.isPresent()) {
            // no sonar qube error
            return emailOptional.get();
        }
        throw new NoSuchFieldException("No email for user: " + user.getId());
    }

    public static class User {

        private final UUID id;
        private String email;

        public User(UUID id) {
            this.id = id;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public UUID getId() {
            return this.id;
        }

        public Optional<String> getEmail() {
            return Optional.ofNullable(this.email);
        }
    }
}

Hi Alla,

We are aware of this issue.

In principle, two calls to getEmail() could return different results, so the rule is correct. We do, however, recognize that this is rarely the case and have an existing tickets to update the implementation, for example, JAVASE-133.

This type of issue is well documented in the rule description. I think the example that you provided can be refactored using orElseThrow:

 public String getUserEmailOrThrowError(User user) throws NoSuchFieldException {
    return user
        .getEmail()
        .orElseThrow(() -> new NoSuchFieldException("No email for user: " + user.getId()));
  }