Is defining get/set methods for every field overkill?
Ali Çehreli
acehreli at yahoo.com
Thu Nov 17 06:29:56 UTC 2022
On 11/16/22 20:39, thebluepandabear wrote:
> I am debating whether or not I should add getter methods to these
> properties.
If you are debating, then the answer is easy: you should not. :)
Less code written means less bugs, more cohesion, easier refactoring,
cleaner code, all good stuff...
Even if a design requires e.g. a 'length' method, the default one should
be a getter. A setter will come in the future only if 'length = 42' is
clearly better than e.g. 'expandTo(42)'.
> in other languages like Java it is a good practice:
I've seen so many tutorials where any user-defined type immediately
defines getters and setters. It is never good style to do that. There
are good examples of where doing that is clearly wrong. For example, can
a Date class really provide a setMonth() setter? It would be so wrong, I
don't even know where to begin. (I remember talks by Kevlin Henney where
he would use that example.)
The guidelines I follow are simple in the following order:
- Don't write any code until it makes sense :)
- Don't write a getter until it makes sense
- Don't write a setter until it makes sense
Ali
More information about the Digitalmars-d-learn
mailing list