Difficulty
 

Builder Pattern

Why use builder pattern if:

  • our constructor consists of more than 3 (according to clean coding practice) parameters
  • we expect our constructer to grow in the future
  • not all fields of an object are required

When we add a new value to the existing constructor, we can do so:

  1. by adding a new parameter to the existing constructor – very difficult to maintain
  2. add additional constructor – too many constructor would be difficult to manage
  3. using setter methods instead of constructor to configure the object – works only for mutable objects, it could lead to an invalid state of an object being exposed (when setting attributes one at the time)
  4. we use builder pattern

Blocks:

  • builder object
  • method chaining (builder methods can be called in any order)
  • final build call

Not all fields have to be required. We can set default values. If we want to make sure field is set, we can throw an exception when building the object (in build() method).

Last update 16.07.2019.
For possible mistakes in content or typos, I apologise and kindly ask you to report here.