Help understanding getters/setters

I am having a tough time grasping the purpose of getters and setters. Could somebody explain them to me as if I was a 5 year old?

class Thermostat {
  constructor(Fahrenheit){
    this.Fahrenheit = Fahrenheit;
  }

  get temperature() {
    return (5 / 9) * (this.Fahrenheit - 32);
  }

  set temperature(C) {
    this.Fahrenheit = (C * 9.0) / 5 + 32;
  }
}

A “setter” is a function that lets you update data. A “getter” is a function that lets you access that data.

1 Like

So in this case the setter lets me update this.Fahrenheit?

So getters and setters are not exclusive to classes. We can also use them in any type of object. The purpose of a getter or a Setter is to allow us to access a function on the object but treated as data.

A very common use for me of Getters and Setters is in a factory function. When I put get/set in my returned object, they have access to private variables within the factory. What that means is I have protected internal state for my Factory, but I have get and set interface methods which allow me to affect that.

Another interesting use case for Getters and Setters (particularly getters) is when we save our objects as Json data. The getter is not treated as a function, but as it’s return value. So getters get saved into a Json object, while functions do not.

1 Like

Thanks 4 that explanation. now understand getters and setters a little bit more

1 Like

i think the point of the exercise is, in part, you can set the Fahrenheit whilst inputting Celsius. so you don’t even need to know that the thermostat is using Fahrenheit. you just use whichever you want and it works.

1 Like

In large part, i think you’re right. It shows how you can use getters and setters as a data transformation and assignment. We take the F, transform that, and assign it to a property (in this case) or a variable (in the factory case).

Further, a getter can return values that aren’t there - getting a temp could be simply returning the C, or converting it internally and returning the F.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.