How are getter-setter better than direct access to attributes? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

28th Jul 2018, 3:29 PM
Amitrajit Bose
Amitrajit Bose - avatar
1 Answer
+ 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.
28th Jul 2018, 4:00 PM
Steppenwolf
Steppenwolf - avatar