Monday, January 19, 2009

5 reasons why I love Immutable objects

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

2 comments:

Unknown said...

my understanding of FSHARP* is that value/immutable types are the default.. Matthew Podwysocki writes a bit about his fetish for the functional world

fkn mac and no SHARP/HAsh key... but it has double ss thing § ... what the hell...

Sebastien Lambla said...

Immutables are thread safe yes, but you need to have conflict resolution and retry semantics. Otherwise, two threads happily modify two objects in two different ways, and you don't get any further.

Immutability and parallelism is the future!

@RhysC: try CTRL+ALT+3 for the sharp key, provided you have the apple keyboard drivers on windows :)