3 ms·
I've got hundreds in the codebase I manage. Imagine you have a type that represents some domain state. It has a bunch of fields that are used to represent this
by UncleMeat 4y ago
I've got hundreds in the codebase I manage.
Imagine you have a type that represents some domain state. It has a bunch of fields that are used to represent this state. But that state has invariants. There are certain combinations of values that the fields are not allowed to take and they relate to each other in complex ways. A well designed interface to this type is such that every sequence of methods called on one of these objects will maintain the invariants. If you instead just directly expose the fields then absolutely nothing guarantees that the invariants hold.
Yes, if the first thing you do when you create a private field is write a public getter and a public setter then you haven't gained anything. But the power is in not writing these methods.