Builder Pattern

The Builder pattern: constructing a complex object step by step, so a constructor with a dozen optional parameters is never needed.

  • 9 cards
  • 4 questions
  • About 18 min
  • Intermediate to Advanced
Share

Some objects have one or two parts that are required and many that are optional, and a constructor that takes every part in order becomes a row of None values nobody can read. The Builder pattern gives such an object a separate builder: each call sets one part, and a final build() checks the parts and returns the finished object.

This topic opens on that problem and the pattern's intent, then reads its participants off the class diagram, including the optional Director that runs a fixed sequence of steps. The template builds it in Python, Java and TypeScript, with validation in build().

Two examples follow: a report with optional sections, written in Python, and the JDK's HttpRequest.newBuilder(), where build() returns a request that cannot be changed. The comparison asks the question Python forces: keyword arguments with defaults already fix a long constructor, so when does a builder still pay? The gotcha is a builder around three fields, and the exercise builds an SQL query whose clauses are added one condition at a time.

By the end you can recognise a builder from its calls, and decide whether a constructor with named arguments would do the same job.

Contents

9 cardsnot started