+ 1
How are getter-setter better than direct access to attributes?
According to the lessons, it tells us to use PRIVATE attributes of the class. Then declare methods in the class for setting and getting values. We can also set or get the value directly by creating an object like: <obj.name>.<attributeName>=<new value> So the above is a Setter. Which can be used instead of setAttribute(newValue). Which one is better and WHY?
1 Odpowiedź
+ 2
Getters&setters give you centralized control on how a particular field is initialized - you can do validation checks in these methods.
It makes debugging easier.
When you have no getters&setters, you can not change internal representation or make it better until making changes in the whole code.
Every code change comes with risk and cost of regression testing is high during maintenance.
You should always use getters&setters.