False positive on java:S6206 suggesting to use record while having mismatching getter return types

Version information:

  • SonarQube 8.9.0.43852
  • Manually installed sonar-java-plugin-7.2.0.26923.jar to support Java 16

Let’s consider the use case when a type is supposed to encapsulate data and ensure some invariants:

final class Bar {

    private final String bar;

    public Bar(String bar) {
        this.bar = ((bar == null) || bar.isEmpty()) ? null : bar;
    }

    public Optional<String> bar() {
        return Optional.of(bar);
    }
}

Sonar recommends converting such a class into a record. While it resembles a record indeed, the return types of the getter(s) differ, therefore the conversion is not possible. A naïve fix could use Optional as the type of the constructor parameter and the field, however, that is considered a bad practice.

I’d suggest to adjust the rule, so that it takes the return types of the getters into account. If the types are not same (or the field types are not covariant with the return types), the warning should not be issued. (There might be yet other suitable constraints for the rule to trigger.)

Hello @pdolezal

Thanks for having a look at our new rules targeting Java 16 and reporting issues with nice reproducers.

I agree that we should not suggest using a record in this case. Ticket created: SONARJAVA-4016.

Best,
Quentin

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.