Quantcast
Viewing latest article 36
Browse Latest Browse All 38

Answer by Thomas Owens for Why use getters and setters/accessors?

One advantage of accessors and mutators is that you can perform validation.

For example, if foo was public, I could easily set it to null and then someone else could try to call a method on the object. But it's not there anymore! With a setFoo method, I could ensure that foo was never set to null.

Accessors and mutators also allow for encapsulation - if you aren't supposed to see the value once its set (perhaps it's set in the constructor and then used by methods, but never supposed to be changed), it will never been seen by anyone. But if you can allow other classes to see or change it, you can provide the proper accessor and/or mutator.


Viewing latest article 36
Browse Latest Browse All 38

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>