|
|
|
|
|
by ScottBurson
3155 days ago
|
|
This is a good argument and I have considerable sympathy with it, but it's actually not an argument against using getters and setters; it's just an argument for making them nonpublic. In a tiny example like this it obviously doesn't matter, but in a large, complex class it can be useful, in my experience, for all assignments to a field to go through a setter. As others here have argued, this provides a convenient hook for changing the behavior of all such assignments -- a hook which is maybe not often needed, but very useful when it is needed. 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. |
|