S2384: Mutable members should not be stored or returned directly
Environment:
SonarQube Version: 10.0.0.68432
Description:
The rule S2384 is triggering a violation for storing mutable arrays directly in private constructors. I believe this may be a false positive, as private constructors do not receive user-supplied arrays from outside the class.
Here’s the code sample that triggers the false positive:
public class AISD {
private final byte[] buf;
private AISD(final byte[] buf) {
this.buf = buf; // FP
}
private void set(final byte[] buf) {
this.buf = buf; // FP
}
public AISD of(final byte[] buf) {
return new AISD(buf.clone());
}
}
Thanks for your message. I feel like your example won’t compile. I suspect you wanted to remove final from byte[] field declaration and a method of(.) is supposed to be static.
In the case you showed, you’re right the only place, where the private constructor is called is in of method and it makes a clone, so eliminates the risk of exposing an array buf and modifying it outside of the class.
However, nothing stops you to have more public methods that invoke your private constructor or private setter. So to eliminate these false positives in the ideal world the rule should rely on the data flow. Unfortunately, this rule is AST-based, and it brings some limitations. Maybe we will rethink this approach in the future, but currently, we have no such plans.
So, anyway, I created a ticket, so we can see what we can do to report less FPs and still produce valuable results: