Sitemap
Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Design Pattern — Builder

7 min readJan 3, 2021

--

In detail discussion on Builder Design Pattern

The Builder Design pattern is one of the Gang Of Four(GoF) creational design patterns. If you’ve ever struggled with a constructor that takes six or seven parameters — and you can’t remember which one is which — Builder is the pattern that fixes that.

What is the Builder Design Pattern?

This design pattern is used far more often than people realize — StringBuilder in Java is a Builder you’ve likely used hundreds of times. It is ideal for creating objects which require several parameters, where the object, once created, is supposed to be immutable.

Builder deals effectively with a large number of parameters by letting you set them one at a time, in any order, with clear method names — rather than passing them all into a constructor where the order and meaning of each argument is unclear.

Examples

Instances where you may have seen or used Builder Design pattern —

  • Java — StringBuilder API in Java is the most common example of this. Another example is the DocumentBuilder.
StringBuilder, an example for Builder Design pattern

As you can see from above, you are trying to build a complex string. Once the string is built, it is immutable. Alternatively, you could have done this using string concatenation, but imagine a big string with different types of data to concatenate.

Problems addressed by the Builder Design pattern

There can be multiple constructors for a class. It can be confusing in determining which constructor to use and in what scenario. Builder addresses this by:

  • Creation of a complex object is simplified — With the help of a builder class, the process of creating a complex object becomes straightforward and readable.
  • Separation of responsibility — Object creation responsibility is moved to a dedicated Builder class, allowing the original class to focus on its state and behavior.
  • Exposed setters eliminated — Using a Builder pattern we do not have to expose setters. The objects created are immutable — no unintended modifications after creation.
  • Telescopic constructor replaced — We can get rid of the constructor mesh. No need to chain one constructor inside another to handle different combinations of parameters.
  • No need to pick the right constructor — The Builder handles which constructor to call. The consumer just sets the properties they need and calls build().

We will see these issues in detail below.

Exposed setters

Imagine you have to create an object of the class Person. Person class would look something like this —

From the above code, you can see it has a default constructor. It has four members. Every person should at least have a name. Having a college degree, house or car is optional. Any person can have any combination of the data. Just by looking at the class, it is not clear what are the must-have and can-have properties. So there is no clear definition of a contract.

Also, this class has setters for each of the member variables and we can change the properties after the class has been created.

So the issue here is that it doesn’t have any contract for the outside world. And it exposes all the setters, which is unnecessary. Also, the object once created is mutable.

“Add a nice constructor”, you might ask. Sure, let’s look at that approach.

Telescopic constructor

Now, we are going to add some constructor to this person class and get rid of all the setter.

If you look closely, you would see a constructor with more number of parameter uses another constructor which has less number of parameters. e.g. Constructor with four parameters — name, degree, car & house uses a constructor with three parameters — name, degree & car. This approach is called a telescopic constructor.

Get Vivek Mittal’s stories in your inbox

Join Medium for free to get updates from this writer.

This is great. However, there are some problems here. What if this person has a name and owns a house. She doesn’t have any college degree or a car. We can pass null to the constructor with four parameters, but that is not elegant. For a problem like this, the previous approach sounds a little better. Let’s apply the Builder pattern to this problem.

UML for Builder

Press enter or click to view image in full size
UML diagram for Builder Design Pattern — PersonBuilder constructs an immutable Person object through chained setters

The PersonBuilder has the same properties as Person. The constructor
requires only the mandatory field — name. Optional fields are set via
chained setters that return the builder itself. The build() method
creates an immutable Person object.

Builder Design pattern in action

Press enter or click to view image in full size
Photo by Jakob Owens on Unsplash

Now we are trying to apply the Builder pattern to the problem of creating a Person class object. See how elegant the solution becomes when we apply the Builder Design pattern to it.

This is the Person class with Builder Design pattern. You can see from above, PersonBuilder is an inner class. Some of the important points are highlighted below —

  • Immutability — All properties of the Person class are final and cannot be modified once created. The only constructor is private and takes the builder as a parameter.
  • Inner class — Mostly the Builder classes are inner static classes. This is however not a requirement for the Builder design pattern.
  • Duplicate properties — The inner builder class has the same properties as the outer class. These duplicate properties are used to create the builder object properly.
  • Public setters — All the properties in the inner class has a public setter. These setters are used to populate data in the builder object. Refer the code snippet below on how this is used. The properties of the builder class can be modified any number of times as required before the final mutable object is created.
  • Chaining — All the setters in the inner class return ‘this’, i.e. the object of the builder class. This is important to provide the chaining of the methods. Again refer to how we have chained setting car & degree.
  • Contract — Using the inner class, we have made a contract that each Person should at least have a name. You cannot create a Person without a name. Also, all the Person objects will be created using a builder object.
  • Flexibility — In the example code below on how to use the builder class we created, notice we haven’t populated the house property of the builder. This is because we don’t have to. A person may or may not have a house and if the person doesn’t we don’t have to call the setHouse() method with null. We can just skip a call and it would work just fine.

Following is the example code to use it —

See how elegant has it become creating the person object.

P.S. Car, college degree or type of house you own, doesn’t define a person. This is just to demonstrate how to use the Builder Design pattern. 😌

When to use the Builder Design pattern?

  • Complex object creation — When creating an object is not as trivial as new Person(). Multiple fields, optional fields, or specific combinations of fields make a simple constructor insufficient.
  • Many parameters — When a constructor requires more than 3-4 parameters, readability suffers. Builder gives each parameter a named method, making the intent clear.
  • Immutable objects — When the object, once created, should not be modified. Builder lets you set everything during construction and then lock it down.
  • Readable API for consumers — When other developers (or your future self) need to understand at a glance what's being built. new Person("Vivek", null, null, "House") tells you nothing. Person.builder().name("Vivek").house("House").build() tells you everything.

Limitations

There are no significant issues with this Design pattern. However, some of the issues are listed below —

  • Requires upfront design — Builder works best when considered in the design phase. Retrofitting it onto an existing class during refactoring is more effort than starting with it.
  • Increased code — The inner Builder class duplicates all the properties of the outer class. For simple objects with 2–3 fields, this overhead isn’t worth it.
  • Only suits immutable objects — Builder is designed for creating immutable objects. If your objects need to be mutable after creation, Builder adds unnecessary complexity.
  • Boilerplate — The pattern requires writing setters, a build() method, and duplicate properties. Libraries like Lombok (@Builder) can generate this, but vanilla implementations are verbose.

Summary

  • Separates object creation from the rest of the code
  • Handles complex objects with many parameters cleanly
  • Produces immutable objects — no exposed setters
  • Replaces telescopic constructors with a readable, chainable API
  • Adds code overhead — the builder class duplicates properties
  • Best adopted in the design phase rather than retrofitted later

Builder is one of the most practical creational patterns. It solves a real, everyday problem — constructing complex objects without losing readability or immutability. The progressive approach we saw — from exposed setters, to telescopic constructors, to Builder — shows exactly why this pattern exists. Each step solves one problem but introduces another, until Builder resolves them all.

If your class has more than three or four parameters, or if the object should be immutable after creation, reach for Builder. It’s a small upfront investment that pays off every time someone reads your code and immediately understands what’s being built.

Written & edited by — Vivek Mittal

https://www.linkedin.com/in/vivekmittal06/

Additional reading

--

--

Written by Vivek Mittal

I love tech and often write about what I learn

Published in Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development