Getters and setters provide a way to enforce encapsulation by providing methods that give controlled access to class 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 the following cases:
- A setter does not update the field with the corresponding name (if it exists).
- A getter:
- does not return any value
- does not access the field with the corresponding name (if it exists).
Underscore prefixes for fields are supported, so setX()
can assign a value to _x
.
The following type of getters and setters are supported:
class A {
#y: number = 0;
setY(val: number) { // Noncompliant: field '#y' is not updated
}
}
class A {
#y: number = 0;
setY(val: number) {
this.#y = val;
}
}
class A {
_x: number = 0;
#y: number = 0;
get x() { // Noncompliant: field '_x' is not used in the return value
return this.#y;
}
get y() { // Noncompliant: method may not return any value
if (condition) {
return #y;
}
}
}
class A {
_x: number = 0;
#y: number = 0;
get x() {
return this._x;
}
get y() {
if (condition) {
return #y;
}
return 1;
}
}
- getters and setters defined with
Object.defineProperty()
let x = 0;
let y = 0;
Object.defineProperty(o, 'x', {
get() { // Noncompliant: variable 'x' is not used in the return value
return y;
}
});
let x = 0;
let y = 0;
Object.defineProperty(o, 'x', {
get() {
return x;
}
});