Immutability
suggest changeImmutability is common in functional programming and rare in object-oriented programming.
Create, for example, an address type with mutable state:
public class Address
{
public string Line1 { get; set; }
public string Line2 { get; set; }
public string City { get; set; }
}
Any piece of code could alter any property in the above object.
Now create the immutable address type:
public class Address
{
public readonly string Line1;
public readonly string Line2;
public readonly string City;
public Address(string line1, string line2, string city)
{
Line1 = line1;
Line2 = line2;
City = city;
}
}
Bear in mind that having read-only collections does not respect immutability. For example,
public class Classroom
{
public readonly List<Student> Students;
public Classroom(List<Student> students)
{
Students = students;
}
}
is not immutable, as the user of the object can alter the collection (add or remove elements from it). IEnumerable<Student> hides Add, but it still shares the original list. Copy the elements into a ReadOnlyCollection<Student> when later changes to the caller’s list must not appear:
public class Classroom
{
public readonly ReadOnlyCollection<Student> Students;
public Classroom(IEnumerable<Student> students)
{
Students = new ReadOnlyCollection<Student>(students.ToArray());
}
}
List<Student> list = new List<Student>();
// add students
Classroom c = new Classroom(list);
With the immutable object we have the following benefits:
- It will be in a known state (other code can’t change it).
- Its own fields do not change, so that state needs no lock. A mutable
Studentis still mutable. - The constructor offers a single place for validation.
- Knowing that the object cannot be altered makes the code easier to understand.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents