ES6 - Use getters and setters to Control Access to an Object

the getter convert the value, but the converted value should not be saved inside the object, only returned

1 Like

This is going to sound stupid to you, but bear with me to the end:

think of objects as black boxes

Inside the box there is 2 elves. Let’s call these elves Gett and Sett.

They are guarding a vault.

The vault contains a number. We do not know what that number is (but it is a temperature of some kind). We can neither see nor touch that number, only the elves can.

We ask Gett and he says that he can tell us the number in celsius.
We talk to Sett and he says that we can pass him a number in celsius and he will take care of storing it in the vault.

So to us on the outside, Gett gives us celsius value (great) and Sett takes a celsius value and stores it (cool).

BUT

on the inside of the box is a whole other story.

The elves are tricky. Their vault actually contains a number in fahrenheit because their vault was made in the USA and everyone know that Americans like Fahrenheit.

However the rest of the world likes Celsius. So the elves decided to hide this fact by secretly storing the temperature as fahrenheit and yet always talking to the outside world in celsius.

So Sett, he says he will take a Celsius temp and beneath the covers, he is converting it to fahrenheit to store it in the vault (but us outsiders can’t see that).

While Gett, whenever anyone asks, runs to the vault and quickly converts the value to return to the outside world in celsius - ALL THE WHILE KEEPING THE VAULT IN FAHRENHEIT. He’s tricky that way.


I know stupid story.
But the point is, getters and setters are meant to hide the internal data from the outside world. They are an “API” or a layer between everyone else and the data inside the object. The object’s data, if is kept in fahrenheit, stays that way forever.
The getters and setters do the work needed to convert it back and forth without actually modifying the internal representation (the units) of the value.

If someone comes in and says, I want to know the temperature in this object but I want it in units of Kelvin, we could create a new getter/setter to do that, again without modifying our internal representation.

Okay, so now I’ve gone out on a limb (a crazy long one) to explain.
Did it work?

2 Likes

You know what might help, if you named the variable you are storing the temperature in a little more accurately. If you are storing it in F then name it something like _fahr. If you are storing it in C then name it something like _celsius. Then it will be much more obvious when you need to make the necessary conversions.

Personally, I would store it as Celsius in the constructor and then you won’t have to do any more conversions.

Thank you, actually, I do understand more clearly with a metaphoric examples like these. I will give it a go

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