2

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?

Curtis
  • 101,612
  • 66
  • 270
  • 352
  • 1
    Such accessors have no purpose. They would have if they did something other than what a simple public field does (like computing some other property when the setter is called, for example). – JB Nizet Jun 26 '18 at 18:49

1 Answers1

4

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.

artem
  • 46,476
  • 8
  • 74
  • 78