Take a look at this small, typical code snippet:
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)
This code is “safer from bugs, easier to understand, and more ready for change” (MIT Course on software construction):
- 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.