Skip to content

Split Loop: One Loop Doing Two Jobs Becomes Two Loops

Learn how to split a loop that computes two unrelated results into two loops, so each one can be named, extracted and tested on its own.

7 min readRefactoring

Split Loop is a small refactoring with a big payoff. You take a loop that accumulates two unrelated things in the same pass and duplicate it, so each copy does exactly one job. On its own that looks like a step backwards: more lines, two passes instead of one. The point is what it enables next. A loop that does one thing can be extracted into a function with an honest name, replaced with a pipeline, or moved to the class that owns the data. In interviews, this comes up when you are asked to clean up a reporting or aggregation function, or when a reviewer asks why you would iterate twice. You should be able to explain why the extra pass is almost always fine, and when it is not.

The problem

A situation where the obvious design starts to hurt.

Picture the shift report at Ember Lane Roasters, a small coffee roastery. At the end of each shift, a function walks through the roast batches and does two things at once. It adds up the kilograms of green coffee roasted, and it collects the IDs of batches whose peak drum temperature went over the limit, so the QA lead can taste them before release.

Both jobs live in the same loop body, with comments explaining which line belongs to which job. You cannot extract the weight calculation without dragging the temperature check along, and any change to one job means rereading the other. The loop is the only thing tying them together, and it is an accident of how the code was first written, not a real dependency.

Before and after

The same code, before and after the change.

Before

interface RoastBatch {
  id: string;
  greenKg: number;
  peakTempC: number;
}

function summarizeShift(batches: RoastBatch[], maxTempC: number): string {
  let totalKg = 0;
  const scorched: string[] = [];
  for (const batch of batches) {
    // weight for the roast log
    totalKg += batch.greenKg;
    // batches the QA lead must cup before release
    if (batch.peakTempC > maxTempC) {
      scorched.push(batch.id);
    }
  }
  const flagged = scorched.length > 0 ? scorched.join(", ") : "none";
  return `Roasted ${totalKg.toFixed(1)} kg; over temperature: ${flagged}`;
}

console.log(
  summarizeShift(
    [
      { id: "R-101", greenKg: 12.5, peakTempC: 228 },
      { id: "R-102", greenKg: 15, peakTempC: 236 },
      { id: "R-103", greenKg: 12.5, peakTempC: 231 },
    ],
    232,
  ),
);
// Roasted 40.0 kg; over temperature: R-102

After

interface RoastBatch {
  id: string;
  greenKg: number;
  peakTempC: number;
}

function totalGreenKg(batches: RoastBatch[]): number {
  let total = 0;
  for (const batch of batches) {
    total += batch.greenKg;
  }
  return total;
}

function overTemperatureIds(batches: RoastBatch[], maxTempC: number): string[] {
  const ids: string[] = [];
  for (const batch of batches) {
    if (batch.peakTempC > maxTempC) {
      ids.push(batch.id);
    }
  }
  return ids;
}

function summarizeShift(batches: RoastBatch[], maxTempC: number): string {
  const totalKg = totalGreenKg(batches);
  const scorched = overTemperatureIds(batches, maxTempC);
  const flagged = scorched.length > 0 ? scorched.join(", ") : "none";
  return `Roasted ${totalKg.toFixed(1)} kg; over temperature: ${flagged}`;
}

console.log(
  summarizeShift(
    [
      { id: "R-101", greenKg: 12.5, peakTempC: 228 },
      { id: "R-102", greenKg: 15, peakTempC: 236 },
      { id: "R-103", greenKg: 12.5, peakTempC: 231 },
    ],
    232,
  ),
);
// Roasted 40.0 kg; over temperature: R-102

Why it's worth it

What the change buys you.

The two accumulators in the original loop never read each other. The total weight does not care which batches ran hot, and the list of hot batches does not care how much coffee was roasted. When two computations share nothing but the iteration, keeping them in one loop only couples them visually and makes extraction impossible.

Once split, each loop has one input, one output and one reason to change. That makes Extract Function trivial, and the names totalGreenKg and overTemperatureIds now say what the comments used to say. The top-level function reads like the report it produces.

The cost is a second pass over the list. Both versions are O(n) in time; the split version does roughly twice the iteration work, which for a shift's worth of batches is negligible. If profiling later shows the loop is genuinely hot, you can merge it back, but you should make that decision with numbers, not by default.

  • Each computation can be extracted, named and unit-tested on its own.
  • Comments that labelled parts of the loop body are replaced by function names.
  • Changing the temperature rule no longer risks breaking the weight total, and vice versa.
  • Each single-purpose loop is an easy candidate for Replace Loop with Pipeline.

Careful with

  • Only split when the computations are independent. If the second job reads a value the first job updates during the same iteration, splitting changes behaviour.
  • Iterators and generators that can be consumed only once, such as a database cursor or a Python generator, cannot be walked twice. Materialise them into a list first or keep a single loop.
  • If the loop body has side effects like logging, writing to a file or calling an API, splitting can change their order or count. Keep side effects in exactly one of the loops.
  • Splitting doubles the iteration work while keeping the same O(n) complexity. Measure before merging loops back for speed; in typical code the difference does not matter.

Step by step

Small, safe steps, with the tests passing after each.

  1. Make sure tests pin the output of summarizeShift, including an empty batch list, a batch exactly at the temperature limit and a shift with several flagged batches.

  2. Duplicate the loop so the same body runs twice in a row. Run the tests; the result must be unchanged except that it would double-count, so do the next step immediately.

  3. In the first copy, delete the temperature check; in the second copy, delete the weight accumulation. Run the tests.

  4. Slide each accumulator declaration down so it sits directly above the loop that uses it. Run the tests.

  5. Extract the first loop and its accumulator into totalGreenKg and call it from summarizeShift. Delete the now-redundant comment. Run the tests.

  6. Extract the second loop into overTemperatureIds, passing the temperature limit as a parameter. Delete its comment. Run the tests.

  7. Optionally, replace each extracted loop with a pipeline such as reduce/filter, sum/comprehension or array_sum/array_filter, running the tests after each change.

Smells it removes

Smells this refactoring helps remove.

Common questions

Short answers to the usual doubts.

Isn't iterating twice wasteful?

Both versions are O(n). The split version touches each element twice instead of once, which is a constant factor. For most business code that cost is far below anything a user would notice, and the clarity gain is real. If a profiler shows the loop is a bottleneck, merge it back deliberately and keep a comment explaining why.

Should I stop after splitting or go on to extract functions?

Splitting is usually a preparatory step. Its value shows up when you extract each loop into a named function or turn it into a pipeline. Leaving two side-by-side loops in the same long method is a smaller improvement than finishing the job.

How do I explain this refactoring in an interview?

Say that the loop is doing two independent things, so you split it to give each computation its own scope, then extract each into a well-named function. Mention the trade-off up front: a second pass over the data in exchange for code that is easier to read, test and change, and note that you would only merge loops back if profiling justified it.

How is Split Loop different from Split Phase?

Split Loop separates two independent computations that happen to share one iteration. Split Phase separates sequential stages, where the first stage produces data that the second stage consumes, such as parsing input and then calculating on the parsed result.

Next guide5 of 7 · Techniques: composing functionsSlide Statements: Group Related Code Before You Extract ItRead the next one