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())
class PizzaBuilder {
private size = "medium";
private toppings: string[] = [];
large(): this { this.size = "large"; return this; } // returning this allows chaining
topping(name: string): this { this.toppings.push(name); return this; }
build(): string {
if (this.toppings.length > 3) throw new Error("max 3 toppings");
return `${this.size} pizza with ${this.toppings.join(", ") || "cheese"}`;
}
}
console.log(new PizzaBuilder().large().topping("olives").topping("basil").build());
console.log(new PizzaBuilder().build());
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
System.out.println(new PizzaBuilder().large().topping("olives").topping("basil").build());
System.out.println(new PizzaBuilder().build());
}
}
class PizzaBuilder {
private String size = "medium";
private final List<String> toppings = new ArrayList<>();
PizzaBuilder large() { size = "large"; return this; } // returning this allows chaining
PizzaBuilder topping(String name) { toppings.add(name); return this; }
String build() {
if (toppings.size() > 3) throw new IllegalStateException("max 3 toppings");
return size + " pizza with " + (toppings.isEmpty() ? "cheese" : String.join(", ", toppings));
}
}
<?php
class PizzaBuilder {
private string $size = "medium";
private array $toppings = [];
public function large(): static { $this->size = "large"; return $this; } // returning $this allows chaining
public function topping(string $name): static { $this->toppings[] = $name; return $this; }
public function build(): string {
if (count($this->toppings) > 3) throw new LogicException("max 3 toppings");
return "{$this->size} pizza with " . (implode(", ", $this->toppings) ?: "cheese");
}
}
echo (new PizzaBuilder())->large()->topping("olives")->topping("basil")->build(), "\n";
echo (new PizzaBuilder())->build(), "\n";
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
- How do you implement a Singleton, and why is it often considered an anti-pattern?
- Explain the SOLID principles.
- What is a design pattern, and why are they useful?
- What is the difference between dependency inversion, dependency injection and inversion of control?
- Why is composition often preferred over inheritance?
- What is dependency injection, and what forms does it take?
- Explain the Factory Method pattern and how it differs from a simple factory.
- What is the Adapter pattern? Give an example.