Member-only story

Immutable, the Builder Pattern vs Messy POJOs (or POCOs)

⚡️Hudson Ⓜ️endes
3 min readNov 15, 2018

--

Learn how these design patterns made famous by the GoF (Gang of Four) can help you achieve more reliable and cleaner code.

One of the 3 line of codes has a _bad bad_ bug. Can you tell?

1. new Phrase(“how are you?”, “en-US”);2. new Phrase()
.setText(“how are you?”)
.setLocale(“en-US”);
3. Phrase
.builder()
.withLocale(“en-US”)
.withText(“how are you?”)
.build()

Neither can the compiler.

The answer is (1), see why below:

public class Phrase {
private final String locale;
private final String text;
public Phrase(final String locale, final String text) {
this.locale = locale;
this.text = text;
}
// (…)
}

What is the Problem?

The parameters are reversed, but neither you or the compiler know.

This would build. And maybe even pass the tests, since whoever was unit-testing the Phrase object remembered pretty well how it was designed.

But depending on how instance of the model Phrase goes in your code, can cause some pretty weird problems, as well as clumsy debugging session.

--

--

⚡️Hudson Ⓜ️endes
⚡️Hudson Ⓜ️endes

Written by ⚡️Hudson Ⓜ️endes

⚡️Staff AI/ML Engineer & Senior Engineering Manager, #NLP, opinions are my own. https://linkedin.com/in/hudsonmendes

Responses (2)