Programming Search⌘K

Techniquecore

Split loop

Split a loop that computes two things into two loops that compute one each, so that each can be understood, extracted and changed on its own; measure before you worry about the cost.

Family
refactoring
Intent
Make each loop do one job.

Purpose

A loop that does two things at once is common, because one pass over the data feels cheaper. The cost is in reading and changing it: to change one of the two computations, you must understand both, and you cannot extract one into a function without the other.

Split loop copies the loop and keeps one computation in each copy. The catalogue card splits a loop over people that sums ages and salaries into one loop for the salaries and one for the ages.1 After the split, each loop can become a function, and often a pipeline: see Replace Loop with Pipeline.

The obvious worry is speed: two passes in place of one. The book's answer is to keep refactoring and optimizing apart. A loop is rarely the bottleneck; if a profile shows that it is, the loops can be joined again, and the clearer code makes other optimizations easier to find.2

Steps

  1. Copy the loop.2
  2. Find the side effects that are now done twice, and remove each from the copy where it does not belong.
  3. Test.
  4. Consider Extract Function on each loop, and Slide Statements to bring each loop's variables next to it.

Example

One loop over orders sums the revenue and finds the largest order. After the split, each computation is a loop of its own, and then a function.

import assert from "node:assert/strict";

const orders = [{ id: 1, cents: 1200 }, { id: 2, cents: 5400 }, { id: 3, cents: 800 }];

// Before: one loop, two jobs.
function summaryBefore(orders) {
  let revenue = 0;
  let largest = null;
  for (const o of orders) {
    revenue += o.cents;
    if (largest === null || o.cents > largest.cents) largest = o;
  }
  return { revenue, largestId: largest?.id };
}

// After: one loop for each job, each extracted.
function revenueOf(orders) {
  let revenue = 0;
  for (const o of orders) revenue += o.cents;
  return revenue;
}
function largestOf(orders) {
  let largest = null;
  for (const o of orders) if (largest === null || o.cents > largest.cents) largest = o;
  return largest;
}
const summary = (orders) => ({ revenue: revenueOf(orders), largestId: largestOf(orders)?.id });

assert.deepEqual(summary(orders), summaryBefore(orders));
assert.deepEqual(summary([]), summaryBefore([]));
assert.deepEqual(summary(orders), { revenue: 7400, largestId: 2 });
console.log("split loop: tests pass");
Output
split loop: tests pass

Each function now has one job and one name. The next step can be Replace Loop with Pipeline: revenueOf becomes a reduce.

Language What the example shows
JavaScript a loop with two jobs split into two functions, as above
Python the same split, where each loop then becomes a call to a built-in, sum and max
Go the same split into two functions, with a test on an empty slice
PythonGitHub
orders = [(1, 1200), (2, 5400), (3, 800)]


def summary_before(orders):
    revenue, largest = 0, None
    for oid, cents in orders:
        revenue += cents
        if largest is None or cents > largest[1]:
            largest = (oid, cents)
    return revenue, largest[0] if largest else None


# After the split, each loop has one job, and each job is a built-in.
def revenue_of(orders):
    return sum(cents for _, cents in orders)


def largest_id(orders):
    top = max(orders, key=lambda o: o[1], default=None)
    return top[0] if top else None


for case in (orders, []):
    assert (revenue_of(case), largest_id(case)) == summary_before(case)
print("split loop: tests pass")
Output
split loop: tests pass
package main

import "fmt"

type Order struct{ ID, Cents int }

func revenueOf(orders []Order) int {
	total := 0
	for _, o := range orders {
		total += o.Cents
	}
	return total
}

// largestOf returns the ID of the largest order, or 0 if there are none.
func largestOf(orders []Order) int {
	id, most := 0, -1
	for _, o := range orders {
		if o.Cents > most {
			id, most = o.ID, o.Cents
		}
	}
	return id
}

func main() {
	orders := []Order{{1, 1200}, {2, 5400}, {3, 800}}
	if revenueOf(orders) != 7400 || largestOf(orders) != 2 {
		panic("split loop")
	}
	if revenueOf(nil) != 0 || largestOf(nil) != 0 {
		panic("empty")
	}
	fmt.Println("split loop: tests pass")
}
Output
split loop: tests pass

When to use

  • A loop does two things. Split it before you change either one.
  • Before Extract Function. A loop with two jobs cannot be extracted as one function with one name.
  • Before Replace Loop with Pipeline. Each loop with one job maps to one pipeline. See Loops.

Pitfalls

Performance. Two passes do more work than one. In most code, the difference does not matter; when it does, measure it with a profiler before you join the loops again. See CPU profiling.2

Single-pass sources. A loop over a stream, an iterator or a network response can only be read once. Split it only after you collect the items, or keep one loop and extract the body of each job.

Duplicate side effects. If the loop body writes to a file, logs or changes shared state, the copy does it twice. Step 2 removes the duplicates; check them with a test.

Tools that do it

This refactoring is a sequence of steps, not one action of a tool. After the split, see Extract Function for the tools that extract each loop.

References

  1. Martin Fowler, Catalog of Refactorings, Split Loop, the entry
  2. Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 8, Moving Features, Split Loop, motivation and mechanics; Chapter 2, Principles in Refactoring, Refactoring and Performance

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)
WritingW3 standard
  • at least three sources