Immutable objects

I can't stress how important immutable objects are in most designs. Most object-oriented languages will allow some mechanism to prevent swapping of references (through encapsulation mostly.) But there is very few support for "deep" immutability. For instance, in C#, one can easily use read-only properties to prevent a reference from being changed. But it's really unpleasant to try and prevent the value of that reference from being changed.

Sometimes, having setters' visibility (recursively) set to internal (or package visible in Java) will suffice to control some external changes. But there are other times where a design if far too 'fragile' to expose such setter, even internally.

In those cases, immutability can be a powerful design practice. Whenever you can make an object immutable, make yourself a favour; let it be.

Posted by: Bryan Menard
Last revised: 22 Oct, 2011 06:52 PM History

Comments

No comments yet. Be the first!

No new comments are allowed on this post.