Member-only story

Effective Java! The Builder Pattern!

Kyle Carter
4 min readDec 24, 2020

It’s time for episode two of the effective Java review series. The topic of today is the builder pattern. Just like our previous chapter this is another creational pattern.

When we are faced with a class that has a significant number of optional members what is the best way to create these objects? The three methods detailed in Effective Java are telescoping constructors, the JavaBean pattern, and the builder pattern. Let’s walk through these methods and see where the first two fall short and how the builder pattern can shine.

Option 1: Telescoping Constructors
First up is my least favorite option if you have more than one or two optional parameters. The telescoping constructor. A telescoping constructor is basically a group of constructors that basically covers all the available permutations of parameters that could be used to create an object. Let’s look at an example:

public Burger(String bunType)
public Burger(String bunType, List<String> condiments)
public Burger(String bunType, List<String> condiments, String meat)
public Burger(String bunType, List<String> condiments, String meat, String temperature)

Looking at these constructors you can see where it gets it’s name. Telescoping constructors suffer from a problem talked about in my previous post in this series. With multiple parameters of the same type it can be easy to get lost in what each parameter is what. (Although hat tip to my favorite IDE Intellij for giving little tool tips giving…

--

--

Kyle Carter
Kyle Carter

Written by Kyle Carter

I'm a software architect that has a passion for software design and sharing with those around me.

No responses yet