liveBook · Manning

Immutable collection

As explained in Grokking Simplicity

Data or state whose represented values cannot be modified after creation.

Immutability means representing data so its values are not modified after creation. Instead of changing existing data, code creates and returns a changed version. This separates stable data from actions that interact with the outside world, making calculations easier to test and reuse. section 2.7 section 6.20

Apply immutability through a small set of practical disciplines:

  • Use copy-on-write: make a shallow copy, modify the copy, and return it instead of changing the original. section 4.10 section 6.20
  • Use structural sharing when a shallow copy can reuse references to unchanged nested values. section 6.13
  • Use defensive copying when interacting with untrusted code; it protects immutability more powerfully but copies more data. section 7.12
  • Keep mutable state safer by storing immutable values and updating them through calculations that return valid replacements. section 18.9

Replacing a mutable cart update

A mutating implementation calls `cart.push(...)`. An immutable version copies the array with `cart.slice()`, pushes the new item into that copy, and returns it. The caller assigns the returned cart, turning the update into an explicit result rather than an implicit output. section 4.10 section 5.8

function add_item(cart, name, price) {
    var new_cart = cart.slice(); #1
    new_cart.push({ #2 
        name: name,
        price: price
    });    return new_cart; #3
}

Inspect the JavaScript copy-on-write implementation that creates a new cart, adds an item, and returns the new value. section 5.8

How Grokking Simplicity covers it

How deep it goes
Implements copy-on-write for JavaScript arrays and objects, extends it to nested data and untrusted code, and addresses performance tradeoffs.
Examples
Demonstrates pizza-business data, shopping carts, JavaScript array copying, nested structures, and ValueCells.
What you can do after
Build it from scratch with copy-on-write array and object operations, or apply defensive copying when code cannot be trusted.
How it connects
Connects data with calculations, actions, copy-on-write, defensive copying, structural sharing, mutable state, and concurrency.

Also explained in

Compare how 24 books explain immutable collection →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Simplicity. The section links point to the parts of the book it draws on.