Skip to content
Veltoryx Technologies
ProLesson 4.4Intermediate7 min readUpdated 31 October 2026

Builder Pattern

Learn how to build complex objects step by step with readable code, avoid long constructors and half-built objects, and see how the JDK and Lombok use builders.

Think about ordering a custom burger. You do not shout twelve answers in one breath. You go step by step: "wheat bun, one patty, extra cheese, no onions, spicy sauce." The cook collects your choices and, only when you say "that's all", assembles the burger. If you ask for something impossible, such as five patties on a small bun, the cook tells you before cooking.

The Builder pattern works the same way for objects. It lets you describe a complex object step by step, with names, and then creates it in one final step, checking that everything makes sense.

01The problem: objects with many options

Let us model a pizza. It has a size, optional extra cheese, optional extra sauce, a list of toppings and more. The first idea is a constructor with all the options:

One long constructor
Pizza pizza = new Pizza("LARGE", true, false, true, false, null, 2, true);

Look at that line and try to answer: which true is the extra cheese? What does the 2 mean? What is null for? Nobody can tell without opening the class. Mix up two true values and the program still compiles, but you now have the wrong pizza.

Programmers sometimes try to "help" by writing many constructors with fewer and fewer parameters. This is called the telescoping constructor problem: the number of constructors grows with every new option, and callers still must pass useless null and false values just to reach the one option they need.

Another idea is to create an empty object and set the options one by one:

The setter style: half-built objects
Pizza pizza = new Pizza();
pizza.setSize("LARGE");
pizza.setExtraCheese(true);
// ... somewhere else in the code someone forgets to set the toppings
bake(pizza);   // the pizza is used before it is complete

This is more readable, but it has a worse problem: the object exists in a half-built state. Any code that gets hold of it in the middle sees an incomplete, possibly invalid pizza. The object also stays mutable forever, so anyone can change it later, even from another thread. Rules between fields (for example "at most five toppings") cannot be checked, because you never know when the object is finished.

Loading the rest of the lesson…