Builder Pattern

The Builder pattern belongs to a group of patterns whose existence is not particularly clear to me, I note a clear redundancy of this. Refers to a group of generative design patterns. Used to implement a simple interface for creating complex objects.

Usage

Simplification of the interface. It can facilitate the creation of an object in constructors with a large number of arguments, objectively improve the readability of the code.

C ++ example without a builder:


auto monster = new Monster();
auto weapon = new Weapon(“Claws”);
monster->weapon = weapon;
auto health = new MonsterHealth(100);
monster->health = health;

C ++ example with a builder:


auto monster = new MonsterBuilder()
              .addWeapon(“Claws”)
              .addHealth(100)
              .build();

However, in languages ​​that support named arguments, there is no need to use it for this particular case.

Swift example using named arguments:


let monster = Monster(weapon: “Claws”, health: 100)

Immutability. Using the builder, you can ensure the encapsulation of the created object, until the final stage of assembly. Here you need to think carefully about whether the use of the pattern will save you from the high dynamics of the environment in which you work, perhaps the use of the pattern will not work, due to the simple lack of culture of using encapsulation by the development team.

Interaction with components at different stages of creating an object. Also, using the pattern, it is possible to provide step-by-step creation of an object when interacting with other components of the system. Most likely it is very useful (?)

Critics

Of course you need to * thoroughly * think about whether it is necessary to establish the widespread use of the pattern in your project. Languages ​​with modern syntax and an advanced IDE eliminate the need to use the Builder in terms of improving the readability of the code (see paragraph on named arguments)
Was it necessary to use this pattern in 1994, at the time of the release of the GoF book? Most likely yes, however, judging by the Open source code base of those years, few people used it.

References

https://refactoring.guru/design-patterns/builder