Given the following type hierarchy:
public class GenericBaseClass<T> { }
public class SpecializedClass<T, E extends Enum<E> & SomeInterface> extends GenericBaseClass<T> { }
public class SomeProvider {
private static final List<SpecializedClass<Foo, ?>> VALUES =
Arrays.asList(createValue());
List<SpecializedClass<Foo, ?>> getValues() {
return VALUES;
}
private static SpecializedClass<Foo, Bar> createValue() {
return new SpecializedClass<>();
}
}
public class Foo {}
public enum Bar implements SomeInterface {}
public interface SomeInterface {}
The SomeProvider is supposed to expose a List of available SpecializedClass for the concrete type Foo. (To simplify the example here is only one concretion given for the type Bar.)
According to https://rules.sonarsource.com/java/RSPEC-1452
Generic wildcard types should not be used in return parameters
this snippet is marked as critical code smell by sonar.
Soo far I was not able to get rid of the wildcard here. Changing the getter method to
List<GenericBaseClass<Foo>> getValues() {
return VALUES;
}
will avoid the warning, but the client loses the information, that this list only contains instances of SpecializedClass.
Basically I have two questions here:
Is this really such a bad code smell in this case? What might be the pitfalls for the client using this getter method here?
How should the getter look like without using a wildcard in the return type?
Many thanks in advance for your help.
What is wrong using
?
Edit:
Also possible but unsure about your static code analysis is
which at least binds your return type to a subtype of
SomeInterface.