Hi I would like to discuss about the rules S1319 and S1948 and more precisely about the following thread and ticket :
The ticket has relaxed the rule S1319 in order to avoid false positives due to the declaration of private fields not using a Java Collections interface. However this is not sufficient IMHO.
If we look at the following code, we see that S1948 will raise an issue du to the fact that java.util.Map is not Serializable :
public class AClass implements Serializable {
private Map<String,String> map = new WeakHashmap<String,String>(); // Noncompliant
private Map<String,String> map = new Hashmap<String,String>(); // Noncompliant according to S1948... but is there really a problem ?
}
This issue seems legit at first sight as Map, List, Iterable, etc. interfaces do NOT extend Serializable. However this is disputable. First, java.util.WeakHashMap, java.util DelayQueue are the only Collections classes not being Serializable and they are not widely used (I never used them so far). Second, interface based programming and decoupling interfaces from implementations provides great changeability benefits.
Therefore I would like to suggest the following improvement to rule S1948 :
- if the type of the field is a Java Collection interface, then an issue should only be raised if a non Serializable implementation of the interface is assigned to the variable and if the field is not final (which implies that the value of the field will be set at instanciation time).
The result would be :
public class AClass implements Serializable {
private Map<String,String> map = new WeakHashmap<String,String>(); // Noncompliant : WeakHashMap is non Serializable
private final Map<String,String> map2 = new WeakHashmap<String,String>(); // Noncompliant : WeakHashMap is non Serializable
private final Map<String,String> map3 = new Hashmap<String,String>(); // Compliant
private final Map<String,String> map3;
public AClass() {
this.map3 = new HashMap<String, String>(); // Compliant
this.map3 = new MyCustomSerializableMap<String,String>(); // Maybe noncompliant : we're not sure that this custom Map will be available at deserialization
}
}
Your opinion ?
Regards,
Michel