Skip to main content

Builder Pattern

Updated Markdown
Part of seriesLow Level Design LLD
Builder Pattern

The Builder Pattern is a creational design pattern that provides a flexible solution to constructing complex objects. Unlike other creational patterns that focus on object instantiation, the Builder Pattern separates the construction of a complex object from its representation, allowing the same construction process to create different representations.

The Problem

Imagine you're building a system that needs to create complex objects with many optional parameters. You might face several challenges:

  • Telescoping Constructor Anti-pattern: Creating multiple constructors with different parameter combinations becomes unwieldy and hard to maintain.

  • Readability Issues: Long parameter lists make code difficult to read and error-prone.

  • Immutability Constraints: You want to create immutable objects, but setting many fields through setters violates immutability.

  • Validation Complexity: Complex validation logic scattered across constructors makes maintenance difficult.

The Telescoping Constructor Problem

public class Computer {
    // Telescoping constructors - hard to maintain!
    public Computer(String cpu, String ram) { ... }
    
    public Computer(String cpu, String ram, String storage) { ... }
    
    public Computer(String cpu, String ram, String storage, String gpu) { ... }
    
    public Computer(String cpu, String ram, String storage, String gpu, 
                    boolean hasWiFi) { ... }
    
    public Computer(String cpu, String ram, String storage, String gpu, 
                    boolean hasWiFi, boolean hasBluetooth) { ... }
}

// Usage - confusing and error-prone
Computer pc = new Computer("Intel i9", "32GB", "1TB SSD", "RTX 4090", true, true);
//                         What do these booleans mean? ↑

The Solution: Builder Pattern

The Builder Pattern addresses these issues by:

  1. Encapsulating the construction logic in a separate Builder class

  2. Providing a fluent interface for setting object properties

  3. Allowing step-by-step construction of complex objects

  4. Supporting immutability by constructing the object only when complete

Structure

The Builder Pattern typically consists of four main components:

  • Product: The complex object being built. This is the final object that the client wants to create. It often has many fields, some required and some optional.

  • Builder: An interface or abstract class that defines all the building steps. It declares methods for constructing different parts of the Product. In many implementations (especially in Java), this is implemented as a static nested class within the Product.

  • Concrete Builder: Implements the Builder interface to construct and assemble parts of the Product. It keeps track of the representation it creates and provides a method to retrieve the final Product.

  • Director (optional): Orchestrates the building process using the Builder interface. It knows the sequence of building steps needed to create specific configurations of the Product. The Director is optional and often omitted in simpler implementations.

  • Client: Uses the Builder to create the Product. The client initiates the building process and retrieves the final Product.

Implementation Example

Basic Builder Pattern in Java

public class Computer {
    private final String CPU;
    private final String RAM;
    private final String storage;
    private final String GPU;
    private final boolean hasWiFi;
    private final boolean hasBluetooth;
    
    private Computer(Builder builder) {
        this.CPU = builder.CPU;
        this.RAM = builder.RAM;
        this.storage = builder.storage;
        this.GPU = builder.GPU;
        this.hasWiFi = builder.hasWiFi;
        this.hasBluetooth = builder.hasBluetooth;
    }
    
    public static class Builder {
        private final String CPU;
        private final String RAM;
        
        private String storage = "256GB SSD";
        private String GPU = "Integrated";
        private boolean hasWiFi = false;
        private boolean hasBluetooth = false;
        
        public Builder(String CPU, String RAM) {
            this.CPU = CPU;
            this.RAM = RAM;
        }
        
        public Builder storage(String storage) {
            this.storage = storage;
            return this;
        }
        
        public Builder GPU(String GPU) {
            this.GPU = GPU;
            return this;
        }
        
        public Builder withWiFi() {
            this.hasWiFi = true;
            return this;
        }
        
        public Builder withBluetooth() {
            this.hasBluetooth = true;
            return this;
        }
        
        public Computer build() {
            return new Computer(this);
        }
    }
    
    @Override
    public String toString() {
        return "Computer{" +
                "CPU='" + CPU + '\'' +
                ", RAM='" + RAM + '\'' +
                ", storage='" + storage + '\'' +
                ", GPU='" + GPU + '\'' +
                ", hasWiFi=" + hasWiFi +
                ", hasBluetooth=" + hasBluetooth +
                '}';
    }
}

Usage

Computer gamingPC = new Computer.Builder("Intel i9", "32GB")
    .storage("1TB NVMe SSD")
    .GPU("NVIDIA RTX 4090")
    .withWiFi()
    .withBluetooth()
    .build();

Computer officePC = new Computer.Builder("Intel i5", "16GB")
    .withWiFi()
    .build();

How It Works: Step-by-Step Explanation

Let's break down what happens when we create a Computer object using the Builder pattern:

Step 1: Create the Builder

Computer.Builder builder = new Computer.Builder("Intel i9", "32GB");

We instantiate the Builder with required parameters (CPU and RAM). The Builder initializes all fields, setting defaults for optional parameters.

Step 2: Configure Optional Parameters

builder.storage("1TB NVMe SSD")  // Returns the same builder instance
       .GPU("NVIDIA RTX 4090")   // Returns the same builder instance
       .withWiFi()               // Returns the same builder instance
       .withBluetooth();         // Returns the same builder instance

Each method modifies the builder's internal state and returns this, enabling method chaining (also called a fluent interface).

Step 3: Build the Final Object

Computer computer = builder.build();

The build() method creates and returns the immutable Computer object, passing the builder itself to the private constructor.

Advanced Patterns

Builder with Validation

One of the key advantages of the Builder Pattern is the ability to centralize validation logic in the build() method. This ensures that invalid objects can never be created.

public Computer build() {
    if (CPU == null || RAM == null) {
        throw new IllegalStateException("CPU and RAM are required");
    }
    
    if (GPU.equals("NVIDIA RTX 4090") && 
        Integer.parseInt(RAM.replaceAll("[^0-9]", "")) < 16) {
        throw new IllegalStateException("High-end GPU requires at least 16GB RAM");
    }
    
    return new Computer(this);
}

Why validate in build() instead of in each setter?

  1. Cross-field validation: You can validate relationships between multiple fields (like GPU and RAM compatibility)

  2. Single point of failure: All validation happens in one place, making it easier to maintain

  3. Flexibility during construction: Users can set fields in any order without triggering premature validation

  4. Clear error reporting: Validation errors occur at the final step, making it clear that the configuration is invalid

Director Pattern

The Director is an optional component that encapsulates the construction logic for common configurations. It's useful when you have standard "recipes" for building objects.

public class ComputerDirector {
    public Computer buildGamingComputer(Computer.Builder builder) {
        return builder
            .storage("1TB NVMe SSD")
            .GPU("NVIDIA RTX 4090")
            .withWiFi()
            .withBluetooth()
            .build();
    }
    
    public Computer buildOfficeComputer(Computer.Builder builder) {
        return builder
            .storage("512GB SSD")
            .withWiFi()
            .build();
    }
    
    public Computer buildServerComputer(Computer.Builder builder) {
        return builder
            .storage("2TB SSD")
            .GPU("None")
            .build();
    }
}

Usage with Director:

ComputerDirector director = new ComputerDirector();

Computer gamingPC = director.buildGamingComputer(
    new Computer.Builder("Intel i9", "32GB")
);

Computer officePC = director.buildOfficeComputer(
    new Computer.Builder("Intel i5", "16GB")
);

Benefits of using a Director:

  • Reusability: Common configurations are defined once and reused

  • Consistency: Ensures standard builds follow the same pattern

  • Separation of concerns: Construction logic is separated from the Builder itself

  • Easier testing: You can test standard configurations independently

Advantages

  1. Improved Readability: Method chaining makes code self-documenting and easy to understand. Compare:

    // Without Builder - unclear what parameters mean
    Computer c = new Computer("i9", "32GB", "1TB", "RTX 4090", true, true);
    
    // With Builder - crystal clear
    Computer c = new Computer.Builder("i9", "32GB")
        .storage("1TB")
        .GPU("RTX 4090")
        .withWiFi()
        .withBluetooth()
        .build();
    
  2. Flexibility: Easy to add new optional parameters without breaking existing code. Adding a new field only requires adding a new builder method.

  3. Immutability: Supports creating immutable objects with many fields. All fields can be final, ensuring thread-safety and preventing accidental modifications.

  4. Encapsulation: Construction logic is separated from business logic. The Product class focuses on its behavior, not on how it's constructed.

  5. Validation: Centralized validation in the build() method ensures invalid objects are never created.

  6. Reusability: Same builder can create different representations. You can create multiple objects with slight variations easily.

  7. Named Parameters: Java doesn't support named parameters, but the Builder pattern simulates this feature through method names.

Disadvantages

  1. Code Verbosity: Requires creating an additional Builder class, which can nearly double the amount of code for the class. For a simple object with 3-4 fields, this overhead may not be justified.

  2. Complexity: Might be overkill for simple objects. If your object only has 2-3 parameters, a simple constructor or factory method is clearer.

  3. Memory Overhead: Creates an additional object (the builder) during construction. While this is typically negligible, it can matter in performance-critical applications creating millions of objects.

  4. Learning Curve: Developers unfamiliar with the pattern need time to understand the fluent interface and method chaining approach.

  5. Maintenance: Changes to the Product class often require corresponding changes to the Builder class, increasing maintenance burden.

When to Use

Use the Builder Pattern when:

  • Your object has many optional parameters (more than 4-5)

  • You want to create immutable objects

  • Object construction involves complex logic or validation

  • You need different representations of the same object

  • You want to improve code readability and maintainability

When NOT to Use

Avoid the Builder Pattern when:

  • Your object has few parameters (use constructors or factory methods)

  • Object construction is simple and straightforward

  • You need mutable objects that change frequently

  • The added complexity doesn't justify the benefits

Real-World Examples

The Builder Pattern is widely used in Java libraries and frameworks. Here are some common examples you'll encounter:

1. StringBuilder in Java

The StringBuilder class is one of the most commonly used builders in Java. It builds strings efficiently through method chaining.

String result = new StringBuilder()
    .append("Hello")
    .append(" ")
    .append("World")
    .append("!")
    .toString();

// More complex example
String html = new StringBuilder()
    .append("<html>")
    .append("<body>")
    .append("<h1>").append("Welcome").append("</h1>")
    .append("<p>").append("This is a paragraph").append("</p>")
    .append("</body>")
    .append("</html>")
    .toString();

Why it uses Builder Pattern:

  • String concatenation with + creates many intermediate String objects (strings are immutable)

  • StringBuilder provides a mutable buffer for efficient string construction

  • Method chaining makes it easy to build complex strings

2. Java HTTP Client (Java 11+)

The modern Java HTTP client uses the Builder Pattern extensively for creating HTTP requests.

import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
import java.time.Duration;

// Building an HTTP Client
HttpClient client = HttpClient.newBuilder()
    .version(HttpClient.Version.HTTP_2)
    .connectTimeout(Duration.ofSeconds(20))
    .followRedirects(HttpClient.Redirect.NORMAL)
    .build();

// Building an HTTP Request
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.example.com/users"))
    .header("Content-Type", "application/json")
    .header("Authorization", "Bearer " + token)
    .POST(HttpRequest.BodyPublishers.ofString(jsonData))
    .timeout(Duration.ofSeconds(10))
    .build();

// Send the request
HttpResponse<String> response = client.send(request, 
    HttpResponse.BodyHandlers.ofString());

Why it uses Builder Pattern:

  • HTTP requests have many optional configurations (headers, timeout, method, body, etc.)

  • Different requests need different combinations of these options

  • The builder makes it clear what each configuration does

3. Android AlertDialog Builder

Android's AlertDialog uses the Builder Pattern to create customizable dialogs.

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;

public void showConfirmationDialog(Context context) {
    AlertDialog dialog = new AlertDialog.Builder(context)
        .setTitle("Confirm Action")
        .setMessage("Are you sure you want to delete this item?")
        .setIcon(R.drawable.ic_warning)
        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Handle confirmation
                deleteItem();
            }
        })
        .setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        })
        .setNeutralButton("Cancel", null)
        .setCancelable(false)
        .create();
    
    dialog.show();
}

Why it uses Builder Pattern:

  • Dialogs can have many optional components (title, message, buttons, icons, etc.)

  • Different dialogs need different combinations of these components

  • The builder provides a clean API for dialog construction

4. Lombok's @Builder Annotation

Project Lombok can automatically generate builder code for you, reducing boilerplate.

import lombok.Builder;
import lombok.Getter;

@Getter
@Builder
public class User {
    private final String username;
    private final String email;
    private final String firstName;
    private final String lastName;
    private final int age;
    private final String phoneNumber;
    private final String address;
}

// Lombok generates the Builder class automatically
// Usage:
User user = User.builder()
    .username("john_doe")
    .email("john@example.com")
    .firstName("John")
    .lastName("Doe")
    .age(30)
    .phoneNumber("555-1234")
    .address("123 Main St")
    .build();

Benefits of Lombok's @Builder:

  • Eliminates boilerplate code

  • Automatically generates the builder class

  • Supports default values with @Builder.Default

  • Reduces maintenance burden

5. Stream API Collectors

Java's Stream API uses builders internally for collecting stream elements.

import java.util.List;
import java.util.stream.Collectors;

List<String> names = users.stream()
    .filter(user -> user.getAge() > 18)
    .map(User::getName)
    .collect(Collectors.toList());

// Custom collector with builder-like pattern
String result = users.stream()
    .map(User::getName)
    .collect(Collectors.joining(", ", "[", "]"));
// Result: "[Alice, Bob, Charlie]"

6. Calendar Builder (Java 8+ Date/Time API)

The modern Java Date/Time API uses builders for creating date/time objects.

import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.ZoneId;

LocalDateTime dateTime = LocalDateTime.now()
    .withYear(2024)
    .withMonth(12)
    .withDayOfMonth(25)
    .withHour(10)
    .withMinute(30)
    .withSecond(0);

ZonedDateTime zonedDateTime = ZonedDateTime.now()
    .withZoneSameInstant(ZoneId.of("America/New_York"))
    .withHour(9)
    .withMinute(0);

Best Practices

  1. Make the Product immutable: Use final fields and no setters

  2. Use method chaining: Return this from builder methods for fluent API

  3. Validate in build(): Perform all validation when constructing the final object

  4. Required vs Optional: Use constructor parameters for required fields, builder methods for optional ones

  5. Consider static factory: Provide a static method on the Product class to get a new Builder

  6. Document clearly: Make it obvious which parameters are required and which are optional

Conclusion

The Builder Pattern is a powerful tool in a developer's arsenal for managing complex object construction. While it adds some verbosity to your codebase, the benefits in terms of readability, maintainability, and flexibility often outweigh the costs. By separating construction logic from representation, the Builder Pattern enables you to create clean, self-documenting code that's easy to understand and modify.

Whether you're building configuration objects, domain models, or API requests, the Builder Pattern provides an elegant solution to the challenge of constructing complex objects with many optional parameters. Master this pattern, and you'll find yourself writing more maintainable and expressive code.

Further Reading

  • "Effective Java" by Joshua Bloch (Item 2: Consider a builder when faced with many constructor parameters)

  • "Design Patterns: Elements of Reusable Object-Oriented Software" by Gang of Four

  • "Head First Design Patterns" by Freeman & Freeman

No comments yet. Be the first to comment.