🧩 OOP Concepts Intermediate

What is the Builder pattern?

Why Interviewers Ask This

This tests whether you can apply OOP Concepts knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.

Answer

The Builder pattern separates the construction of a complex object from its representation. It allows creating different representations of the same object step by step. Especially useful when an object has many optional parameters. Problem without Builder: // Telescoping constructor anti-pattern: new Pizza("large", "thin", "mozzarella", "tomato", true, false, true, false); // What does each boolean mean?! Unreadable!. Builder solution: class Pizza { private final String size; private final String crustType; private final String cheese; private final String sauce; private final boolean pepperoni; private final boolean mushrooms; private final boolean onions; private Pizza(Builder builder) { this.size = builder.size; this.crustType = builder.crustType; this.cheese = builder.cheese; this.sauce = builder.sauce; this.pepperoni = builder.pepperoni; this.mushrooms = builder.mushrooms; this.onions = builder.onions; } public static class Builder { private String size = "medium"; // Defaults private String crustType = "regular"; private String cheese = "mozzarella"; private String sauce = "tomato"; private boolean pepperoni = false; private boolean mushrooms = false; private boolean onions = false; public Builder size(String size) { this.size = size; return this; } public Builder crustType(String type) { this.crustType = type; return this; } public Builder withPepperoni() { this.pepperoni = true; return this; } public Builder withMushrooms() { this.mushrooms = true; return this; } public Pizza build() { validate(); return new Pizza(this); } private void validate() { if (size == null || size.isEmpty()) throw new IllegalStateException("Size required"); } } } // Usage: Pizza myPizza = new Pizza.Builder() .size("large") .crustType("thin") .withPepperoni() .withMushrooms() .build();. Benefits: readable construction, optional parameters with defaults, immutable final objects, validation in build(). Real examples: StringBuilder, Java Stream.Builder, Lombok @Builder, OkHttp RequestBuilder, Retrofit.

Pro Tip

This topic has OOP Concepts-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.