Builder pattern for object construction

David Kumar Jan 2026
2 tabs
package com.example.demo.model;

import lombok.Builder;
import lombok.Data;
import java.time.LocalDateTime;

@Data
@Builder
public class LombokUser {
    private Long id;
    private String name;
    private String email;
    private String phone;
    private String address;

    @Builder.Default
    private LocalDateTime createdAt = LocalDateTime.now();

    @Builder.Default
    private boolean active = true;
}

// Usage with Lombok:
// LombokUser user = LombokUser.builder()
//     .name("John Doe")
//     .email("john@example.com")
//     .build();
2 files · java Explain with highlit

The Builder pattern creates complex objects step-by-step, improving readability and flexibility. I implement builders with static inner classes—fluent methods return the builder for chaining. Required fields use constructor parameters, optional fields use builder methods. The build() method validates and constructs the final object. Lombok's @Builder annotation generates builders automatically. Builders prevent telescoping constructors and make object creation self-documenting. They're ideal for objects with many parameters, especially when some are optional. Immutable objects benefit from builders since all fields are set before construction. The pattern enhances code clarity—User.builder().name("John").email("john@example.com").build() reads like natural language. Spring Boot's auto-configuration heavily uses builders internally.