7
← Back to Pattern Arsenal
creational

Builder

must know

Stage 1: Problem

Problem

You are building a notification service. A notification has many optional parts:

  • channel: email, SMS, push, Slack, webhook (can be multiple)
  • recipient: userId, email address, phone number, Slack channel
  • template: a named template with variable substitution
  • subject: for email only
  • body: plain text or HTML
  • attachments: optional file references
  • scheduling: send now, delay by N minutes, send at specific time, or within a time window
  • retry policy: max attempts, backoff strategy (fixed, exponential)
  • priority: low, normal, high, critical
  • metadata: arbitrary key-value pairs for tracking
  • deduplication key: prevent duplicate sends within a window
  • expiry: message expires after N hours (don't deliver stale notifications)

The notification object is immutable once built — it gets serialized to a queue.

Challenges:

  1. A constructor with 12+ parameters is unreadable and error-prone (what's the 7th argument again?)
  2. Many parameters are optional, leading to dozens of constructor overloads or a single constructor with tons of undefined values
  3. Some combinations are invalid: SMS notifications can't have attachments; push notifications require a device token; email requires a subject
  4. You want to validate the complete notification at build time, not after it's halfway through the pipeline

How would you design a clean API for constructing these notifications?


Related Patterns

Confused With a Similar Pattern?

1 / 10 — Problem