I like the immutability concept but sometimes I wonder, when an application isn’t meant to be parallel, should one avoid making things immutable?
When an application isn’t multi-threaded, you aren’t plagued by shared state problems, right?
Or is immutability a concept like OOP that you either use all the way or not? Excluding the cases when something shouldn’t be immutable based on use/performance, etc.
I am faced with this question when writing an application for myself, that is moderately big (maybe like 1-2k lines).
I love immutability because it means I don’t have to trust other peoples code not to mess around with objects I expect to stay the same.
When you pass an object off to another component such as a
List<T>, you are at the mercy of what that component does. This is especially important when you return collections as properties.There’s nothing stopping a consumer of this class from clearing the collection out from under me. Even switching the return type to
IEnumerable<Bar>is not entirely safe. There’s nothing stopping some piece of badly written code from casting this back toList<T>and calling .Clear().However if I really want the collection to stay consistent I could rewrite it as followis
Now I’m safe from having to trust other code from using my class incorrectly. They can’t mess it up.