Question

Consider following case

public void setRules(MyRule[] rules) {
    this.rules=rules;
}

Sonar complain and says,

Constructors and methods receiving arrays should clone objects and store the copy. This prevents that future changes from the user affect the internal functionality.

This is true and I got the point when some one change the value of array after setting this, That change may effect to inside functions. If we clone that array changes will not effect.

Now consider another case

public void setExecutions(List<MyRule> ruleList) {
    this.ruleList= ruleList;
}

Now Sonar not telling any issue. why clone is not needed here?

Was it helpful?

Solution

In fact there can be only one motivation behind this PMD rule : primitives are passes by value and objects are passes by reference. What about arrays ? arrays are objects in Java and so are also passes by reference but some junior developers may not be aware of that and might believe that the whole array is passes by value. Personally I think this rule is valueless.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top