@tera8793863138 @cosmic_noir @jnijnijni
While we can access a property by either its _propertyName or getters and setters,
The importance of getters and setters goes beyond alerting other coders of the privacy of a property, it can help you avoid errors which could make your code do things it shouldn’t, also to have a more readable and allows for easy debugging.
I’m going to try to establish why it is best to use getters and setters.
When we make a variable private, we only want to retrieve or modify the value following due process.
let’s use an analogy of cooking for setters:
let’s say you want to fry plantain, now literally speaking frying is the act of cooking in oil.
Do we just buy plantain and put it in the frying pan containing oil to fry it? NO!!!
Rather we have to follow due process:
- cut the plantain we want from the bunch.
- wash the plantain
- peel off the back
- cut the plantain to size.
- spice it up .
- fry
from the above we can see that while our end goal was to fry plantain , we would not achieve well fried plantain if we don’t follow due process
Now let’s come back to programming,
let person = {
_name: “Messi”,
_age: 33,
get name(){
return `The name of this person is ${this._name}.`
},
get age(){
return `${this._name} is ${this._age}years old.`
},
set age(newAge){
if (newAge > 0){
this._age = newAge
}
else{
console.log("You entered an invalid age,enter an age greater than 0")
}
}
}
console.log(person.age)
person.age = -19
lets assume our end goal is to change the age property of the person object above. We could easily just access the _age property above and reassign it. If we do that, the value changes, but we’ll be forgetting one crucial detail about age: that age can only be positive!
However if we try to reassign the age using our setter above, it first checks if the new age were passing meets our requirements and if it does it reassigns the _age property.
The example above is really simplified in a more complex program a value may need to meet many conditions before it is reassigned as the new value of a property and using setters will ensure that we follow due process before reassigning a property.
On the issue of getters, I feel it’s more about getting the value of a property in the way we want, for example we could store a the value of _temperature in kelvins (S.I unit), but in our getter we may choose to return the output in Celsius or Fahrenheit. Here _temperature can be viewed as a raw unit which if printed we wouldn’t understand. Then the getter returns the temperature in a format/unit we can easily understand.
We could also use this.temperature to get the _temperature within another method in the same object and perform different operations.
In the person object above, our getter for age returns an output that is formatted in an easily understandable way rather just the vague 33.
I hope I’ve been able to convince and not confuse you. 