DEV Community


Discussion on: What Do You Think About Immutable Data?

oscherler profile image
Olivier “Ölbaum” Scherler

Sometimes immutable data makes the code easier to write. I had a piece of code that received a large-ish nested structure (like the page hierarchy of a web site) and needed to walk through it, add properties to each item (a unique, incremental ID, and a sequential number that resets on each level), while building some other structures about it (e.g. an ID map).

It was initially done with foreach loops with the loop variable passed as reference, to transform the structure in-place, which seemed to be easier. It turned out to be a nightmare to read, modify and debug.

In the end, inspired by the way this kind of thing is typically done in Erlang, I rewrote everything recursively with pure functions that take as arguments the data left to process and the part of the result that was already processed, and return a new copy of the structure instead of modifying it in place (of course, it means you are often returning several values in an array, for the result, the rest of the yet-unprocessed data, and some carries like the last used ID or current sequence value—you typically use a tuple in Erlang).

To my surprise, it turned out to be much, much easier to write, read, and debug than the initial code, even though it seemed more complicated when you thought about it before starting (I was expecting a bit easier, but not by that amount).