An old colleague (Jason Langford) first piqued my interest in the “readonly” keyword probably 18months ago. I had read about it in the FDG with regards to exposing arrays from properties and providing setter on Enumerable properties (eg Collections) which is most of the time a silly idea.
I then heard about the benefits of Immutable objects in concurrent programming from Joel Pobar during an excellent presentation on the future of Multi-threaded programming.
And now I as I complete reading Eric Evan’s brilliant book I see that this stuff has been encouraged by him since 2004.
So, my 5 reasons I love Immutable objects
- Reduced cognitive load. Once created that is it, no need to mentally track any changes or side effects.
- Expressive/Discoverable. Readonly objects are easy to use because there is only one way, Construct –> read. See pit of success
- Maps to DDD concept of a value type
- Enabler of side effect free programming
- .. therefore they are thread safe