Immutable entities – Rob Allen's DevNotes

:

: 2

I've been thinking recently about using immutable objects for some of my model-layer entities. That is, an object that cannot be changed once it is created.

Immutable objects have a number of benefits including the fact that they are much easier to understand, simple to use and very easy to test. The main motivation for me is that an immutable object is very predictable as it's state doesn't change. This means that any calculated properties can be done once on creation. This is interesting as one application that I'm currently working on has a lot of calculated properties and it's a source of bugs when one property changes and all the dependent calculations aren't always done.

Immutable objects, as the name implies, cannot be changed. However, properties on our entities do need to change and we can't simply call a set method to change a property. To change an immutable object, we have to create a new object with the new data and delete the old one.

This is clearly more overhead than using a setter method to change a property, but I'm wondering if it's worth the cost for the simplifications elsewhere.

In traditional thinking about object orientation and the domain layer, entity objects have an identity that persists over time which is usually modelled as an id of some sort. The other values within the object change over time. For example a Customer object's title may change (e.g. received a doctorate), but it's still the same customer. As a result our Customer model entity is expected to be mutable. This is especially true if you are using an ORM as the object is coupled to the database row.

I think there's a clear set of entity objects in some of the applications that I write where my life would be simpler if they were immutable. This is especially true of fairly complex business applications with lots of interacting entities that are used to generate reports and analysis.

To me, this is an area worth exploring. Thoughts?