The Iterate-and-Mutate Programming Anti-Pattern

Take a look at this small, typical code snippet:

let car_ids = [];
for (let i = 1; i <= 5; i++) {
    const car_id = `car-${i}`;
    if (car_is_empty(car_id)) {
        car_ids.push(car_id);
    }
}
return car_ids;

I call this the iterate-and-mutate pattern. It comes up all the time in code. But every time we see it, we should think about replacing it with a mapping operation, like this: (Ruby syntax)

return (1..5)
         .map{|n| "car-#{n}"}
         .select{|m| car_is_empty(m)}

This is better for lots of reasons:

  • Code that mutates (changes) a variable is harder to reason about, and so easier to get wrong.
  • An explicit for loop is another common source of bugs.
  • The original snippet is longer because it’s doing boring, low-level work. More, boring, code is another source of bugs.
  • Long code with low-level operations like for loops and pushing values onto arrays is not expressive.
  • The shorter, functional version has no variables, no mutation, and no explicit looping. It’s much shorter and easy to understand, once you’ve seen this style.

Here’s a great intro to functional programming in Javascript.