Immuable Data
Immutable data structures:
- Have one state and never change
- Are simpler to construct, debug, test, and reason about
- Are side-effect free
- Improve performance and are more scalable because they are easier to cache
- Are safer in that they prevent null pointer references
- Are thread safe
- Are always in a stable state
Since immutable data structures are never changed, that means that failures never occur during a data modification operation. When an immutable data structure is initialized it will either fail or succeed, returning a valid data structure that never changes.
In order to make changes to an immutable data structure, we must create a new tree. Suppose we want to update the value of g in the existing tree data structure (previous root). First, we would create the g' node and build the new tree by traversing the nodes connected to g and copying only those values necessary to rebuild the tree. References to other nodes can be created without creating new nodes (these are the nodes in white). With the new root in place, new leaf nodes are added to the new tree structure.
Once the new root has been created the previous/old root can be preserved or it can be marked for deletion.
This may seem like a lot of work, but one of the greatest benefits is that we no longer need to worry about our data unexpectedly changing. For example, what if one Goroutine is looping through our data structure while another one is removing elements from it? We no longer need to concern ourselves with dealing with race conditions and verifying that our preconditions are still valid. When we use immutable data structures, our code becomes more robust and easier to reason about.
Can you think of any solutions today that make use of immutable data structures?
Ever wondered how git works?
Interested in full stack development? How does ReactJS update its models?
In the game of soccer, we may loose to a team because they have a player with specific skills. When we face the team again we may forget the past, but that does not change history; It is not possible to change the past. When the past is not preserved, we cannot learn from it and history will repeat itself. Mutability hides changes.