Matt Field: Don't go changing

Orde Saunders' avatarPublished: by Orde Saunders

Matt Field (@mattfieldy) was talking about immutable state at Scotland.js, these are my notes from his talk.

2006 - Out of the Tar Pit.  Moseley and Marks.  Complexity is the most common cause of problems in software.  Handling of state is the main cause of complexity.  In JS we mutate things left right and centre which doesn't scale.  This is incidental complexity, we shouldn't be dealing with this.

Modern software dev is brute force, just throw person hours at it.

OO is a way of modeling programmes in the same way we see the world.  Objects have mutable state - this is seen as advantageous (a cup of coffee is still a cup of coffee weather it is hot or cold.)

No man can cross the same river twice, the water will flow and change. 

  1. Values - does not and cannot change.  42 + 1 = 43  42 has not changed.
  2. Identity - named entities, the head marker in Git is an example - points to a new immutable value.
  3. State - value of an identity at a moment in time.  Snapshot and immutable.
  4. Change - movement from one state to another

Mutable state doesn't make sense.

Data structures are a series of states that we attach an identity to.  State can be captured with certainty, stored and re-used later without fear of change.

What can we do?

Make state handling explicit.

Purity

Given the same input we get the same output every time.  Result calculated from the arguments - cannot rely on or change outside  itself.  This makes it a value - you can swap the function call and the result with certainty.

mutability !== dynamism

Persistent data structure

At some point you need to change data.   Update them by creating a copy with modifications - a new state.  We preserve old versions of state.

Singly linked lists that are a pair - data in the head and the rest of the list at the tail.  We only store a reference to the value at the head of the list.

mori library- Clojure data structures exported for JS.

Constantly question weather the complexity you are facing is incidental or essential.