Mutable & Immutable Classes

This post describes a method for creating a mutable and immutable version of the same class. At a first glance, there may seem to be two obvious ways to approach this problem; either:

  1. Create a base Mutable Class and derive a Immutable version of this class; or
  2. Create a base Immutable Class and derive a Mutable version of this class.

To help decide which may be the best design, we can refer back to the principles of object-oriented design. The Liskov Substitution Principle states that subtypes must be substitutable for their base types.

Don’t inherit unless you really are (and can be treated in all respects) like what you derive from.

Keeping this in mind, we can see that solution one would violate this principle. You can not treat an Immutable object as a Mutable object. i.e. you would not want a user to be able to cast an immutable object, to it’s parents-type, so that the user could then mutate that object.

A simple implementation of solution two is shown below.

    public class ImmutableClass
    {
        public int SomeProperty { get; protected set; }
        public string AnotherProperty { get; protected set; }
    }

    public class MutableClass : ImmutableClass
    {
        public new int SomeProperty
        {
            get
            {
                return base.SomeProperty;
            }
            set
            {
                base.SomeProperty = value;
            }
        }

        public new string AnotherProperty
        {
            get
            {
                return base.AnotherProperty;
            }
            set
            {
                base.AnotherProperty = value;
            }
        }
    }

One thought on “Mutable & Immutable Classes

  1. This design is good but not perfect. It does not solve the issue of some code sending off a mutable object to a method that expects an immutable object. The receiving method might put that immutable object (which is actually mutable) into a cache or send it off to a separate thread for some parallel processing.

    I wrote an article recently that delves into those things: http://rickyhelgesson.wordpress.com/2012/07/17/mutable-or-immutable-in-a-parallel-world/

    /Ricky

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>