Is defining get/set methods for every field overkill?

thebluepandabear therealbluepandabear at protonmail.com
Thu Nov 17 06:46:36 UTC 2022


On Thursday, 17 November 2022 at 06:29:56 UTC, Ali Çehreli wrote:
> 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
Appreciate your insight.

Btw I think my example is a bit flawed as the fields are const 😂

I would be interested in hearing your thoughts on using 'const'.

Many people claim that all variables should be const by default, 
but whether or not it is really needed is debatable and 
oftentimes making everything const could cause readability issues 
and make the code more complex. There is no real end to how much 
variables can be const. Oftentimes in popular repos I don't even 
see const being used.

Some languages like Kotlin and Rust are const by default, but for 
languages that are not like D I have always wondered how often 
you should use const.



More information about the Digitalmars-d-learn mailing list