Named constructors

Per Nordlöw per.nordlow at gmail.com
Thu Dec 12 07:55:14 UTC 2024


On Saturday, 9 November 2024 at 00:02:52 UTC, JN wrote:
> Let's say you want to have an Angle class, which holds radians 
> internally but can be initialized with degrees or radians.

I would refactor this into a type-driven design via

```d
struct Radians {
    private float _value;
    // various property functions to access `_value`.
}
struct Degrees {
    private float _value;
    // various property functions to access `_value`.
}

class Angle
{
     float radians;

     this(Radians rad) : radians(rad) { }
     this(Degrees degs) : radians(degs * (PI / 180.0f)) { }
}
```

. Now you can use

```d
Angle(Radians(0.0));
Angle(Degrees(0.0));
```

or

```d
Angle(rad: Radians(0.0));
Angle(deg: Degrees(0.0));
```

for extra verbosity.

This is the beginning of a units of measurements module/package 
similar to, for instance, https://code.dlang.org/packages/units-d.

See also https://en.wikipedia.org/wiki/Unit_of_measurement.


More information about the dip.ideas mailing list