Search code examples
typescriptoopencapsulationaccessor

Are accessors necessary in Typescript?


I understand the importance of encapsulation in OOP, and accessors (getters/setters) provide this level of abstraction.

However, with Typescript I can substitute my property with accessors at a later date, with the same name, and rename my property to be prefixed with an underscore (therefore not causing a breaking change).

For example I could have:

class foo {

  name: string;

}

Later if I wish to add accessors to this property I could change to the following:

class foo {

  private _name: string;

  get name():boolean {
    return this._name;
  }

  set name(name: string) {
    this._name = name;
  }

}

Is this considered bad practice?

What is the purpose of the accessors in this context?


Solution

  • Accessors are an implementation detail. If you follow "program to the interface, not to the implementaion" rule, users of foo should only see

    interface foo {
        name: string;
    }
    

    How exactly this interface is implemented does not matter. It could be a class with getters and setters, a class with public property, or even a plain object.

    Whichever is best is determined by the constraints that particular implementation must obey. In most cases, accessors don't seem to be necessary, but could be convenient sometimes.