|
|
|
|
|
by HumanDrivenDev
3151 days ago
|
|
But by definition getters and setters lack lexibility. They expose the internal representation of an object. They stop really being "objects" - high level opaque things you send messages to - and they turn into big porous bags of fields. To clarify, I would not consider something like this a setter: class Monster {
int health;
void Damage(int d) {
this.health -= d;
}
}
True, it is a method that just sets a variable. But it makes no mention of that variable. It's defined in terms of its actual purpose (inflicting damage on a monster), not its implementation (modifying an internal field called 'health').There is definitely a time and place for plain data objects. But if you find yourself actually needing validation and preprocessing in your get/set, then you probably have a 'real' object hiding their. Stop being lazy and give it proper methods. |
|
That said, I don't agree with your argument in all cases. Some classes really are relatively passive carriers of data. My favorite example is AST node classes in a compiler; the logic that controls the transformations applied to these is naturally outside the classes, because most of the interesting postconditions and invariants apply to the entire AST of which each node is only a small part.