When are Getters and Setters Justified
- by Winston Ewert
Getters and setters are often criticized as being not proper OO. On the other hand most OO code I've seen has extensive getters and setters.
When are getters and setters justified? Do you try to avoid using them? Are they overused in general?
If your favorite language has properties (mine does) then such things are also considered getters and setters for this question. They are same thing from an OO methodology perspective. They just have nicer syntax.
Sources for Getter/Setter Criticism (some taken from comments to give them better visibility):
http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html
http://typicalprogrammer.com/?p=23
http://c2.com/cgi/wiki?AccessorsAreEvil
http://www.darronschall.com/weblog/2005/03/no-brain-getter-and-setters.cfm
http://www.adam-bien.com/roller/abien/entry/encapsulation_violation_with_getters_and
To state the criticism simply: Getters and Setters allow you to manipulate the internal state of objects from outside of the object. This violates encapsulation. Only the object itself should care about its internal state.
And an example
Procedural version of code.
struct Fridge
{
int cheese;
}
void go_shopping(Fridge fridge)
{
fridge.cheese += 5;
}
Mutator version of code:
class Fridge
{
int cheese;
void set_cheese(int _cheese) { cheese = _cheese; }
int get_cheese() { return cheese; }
}
void go_shopping(Fridge fridge)
{
fridge.set_cheese(fridge.get_cheese() + 5);
}
The getters and setters made the code much more complicated without affording proper encapsulation. Because the internal state is accessible to other objects we don't gain a whole lot by adding these getters and setters.
The question has been previously discussed on Stack Overflow:
http://stackoverflow.com/questions/565095/java-are-getters-and-setters-evil
http://stackoverflow.com/questions/996179