Pattern 15Chain of Operations

Intent

To chain a sequence of computations together—this allows us to work cleanly with immutable data without storing lots of temporary results.

Overview

Sending some bit of data through a set of operations is a useful technique. This is especially true when working with immutable data. Since we can’t mutate a data structure, we need to send an immutable one through a series of transformations if we want to make more than a single change.

Another reason we chain operations is because it leads to succinct code. For instance, the builder we saw in Pattern 4, Replacing Builder for Immutable Object, chains setting operations to keep our code lean, as the following snippet shows:

JavaExamples/src/main/java/com/mblinn/oo/javabean/PersonHarness.java ...

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.