Grokking Design Patterns for Engineers and Managers
Vote

0% completed

Builder Pattern

The Builder Pattern assembles a complex object step by step, so callers never face a constructor with a dozen arguments.

An object gains fields. Most of them are optional. The constructor grows until the call looks like this:

new HttpRequest(url, "GET", headers, null, 30, 3, true, false, null);

Nobody can read that. Which of the two nulls is the body? What is true? Swap the two booleans and it still compiles, and the bug shows up in production as requests that follow redirects when they should not.

.....

.....

.....

Like the course? Get enrolled and start learning!
Ioana T

Ioana T

· 9 days ago

HawaiianPizza pizza = new HawaiianPizzaBuilder() .addCrust("thin") .addTopping("ham") .addTopping("pineapple") .build(); Always returning the current Builder object when add more parameters allows you to chain together endless options/set however many params you need until building the object. It is also a language agnostic practice.

Show 1 reply
Ioana T

Ioana T

· 9 days ago

It should be mentioned that it is common practice in a Builder class to always return the Builder object when setting or adding a component for readibility/API ergonomic purposes and to return to object that is getting built, when calling a final build().

addCrust(), addTopping() inside HawaiianPizzaBuilder should return HawaiianPizzaBuilder object itself and then finally when calling build() at the end of the construction process the HawaiianPizza object should be returned....

Show 1 reply

Reading Progress

0%


Vote for new content