Possible Duplicate:
Why use getters and setters?
I know this is very trivial. But why do we define private and then we use getter and setters. Is this more like for preventing the programmers from making mistakes on using private variables or methods? Or is it for security reasons. If for security reasons then what is the point of having getters or setters? I know that we can have restrictions inside getter and setter but those if clauses are mostly for preventing the mistakes not the privacy restrictions. E.g. we don't usually say for these members limit the access to this method with an if clause.
Thanks.
The practice of automatically, unthinkingly creating getX() and setX() methods for every variable is bad. It's mostly pointless, as you have observed.
But it's the unthinking part that's bad. Methods are infinitely better than exposed variables because, again, as you observed, you can control how the underlying data is accessed. If you think about what you're doing, and apply mutators and accessors as appropriate, they're a wonderful tool:
synchronized accessors.These are only some of the things you can do with mutators and accessors. By using them, you make your software easy to change and easy to maintain.
If one allows variables from a class to be edited by anyone, then Very Bad Things can happen. (for instance, if an unwary user changes a denominator to zero, we could destroy the universe [or get a divide by zero error]). Defining get() and set() methods allow you (the programmer) to define exactly how others can interact with your variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With