Honest question: why put every field of a struct of your public API behind a getter&/setter? What's the point? Why not just expose the field?
Conversation
Replying to
I like using builders that validate the fields instead of setters.
Ideally when you have getters some sort of invariant is maintained.
3
9
Replying to
Yeah builders are great... I was more thinking about getters than setters actually
1
1
Replying to
There's no point to getters if no invariant is being maintained. Just make the fields public in that case.
They're nice when the type makes invalid states unrepresentable.
1
6
It also keeps open the possibility of adding logic in the future without a backwards incompatible change to the API. For example, it may become desirable to have setting a field regenerate a cache or to change the way it's stored. It's very relevant if it's a public library API.
1
3
It's rare to have a way to allow direct access but not direct assignment without making the field read-only.
Some languages support overriding getting/setting fields with methods so it can be freely switched between direct access or methods without changing the API externally.
1
1
Examples:
docs.microsoft.com/en-us/dotnet/c
docs.python.org/3/library/func
Some languages use this pervasively and it's unidiomatic to have getters/setters simply taking one parameter and not returning anything. Other languages have this feature but tend to look at it as unnecessarily magical.


