Getters and setters provide a way to enforce encapsulation by providing public methods that give controlled access to
private fields. However in classes with multiple fields it is not unusual that copy and paste is used to quickly create the needed
getters and setters, which can result in the wrong field being accessed by a getter or setter.
This rule raises an issue in any of these cases:
class A {
#x: number = 0;
#y: number = 0;
get x() { // Noncompliant: field 'x' is not used in the return value
return this.#y;
}
set x(val: number) { // Noncompliant: field 'x' is not updated
this.#y = val;
}
getY() { // Noncompliant: field 'y' is not used in the return value
}
setY(val: number) { // Noncompliant: field 'y' is not updated
}
}
const obj = {
_x: 0,
_y: 0,
get x() { // Noncompliant: field '_x' is not used in the return value
return this._y;
}
};
let x = 0;
let y = 0;
Object.defineProperty(o, 'x', {
get() { // Noncompliant: variable 'x' is not used in the return value
return y;
}
});
class A {
#x: number = 0;
#y: number = 0;
get x() {
return this.#x;
}
set x(val: number) {
this.#x = val;
}
getY() {
return this.#y;
}
setY(val: number) {
this.#y = val;
}
}
const obj = {
_x: 0,
_y: 0,
get x() {
return this._x;
}
};
let x = 0;
let y = 0;
Object.defineProperty(o, 'x', {
get() {
return x;
}
});