Is defining get/set methods for every field overkill?
Alexandru Ermicioi
alexandru.ermicioi at gmail.com
Mon Nov 21 11:20:31 UTC 2022
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?
Dunno if someone mentioned, but you can minimize use of
boilerplate by hiding it into mixin templates. Say you have:
```D
mixin template Property(T) {
private T subject_;
T Property() { return subject_; }
void Property(T value) { subject_ = value; }
}
```
The you can use it in your class to define properties of class:
```D
class MyMegaPropertyClass {
mixin Property!(string) myFancyProperty;
}
auto c = new MyMegaPropertyClass()
c.myFancyProperty = "indeed"
```
The only issue is that, by using eponymous naming you also block
any access of underlying subject_ or any other miscellaneous info
that you may add.
Best regards,
Alexandru.
More information about the Digitalmars-d-learn
mailing list