Description
If a public method returns its private array directly, callers can modify the object's internal state through that reference.
Potential impact
- External code may change role lists, policies, or validated values.
- The object's invariants may be bypassed.
Remediation
- Return a copy using spread syntax,
slice(), orArray.from(). - Expose immutable data structures when callers do not need to modify values.
- A shallow copy still shares nested objects. Copy mutable elements to the required depth or make them immutable.
Examples
Before
javascript
class AccessPolicy {
#roles = [];
getRoles() {
return this.#roles;
}
}
After
javascript
class AccessPolicy {
#roles = [];
getRoles() {
return [...this.#roles];
}
}
getRoles() returns a shallow copy of #roles. Removing an entry from the returned array leaves it in #roles. The arrays still share any objects they contain.