Search code examples
javagetter-settersettergetter

Is It Always Appropriate to Implement Getter and Setter Methods in Java Classes


When creating Java Classes, should getter and setter methods always be implemented? I understand that in some cases, it is undesirable for other classes to be able to be able to change class variables via setter methods, but as long as we implement input validation inside of those methods, is it always appropriate to include them?

If it is not always appropriate to include getter and setter methods, please provide guidelines for when we should specifically implement and not implement them.


Solution

  • In short, there's no hard-and-fast rule.

    You include a getter for a field if you think there's a need for other classes to have access to it. It's entirely appropriate to not have a getter for a field that's entirely internal to your class' workings, and is not intended to be exposed. it's also entirely appropriate to have your getter return not the field itself, but some modified form of it, or an immutable copy of it (e.g., a copy of an internal List field).

    You include a setter if you think there's a need for other classes to have free access to mutate the field. Omitting the setter essentially makes the field read-only. You can also opt to include a custom method to mutate your field, in lieu of the traditional setter (e.g., an add() method to add values to an internal List or Set, just to give an example). All approaches are entirely appropriate, depending on the circumstances.

    EDIT: changed "property" to "field" in line with the established terminology