Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why setter and getter methods [duplicate]

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.

like image 276
Sara Avatar asked Dec 01 '25 05:12

Sara


2 Answers

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:

  • You can restrict clients to only reading, but not writing to a variable.
  • You can restrict the values of an integer to only positive values (for example).
  • You can ensure that one variable is always equal to one-half the value of another (for example).
  • You can ensure that, any time the value of a variable is changed, an event is sent to notify other clients.
  • You can change the data type of an underlying variable, perform conversions in the public methods, and not break any clients.
  • You can convert an object to a remote client for a server-side version of the same object, and again, the client code won't change.
  • You can ensure strict memory ordering across threads by using 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.

like image 178
Ernest Friedman-Hill Avatar answered Dec 02 '25 17:12

Ernest Friedman-Hill


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.

like image 37
SomeKittens Avatar answered Dec 02 '25 17:12

SomeKittens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!