Is defining get/set methods for every field overkill?

thebluepandabear therealbluepandabear at protonmail.com
Thu Nov 17 04:39:35 UTC 2022


I am creating a TUI library and I have a class with the following 
constant fields:

```
class Label : Renderable {
     const string text;
     const TextAlignment textAlignment;
     const Color color;

     this(Dimensions dimensions, string text, TextAlignment 
textAlignment, Color color) {
         this.dimensions = dimensions;
         this(text, textAlignment, color);
     }

     this(string text, TextAlignment textAlignment, Color color) {
         this.text = text;
         this.textAlignment = textAlignment;
         this.color = color;
     }

     override Cell[] render() const {
         Cell[] cells;

         for (int x = 0; x < 0 + text.length; ++x) {
             cells ~= Cell(Coordinates(x, 0), text[x], color);
         }

         return cells;
     }
}
```

I am debating whether or not I should add getter methods to these 
properties. On one hand, it will inflate the codebase by a lot, 
on the other hand -- in other languages like Java it is a good 
practice:

```
class Label : Renderable {
     private const string text;
     private const TextAlignment textAlignment;
     private const Color color;

     this(Dimensions dimensions, string text, TextAlignment 
textAlignment, Color color) {
         this.dimensions = dimensions;
         this(text, textAlignment, color);
     }

     this(string text, TextAlignment textAlignment, Color color) {
         this.text = text;
         this.textAlignment = textAlignment;
         this.color = color;
     }

     string getText() const {
         return text;
     }

     TextAlignment getTextAlignment() const {
         return textAlignment;
     }

     Color getColor() const {
         return color;
     }

     override Cell[] render() const {
         Cell[] cells;

         for (int x = 0; x < 0 + text.length; ++x) {
             cells ~= Cell(Coordinates(x, 0), text[x], color);
         }

         return cells;
     }
}
```

It's not a lot of code that has been added but if you have a 
class with say 10 different fields, adding getter methods would 
definitely increase the code size by a lot, so what are you guys 
thoughts on this?


More information about the Digitalmars-d-learn mailing list