The right time to use the builder pattern in Java


News: The right time to use the builder pattern in Java

  1. Builder design pattern is a cool way to create object in Java. It allows you to build object  by adding property one by one in a readable fashion. Since after 4 or 5 arguments constructor started getting ugly, builder pattern solves that problem elegantly. It also solves problem of telescoping constructor.

    Pros and Cons of Builder design pattern:


    1) Code is more maintainable if number of fields required to create object is more than 4 or 5.

    2) Object creational code less error-prone as user will know what they are passing because of explicit method call.

    3) Builde patter increse robustness, as only fully constructed object will be available to client.


    1) Builder pattern is verbose and requires code duplication as Builder needs to copy all fields from Original or Item class.

    See this blog post for sample code and detailed explaination on buildern pattern in Java.

  2. Lombok project offers builder pattern code with just an annotation:


    So you can put it everywhere you want with juste a minimal effort!

  3. IntelliJ has the builder pattern as a refactoring, too.