How do I generate `setX` methods for all private mutable variables in a class?

Paul Backus snarwin at gmail.com
Mon Jun 5 15:28:34 UTC 2023


On Monday, 5 June 2023 at 13:57:20 UTC, Ki Rill wrote:
> How do I generate `setX` methods for all private mutable 
> variables in my class? Do I need to use `__traits`?
>
> I need this for my 
> [tiny-svg](https://github.com/rillki/tiny-svg) project to 
> generate `setX` methods for all Shapes.
>
> Example:
> ```D
> class Rectangle {
>     private immutable ...;
>     private Color fillColor;
>     private Color strokeColor;
>     private uint strokeWidth;
>
>     this(int x, int y) {...}
>
>     mixin(???);
>
>     // I need this:
>     Rectangle setFillColor(Color color) {...}
>     Rectangle setStrokeColor(Color color) {...}
>     Rectangle setStrokeWidth(uint color) {...}
> }
> ```

Is there a reason you can't just make these fields `public`?

D supports property accessors, so you can always go back and make 
them `private` later on if it turns out you need to. For example:

```d
// Before
class MyClass1
{
     public int data;
}

void example1(MyClass1 c)
{
     c.data = 123; // set
     int n = c.data; // get
}

// After
class MyClass2
{
     private int data_;
     int data() { return data; }
     void data(int value) { data = value; }
}

void example2(MyClass2 c)
{
     // Usage is exactly the same
     c.data = 123; // set
     int n = c.data; // get
}
```


More information about the Digitalmars-d-learn mailing list