This an oxymoron: immutable state!
By essence, an object’s state keeps mutating, according to the side effects experienced by the object. On the other side, we have the immutable value object. You just can not change it, you can only get a different instance that represents another value. Mutable objects are the bane of concurrent programming, where value objects thrive. But immutability comes at a great cost: the loss of identity.
Whatever you try to do, the number 2 cannot change to 8. The physical world is the world of mutability, stuff keeps changing: objects move, living things grow, stars explode, even atoms have a life expectancy. But, if change happens slowly we can get a decent sense of immutability: a pictures, even if it had a life of its own, its content is immutable, people on the snapshot will not move!
Same for a book: the paper may go yellow, the story will remain the same, which is important if we plan to read it: how could anyone read a book if its content kept changing. Now leave the physical world and go back to the virtual one: the situation is similar, stuff keep changing but we need them to be stable (and consistent) as long as we need them to execute some tasks. The usual approach to that was mutual access exclusion: if you are the one and only one to access the entity you need, you have full control on what may happen to it. But, as I pointed out numerous times, this approach just fails in the long run, if not in the short. Just to stress one pitfall out, one can assume that reads of the entity will outnumber writes, which leads to useless contention: no protection is required when there is no active writer. The usual solution relies on so-called read-write locks, which allow many readers but just a single writer. Better, yes, but it has its own pitfalls:
- it can lead to writer starvation (so many readers that you cannot write)
- it triggers tricky deadlocks due to lock promotion (when a reader needs to write)
- most implementations have disappointing performances
How to efficiently address read vs. write contentions? What if the readers and writers did not compete? The only remaining contentions would be among writers, as readers happily share! Then use an immutable state:
- readers can get a valid state whenever they need
- writers just generate to state instances, without altering the preexisting ones
One thought on “Pattern: Immutable State”
I don’t know why, but I really like this name 😉