All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.javascript.rules.javascript.S4275.html Maven / Gradle / Ivy

There is a newer version: 10.20.0.29356
Show newest version

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:

  • A setter does not update the field with the corresponding name.
  • A getter does not access the field with the corresponding name.

Noncompliant Code Example

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;
  }
});

Compliant Solution

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;
  }
});




© 2015 - 2025 Weber Informatics LLC | Privacy Policy