Builder: Tiny Utility Library to Add a Builder API to Classes

Vijay Nayar madric at gmail.com
Thu Jan 5 21:48:40 UTC 2023


https://code.dlang.org/packages/builder

Interacting with many projects that are related to Java, I could 
not help notice that a common "Builder API" is not easily 
available in D.

What is the problem? When constructing classes, especially those 
with lots of data, there are two broad ways of building the 
object.

1. Initializing each field in a different statement.
```
A a = new A();
a.setName("Bob");
a.setAge(20);
a.isProbation(false);
a.isActive(true);
...
```

This approach involves writing a lot of boiler plate, and it 
doesn't work well for quickly creating objects inline, such as 
during a function call.

2. Using a constructor with many arguments.
```
A a = new A("Bob", 20, false, true);
```

This approach can construct arguments inline, such as during a 
function call, however, the arguments are not labeled, making it 
easy to get the order wrong or for the meaning to be unclear.


This library allows one to get the best of both worlds. 
Construction within a single statement, but also without losing 
meaning of the parameters, e.g.

```
class A {
   string name;
   int age;
   bool isProbation;
   bool isActive;

   mixin AddBuilder!(typeof(this));
}

A a = A.builder()
   .name("Bob")
   .age(20)
   .isProbation(false)
   .isActive(true)
   .build();
```


More information about the Digitalmars-d-announce mailing list