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.)