References https://refactoring.guru/design-patterns/builder (Builder pattern explanation) https://projectlombok.org/features/Builder (Lombok) What is Builder? Creational design pattern A design pattern that allows you to construct complex objects step-by-step. Allows you to create different types of objects with the same construction code. Situation You need to create a complex object with many fields and nested objects. Not Recommended Method 1 - Implementation via Class Inheritance Method Description Create a base class Suppose you create a base class called House. This class has a roof, windows, and exterior walls. You make it with specific field values. In other words, you create classes like CabinHouse and BrickHouse. For example, the exterior wall of CabinHouse is wood, and for BrickHouse, it is brick. For extension - create a subclass If you want to make a cabin house with a storage room, you inherit from CabinHouse and add a storage room. Problems You end up with countless subclasses Because you have to create a new subclass for every new parameter. The hierarchy can become deep Inheritance forms a hierarchical structure. If you want to extend not with an annex but with a style (e.g., modern), you have to make it one level deeper. Not Recommended Method 2 - Giant Constructor Method Description Write a constructor that takes all possible parameters. Problems You have to consider unnecessary parameters and put them as arguments As shown on the left of the figure above, even when creating a regular house with only a storage room, you have to consider other options and put null for them. It’s hard to figure out the meaning of each argument When there are many parameters, it’s hard to know what each argument means. Solution - Builder Pattern The Builder pattern moves the object creation code outside the class to be created. It delegates the creation responsibility to individual objects called builders. These builders:
...