Sunday 16 July 2017

Why do people hide all class variables behind getters?

I have seen the following pattern several times:class Cat { constructor(id, name, species) { this._id = id; this._name = name; this._species = new Map(species); } get id() { return this._id; } get name() { return this._name; } get species() { return this._species; } } I understand that this is implying that id, name, and species are supposed to be read only. However at the same time, it just feels like it bloats the code. I can understand if your creating a getter for a case where you are computing the property value on the fly.However is this really that much better than this:class Cat { constructor(id, name, species) { this.id = id; this.name = name; this.species = species; } } I am going through code where a class has 15+ getters for nothing other than properties passed into the object, which feels like a huge waste. Is there some better reason for this?

Submitted July 16, 2017 at 08:20PM by frankimthetank

No comments:

Post a Comment