Why do we need to use the builder design pattern when we can do the same thing with setters?
The builder pattern can be useful to:
- apply some check on the data used to initialize the object. For example if you need a double check between variables
- create immutable objects. You can't change an object once initialized, so you can't use setters
- add readability of code.
- reduce the code used to initialize the object
- have the instance in a valid state. Using setters the object instance can be in a not valid state before all the setters are called.
Note on using the builder to create immutable objects.
When you work in a multithread environment an immutable object can be shared between threads without explicit synchronization. Because the object can't change during the time is not possible to have a race condition accessing and modifying it by two threads at the same time.
There is no need to use any pattern. You can even avoid setters with making the variables public. However,
the intent of the Builder design pattern is to separate the construction of a complex object from its representation
Source: https://en.wikipedia.org/wiki/Builder_pattern
Using a builder pattern has a few advantages:
Unlike with setters (which make your class mutable), a builder can be used to contruct immutable objects. In many cases immutable objects are preferred over mutable objects, because they are easier to understand and maintain, and because they avoid the need for locking in multithreaded environments.
A builder can make sure that the object satisfies some invariants even directly after construction. For example, if your class has a
name
field which must never benull
, the builder can check this condition and fail to construct the object when not satisfied.
Both things you can also accomplish by using a constructor which takes all the class contents as parameters, but that will be quite unreadable when your class has more than a few fields to initialize.