All topics
library
intermediate

Builder Pattern in Java

Construct complex objects step-by-step with a fluent API, and understand where Lombok's @Builder fits.

The Builder pattern separates object construction from representation. Instead of a constructor with 10 parameters, use named setter-like methods that return the builder for chaining.

Builder = ordering a custom pizza. You specify toppings one by one (fluent setters). When done, you submit the order (build()). The pizza arrives fully assembled (immutable object). You can't change it after baking.

Key Concepts

1
Why Builders: - Constructors with many parameters are error-prone (parameter order confusion) - Setters make objects mutable after construction (bad for immutability) - Builders give named parameters + immutability + validation in build()
2
Implementation approaches: 1. Manual inner static class Builder with fluent setters and build() method 2. Lombok @Builder: generates the builder at compile time (zero boilerplate) 3. Records + manual builder: combine records' immutability with builder ergonomics
3
Builder guidelines: - Make the constructor private — force use of the builder - Return this from every setter for fluent chaining - Validate in build() — throw IllegalStateException for missing required fields - Use @Builder.Default in Lombok for default values - Consider toBuilder() for creating modified copies
this
4
The Effective Java Builder (Joshua Bloch's approach) uses a static inner class. Lombok's @Builder automates this exact pattern. For simple classes with few fields, just use a constructor or static factory method.