Immutability

Immutability

One of biggest trends in the last few years is functional programming, once again proving that fashion goes in circles.

Immutability is a central tenet of functional programming, the idea is that variables are not variable, once an object is created it does not change. If you need to modify a property in an immutable object you return a new object.

This is easy to implement in functional languages like F# or Haskell and it can be done in more object oriented languages like Java or C#

 public class MyImmutableClass
 {
    public int IntProperty { get; }
    public string StringProperty { get; }

    public MyImmutableClass(int intProperty, string stringProperty)
    {
        IntProperty = intProperty;
        StringProperty = stringProperty;
    }
 }

This creates a C# class where once the properties are set in the constructor they cannot be modified.

Because the properties cannot be modified we don't have concurrency issues, the class is automatically thread-safe. We can reference the same object from any number of separate threads or processes at the same time and be absolutely sure that the data is consistent.

Suppose in the example above we want to make sure that IntProperty has a value greater than zero. Because the value cannot be modified after it is created a single validation check in the constructor is enough to ensure correctness through the entire application.

This simplifies development while eliminating entire ranges of possible bugs. We can very easily ensure that IntProperty will always be in a valid range and that StringProperty will never throw a NullReferenceException and anything that prevents those has to be a good thing!