Design Patterns interview question · Most asked

What problem does the Builder pattern solve? Show an example.

Summary

Builder assembles complex objects step by step with named, chainable methods and a final build() that validates the combination. It replaces telescoping constructors and unreadable positional arguments.

Longer Answer

A builder keeps defaults, lets callers set only what they need (.timeout(5).header(...)), and checks invalid combinations (a GET with a body) in build(), close to where the object is assembled. The product can be immutable.

In Python, PHP 8 and TypeScript, named arguments and object literals remove much of the need; builders still shine for validation, fluent APIs (query builders) and test data builders.

Code Example

class PizzaBuilder:
    def __init__(self):
        self.size, self.toppings = "medium", []

    def large(self):
        self.size = "large"
        return self  # returning self allows chaining

    def topping(self, name):
        self.toppings.append(name)
        return self

    def build(self):
        if len(self.toppings) > 3:
            raise ValueError("max 3 toppings")
        return f"{self.size} pizza with {', '.join(self.toppings) or 'cheese'}"


print(PizzaBuilder().large().topping("olives").topping("basil").build())
print(PizzaBuilder().build())

Key Points

  • Named, chainable steps; build() validates.
  • Replaces telescoping constructors.
  • Product can be immutable.
  • Named arguments often suffice in Python/PHP/TS.

Deep dive: Design Patterns, Explained Simply: Builder

Explanation

What interviewers look for

Chaining, validation in build(), defaults, and awareness of named arguments as an alternative.

Follow-up questions

  • What is a director in the Builder pattern?
  • Give a real library that uses Builder.

More most-asked Design Patterns questions

← All Design Patterns questions