20 minlesson

Introduction to Builder Pattern

Introduction to Builder Pattern

Builder separates the construction of a complex object from its representation, allowing the same construction process to create different representations.

The Problem

Complex objects with many optional parameters:

typescript
1// Telescoping constructor anti-pattern
2class Shipment {
3 constructor(
4 sender: Address,
5 recipient: Address,
6 packages: Package[],
7 insurance?: number,
8 signature?: boolean,
9 fragile?: boolean,
10 priority?: boolean,
11 saturdayDelivery?: boolean,
12 // ... more options
13 ) {}
14}
15
16// Hard to use - what do all these booleans mean?
17new Shipment(sender, recipient, packages, 100, true, false, true, false);

The Solution: Builder

Step-by-step construction with fluent interface:

typescript
1const shipment = new ShipmentBuilder()
2 .from(senderAddress)
3 .to(recipientAddress)
4 .addPackage(package1)
5 .addPackage(package2)
6 .withInsurance(500)
7 .requireSignature()
8 .markFragile()
9 .build();

Pattern Structure

typescript
1interface Builder<T> {
2 reset(): this;
3 build(): T;
4}
5
6class ShipmentBuilder implements Builder<Shipment> {
7 private shipment: Partial<Shipment> = {};
8
9 reset(): this {
10 this.shipment = {};
11 return this;
12 }
13
14 from(address: Address): this {
15 this.shipment.sender = address;
16 return this;
17 }
18
19 to(address: Address): this {
20 this.shipment.recipient = address;
21 return this;
22 }
23
24 build(): Shipment {
25 this.validate();
26 const result = this.shipment as Shipment;
27 this.reset();
28 return result;
29 }
30
31 private validate(): void {
32 if (!this.shipment.sender) throw new Error('Sender required');
33 if (!this.shipment.recipient) throw new Error('Recipient required');
34 }
35}

When to Use Builder

  1. Complex construction - Many optional parameters
  2. Step-by-step - Object built incrementally
  3. Validation - Validate before creating
  4. Immutability - Create immutable objects
  5. Different representations - Same process, different results

Benefits

  • Readable, self-documenting construction
  • Prevents invalid object states
  • Separates construction from representation
  • Supports immutable objects

Summary

Builder is ideal for complex objects with many optional parameters. It provides a readable, fluent API and can validate objects before creation.