Pattern 4Replacing Builder for Immutable Object

Intent

To create an immutable object using a friendly syntax for setting attributes—because we can’t modify them, we also need a simple way to create new objects based off existing ones, setting some attributes to new values as we do so.

Overview

In this section, we’ll cover Fluent Builder, which produces immutable objects. This is a common pattern; Java’s standard library uses it with its StringBuilder and StringBuffer. Many other common libraries use it as well, such as Google’s protocol buffers framework.

Using immutable objects are a good practice that’s often ignored in Java, where the most common way of carrying data around is in a class with a bunch of getters and setters. This forces ...

Get Functional Programming Patterns in Scala and Clojure now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.