Why do we need to define getters and setters?
Printable View
Why do we need to define getters and setters?
Getters and setters provide a public interface to your class with which you can manipulate the values of member variables. Setters are used to control if new values are allright.
Furthermore (and possibly more important), getters and setters are used to maintain the concept of encapsulation. You declare all member variables as private and provide getters and setters for them.
----------------
You can contact me directly at Christoph.Schulze@gmx.co.uk
Don't forget your parsley cause you can't eat your dog after having stolen him from some animal shelter and having drowned him in the Atlantic Ocean.
Captian Nuss is right. In general, the class should have full responsibility for its own data, and other classes may only request that a change be made or some data returned. So getters and setters, together with private data, give the class complete control. This means that as long the signature of the getters and setters doesn't change, the internal data can be managed however the class sees fit by using the getters and setters to 'translate'. For example, the data could be held as class data members in memory or stored only as rows in a database, but the user of the class doesn't have to know or care. The data storage method and/or type in the class can be changed without affecting any other code that uses that class.
The getters and setters are also the place to do checks on requests for data change or return. Invalid change values can be rejected, user permissions can be checked for access, changes can be logged, and debugging code can help you track what's happening to the data.
Dave
To email me remove '_spamjam' from my email address