I heard it is not really good idea to work with class attributes directly, instead using setters and getters. Can somebody tell me why?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Funnily enough the wikipedia article on this subject gives good guidance: http://en.wikipedia.org/wiki/Accessor
In short, a class should use mutator methods (getters, setters etc) to validate the input before it is stored privately. Doing so ensures the class can always be relied upon elsewhere in the code.
By contrast, if the attribute is globably available, anybody could modify it. If you have, for example, a string that needs to be a specific format and somebody adds a value that isn’t correct, bugs may result.