I am a huge fan of immutables, especially for value objects. Even in clumsy static languages like C# and Java that seem to throw every obstacle in your way to deter you from using them I find the benefits outweigh the costs.
Sometimes though a mutable makes sense. Whether that's because of the restrictiveness of a framework or the paradigm of the language. But what if we don't want to loose the power of immutables behind the scenes?
Introducing The Immutable Wrapper Pattern!
The Immutable Wrapper is a wonderfully simple pattern because there are only two things you need to do.
- Create a class with only one mutable field
- Wrap the immutables functions.
Here's an example. You've got a copy-on-write list implementation but your binding it to some GUI control that gives you a big headache if you try and point it to a different data source.
Here's your immutable:
private readonly IEnumerable items;
return new CopyOnWriteList(new List(items, item));
Now wrap it:
list = list.Add(item)
There, it couldn't be simpler. So simple in fact I don't know what else to say. Enjoy!