When I first started learning about Object-Oriented Programming, I came across the concept of using getters and setters.
I understood how it worked but not why you need it. Getters and Setters are typically used for Encapsulation. Encapsulation is just a fancy way to say that some data should be private and the data is only accessible through the current class.
You use a getter to get the value of a variable. You use a setter to set the value of a variable.
So if you get the variable with a getter and you set it with a setter function, why use getters and setters in the first place? Why not just read and set the value of a variable directly?
The reason why is so you can control what is read or what is set. In the getter, you can alter what is returned.
Let’s see a real example for a getter. Say you have an instance of a Person class with an age variable. The age attribute for this instance is: age = 20.
If you directly read the age,
person.age you get 20. However, if you use a getter, you can return “20 years old”. Or if the age is under 18, you can return “The user is under 18 years old”.
Basically, you control exactly what is returned.
With the setter, you control what data is set. Let’s see you have a first name attribute. You can directly set it like
person.name = 'uhded'. But let’s say the first letter has to be capitalized before you set the attribute. In the setter, you can capitalize the name before saving it. So it would end up being saved as ‘Uhded’ instead of ‘uhded’.
I hope I was able to simplify the concept of getters and setters.