On Thursday, 17 November 2022 at 04:39:35 UTC, thebluepandabear wrote:
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?

Obligatory note that boilerplate https://code.dlang.org/packages/boilerplate exists for just this reason:

    class Label : Renderable {
        @ConstRead
        private const string text_;

        @ConstRead
        private const TextAlignment textAlignment_;

        @ConstRead
        private const Color color_;

this(Dimensions dimensions, string text, TextAlignment textAlignment, Color color) {
            this.dimensions_ = dimensions;
            this(text, textAlignment, 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;
        }

        mixin(GenerateFieldAccessors);
        mixin(GenerateThis);
    }

Reply via email to