Programming Search⌘K

Techniquecore

Replace loop with pipeline

Also called replace loop with collection pipeline.

Replace a loop that filters, transforms and collects items with a collection pipeline of operations such as filter, map and reduce; each language has its own form.

Family
refactoring
Intent
Show the steps of a computation over a collection as a sequence of named operations.

Purpose

A loop says how to visit each item. What it computes is spread over the body: an if that skips some items, a line that changes each item, a push that collects the result. The reader must put those back together.

A collection pipeline names each step. In Fowler's words, "A collection pipeline lays out a sequence of operations that pass a collection of items between them".1 The catalogue card turns a loop that collects the names of programmers into input.filter(...).map(...).2 The book names the Loops smell and gives this refactoring as its fix.3

The pattern has a different form in each language: array methods in JavaScript, streams in Java, iterator adapters in Rust, and comprehensions or generator expressions in Python. The article notes that comprehensions express the same pipeline in another syntax.1 For Python, the tutorial puts it this way: "List comprehensions provide a concise way to create lists".4

Steps

  1. Make a variable for the collection that the loop walks over.3
  2. Take the first piece of behavior in the loop body, for example the if that skips some items, and express it as a pipeline operation on that variable, here a filter. Test.
  3. Repeat for each piece: a transformation becomes map, a nested collection becomes flatMap, a limit becomes slice or take.
  4. When the loop body is empty, delete the loop. If the loop added to an accumulator, assign the pipeline's result to it.3
  5. Test.

Example

A loop finds the paths of the three slowest failed requests in a log. The pipeline says the same thing as a sequence of steps.

import assert from "node:assert/strict";

const log = [
  { path: "/a", status: 200, ms: 40 }, { path: "/b", status: 503, ms: 900 },
  { path: "/c", status: 500, ms: 120 }, { path: "/d", status: 502, ms: 2500 },
  { path: "/e", status: 500, ms: 300 }, { path: "/f", status: 404, ms: 10 },
];

function slowFailuresLoop(log) {
  const failed = [];
  for (const r of log) {
    if (r.status >= 500) failed.push(r);
  }
  failed.sort((x, y) => y.ms - x.ms);
  const paths = [];
  for (let i = 0; i < failed.length && i < 3; i++) paths.push(failed[i].path);
  return paths;
}

const slowFailures = (log) => log
  .filter((r) => r.status >= 500)
  .toSorted((x, y) => y.ms - x.ms)
  .slice(0, 3)
  .map((r) => r.path);

assert.deepEqual(slowFailures(log), slowFailuresLoop(log));
assert.deepEqual(slowFailures(log), ["/d", "/b", "/e"]);
assert.equal(log[1].path, "/b"); // toSorted leaves the log in its order
console.log("replace loop with pipeline: tests pass");
Output
replace loop with pipeline: tests pass

Each line of the pipeline is one step: keep the failures, order by time, take three, keep the path. toSorted returns a sorted copy; sort would change the log in place.

Language Pipeline form What the example shows
JavaScript array methods filter, toSorted, slice and map on an array, as above
Python comprehensions and built-ins a list comprehension, sorted with a key, and slicing; a generator expression for a lazy form
Java streams stream().filter().sorted().limit().map().toList(), with lazy intermediate operations
Rust iterator adapters iter().filter().map() and collect; the sort is on a collected Vec, since iterators do not sort
PythonGitHub
from itertools import islice

log = [
    ("/a", 200, 40), ("/b", 503, 900), ("/c", 500, 120),
    ("/d", 502, 2500), ("/e", 500, 300), ("/f", 404, 10),
]


def slow_failures_loop(log):
    failed = []
    for r in log:
        if r[1] >= 500:
            failed.append(r)
    failed.sort(key=lambda r: r[2], reverse=True)
    return [failed[i][0] for i in range(min(3, len(failed)))]


def slow_failures(log):
    failed = [r for r in log if r[1] >= 500]            # filter
    ranked = sorted(failed, key=lambda r: r[2], reverse=True)
    return [path for path, _, _ in ranked[:3]]          # take 3, map


# A lazy form: a generator expression and islice read only what they need.
def first_failures(log, n):
    return list(islice((path for path, status, _ in log if status >= 500), n))


assert slow_failures(log) == slow_failures_loop(log) == ["/d", "/b", "/e"]
assert first_failures(log, 2) == ["/b", "/c"]
print("replace loop with pipeline: tests pass")
Output
replace loop with pipeline: tests pass
JavaGitHub
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Main {
    record Request(String path, int status, int ms) {}

    static List<String> slowFailuresLoop(List<Request> log) {
        List<Request> failed = new ArrayList<>();
        for (Request r : log) if (r.status() >= 500) failed.add(r);
        failed.sort(Comparator.comparingInt(Request::ms).reversed());
        List<String> paths = new ArrayList<>();
        for (int i = 0; i < failed.size() && i < 3; i++) paths.add(failed.get(i).path());
        return paths;
    }

    static List<String> slowFailures(List<Request> log) {
        return log.stream()
                .filter(r -> r.status() >= 500)
                .sorted(Comparator.comparingInt(Request::ms).reversed())
                .limit(3)
                .map(Request::path)
                .toList();
    }

    public static void main(String[] args) {
        List<Request> log = List.of(
                new Request("/a", 200, 40), new Request("/b", 503, 900), new Request("/c", 500, 120),
                new Request("/d", 502, 2500), new Request("/e", 500, 300), new Request("/f", 404, 10));
        if (!slowFailures(log).equals(slowFailuresLoop(log))) throw new AssertionError("differ");
        if (!slowFailures(log).equals(List.of("/d", "/b", "/e"))) throw new AssertionError(slowFailures(log));

        // Laziness: with no terminal operation, the filter never runs.
        int[] calls = {0};
        log.stream().filter(r -> { calls[0]++; return true; });
        if (calls[0] != 0) throw new AssertionError("ran early");
        System.out.println("replace loop with pipeline: tests pass");
    }
}
Output
replace loop with pipeline: tests pass
RustGitHub
struct Request {
    path: &'static str,
    status: u16,
    ms: u32,
}

fn slow_failures(log: &[Request]) -> Vec<&'static str> {
    // Iterators have no sort, so collect the failures, sort, then go on.
    let mut failed: Vec<&Request> = log.iter().filter(|r| r.status >= 500).collect();
    failed.sort_by(|a, b| b.ms.cmp(&a.ms));
    failed.iter().take(3).map(|r| r.path).collect()
}

fn main() {
    let log = [
        Request {
            path: "/a",
            status: 200,
            ms: 40,
        },
        Request {
            path: "/b",
            status: 503,
            ms: 900,
        },
        Request {
            path: "/c",
            status: 500,
            ms: 120,
        },
        Request {
            path: "/d",
            status: 502,
            ms: 2500,
        },
        Request {
            path: "/e",
            status: 500,
            ms: 300,
        },
        Request {
            path: "/f",
            status: 404,
            ms: 10,
        },
    ];
    assert_eq!(slow_failures(&log), vec!["/d", "/b", "/e"]);

    // Laziness: an adapter does nothing until something consumes it.
    let mut calls = 0;
    let lazy = log.iter().map(|r| {
        calls += 1;
        r.ms
    });
    drop(lazy);
    assert_eq!(calls, 0);
    println!("replace loop with pipeline: tests pass");
}
Output
replace loop with pipeline: tests pass

When to use

  • The loop filters, maps or collects. Those steps have names in a pipeline.
  • The loop has one job. A loop with two jobs first needs Split Loop.
  • The result is a value. Pipelines fit computations that produce a collection or a value from a collection.

Pitfalls

Laziness. In some languages the steps of a pipeline do not run until a final step asks for the result. In Java, "Intermediate operations are always lazy".5 In Rust, "Iterators (and iterator adapters) are lazy".6 Side effects inside a map then run late, or not at all if nothing reads the result. Keep pipeline steps free of side effects.

Early exit and complex state. A loop that stops at the first match, or that keeps state across items, maps to find, takeWhile or a fold. If no operation fits, the loop can be the clearer form.

One pass or several. A pipeline can make several passes, or build a collection at each step, where the loop made one. In most code this does not matter. If it does, measure, and use the language's lazy form: a stream in Java, an iterator in Rust, a generator expression in Python. See laziness.

Order. A step that sorts or groups needs the whole collection. Put filters before it, so it sorts less.

Tools that do it

This refactoring is a sequence of steps, not one action of a tool. Each step can be checked with the tests.

References

  1. Martin Fowler, Collection Pipeline, 2015, Defining Collection Pipeline; the comparison with comprehensions
  2. Martin Fowler, Catalog of Refactorings, Replace Loop with Pipeline, the entry
  3. Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 8, Moving Features, Replace Loop with Pipeline, motivation and mechanics; Chapter 3, Bad Smells in Code, Loops
  4. The Python Tutorial, Data Structures, 5.1.3 List Comprehensions
  5. Java SE 21 API, package java.util.stream, Stream operations and pipelines; Laziness
  6. The Rust Standard Library, module std::iter, Adapters; Laziness

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/NPJT0B/text.yaml