Readonlyness and immutability

I blogged about immutable objects not too long ago and I've come to mature my thoughts some more on the subject. This came to me while maintaining an existing code base (adding unit tests) and after reading a couple items in Bill Wagner's book, Effective C# (2004).

C# made the listener pattern very easy to implement with events. It's so easy to use - and it feels right to do so - that we often find ourself overusing events. This is a classic case of being able to use it doesn't necessarily mean you should; Not all the time at least.

What do events have to do with immutability? you might wonder. Well, rendering an object mutable usually makes it harder to keep track of changes. In C#, that problem requires very few lines of code; With a little configuration and Resharper's live templates, implementing an event-throwing property takes two seconds (literally). However, we often forget the make things immutable - or have parts of it readonly - when we should. Is there a big difference between the following snippets?

public class Customer
    public Customer() {}

    public string Name { get; set; }

public class Customer
    public Customer(string name) { = name; }

    private readonly string name;
    public string Name { get { return name; } }

Technically, there's only a minor difference; Nonetheless, it has far-reaching implications:

  • You can hardly base uniqueness on a customer's name when it's modifiable;
  • Wherever customers are provided (say to list them), there's a chance the name of a customer could change in the first version;
  • And so on...

Whatever the situation is, we should always fall back on the object's conceptual definition: Is it possible for a customer to change his name within his lifetime in the system? Simple questions like that we suffice to resolve any dilemma about readonlyness or immutability.

All of this is simple; we're talking about basic OOD principles. But it often helps to take a step back and look at the big picture when designing business objects. It may not be a huge advantage to render a property readonly instead of modifiable but it makes a huge difference if you can make an entire object immutable.

Posted by: Bryan Menard
Last revised: 22 Oct, 2011 10:01 PM History


No comments yet. Be the first!

No new comments are allowed on this post.