What is the objective of adding get method in objects if this is just for returning the property without needing to add conditions

Hello all,

I have just finished the lesson on Objects and i’m dealing with the 2 mini projects:

  • Meal Maker
  • Team Stats

In those 2 projects, we are asked to add getter methods that return the property itself and that’s it.
What is the objective of this?
I mean: for the Team Stats project for example, we obtain the exact same result without the get methods if in the 2 fuctions addPlayer and addGame we call: this._players.push(player) instead of this.players.push(player) and this._games.push(game) instead of this.game.push(game).

Can someone explain to me the purpose of the get method for that Team Stat project?

We could do more useful things, like change the default behavior of a property:

myObj = {
  _a: [1, 2, 3],
  get a()
     return this._a.join('-')
  set a(valIn)

myObj.a = 4

we could then add validation to the setter (that the input has to a number for example)

The problem (In my opinion) with the way JS implements getters is not enforcing proper encapsulation.

With proper encapsulation+ inheritance getters and setters really start coming alive. We could implement that the child class can use the getter (protected) but not on the instance itself.

Thank you for your answer. Actually i was not putting in question the usefullness of getter and setter methods when it actually links the object property to a function that does something else than only return the property of the object in question. I was wondering the interest of doing it, in the context of the Team Stat project because for me it doesn’t add anything that would justify the need to have a get method on the code.

Some of these projects do implement mostly default behavior for getter, not adding much value except offering the possibility of doing useful things with getters and setters once you start expanding the project

bit of shame/missed opportunity

1 Like