Immutable Objects
I am back in Chicago for more training. This time it is Object Bootcamp. One thing that we touched on today was the idea of immutable objects. Put simply, this means that the state of an object cannot be changed. From a conceptual point of view, this makes a lot of sense. If you have a Money and you create a new object worth $5.00 there is no way that you should be able to change that into $2.00. If you want to have $2.00, you need to create a new object since in reality you would no longer have $5.00.
The trick comes when you need to scale this up to more complex domain objects which have more then one or two attributes. So for example, how does this translate when you have a Class that represents a person. If that person’s name changes, does that make them a new person? Probably not. However, if their address changes, and the address is represented by an object composited within Person, then you can make a very strong argument that it represents a new address. Therefore, a new Address object needs to be instantiated.
The same argument could be made for a person’s email address or phone number.
This idea becomes important when you think about creating multi-threaded systems. Having all of your domain objects immutable means that they are all read-only. This means that you really do not have any shared resources between threads and it reduces the complexity of the entire application.
I am still thinking all of this through and have yet to try any of it on a real life application. In theory though it makes a lot of sense, but I am not sure how well it will work in practice. I think there will always be some information in domain model objects, or any class for that matter, that it makes sense to have change and thus violates this idea of having all objects be immutable.
Well that maybe, but it depends on the type of application your building and what you want to be immutable. You could have users immutable if you want or maybe things you store in history (system log of your application). But try to see what the advantage of this is… Don’t forget you can always add synchronize to your method definitions.
take care.
In the book Domain-Driven Design, Eric Evans writes about the importance of knowing your (immutable) Value Objects from your (changeable) Entities, in the very same direction you are reasoning.
The book: http://domaindrivendesign.org/books/
Cool. I have had the book Domain-Driven Design on my to-read list for a while now, I think I will earmark it as my next book. Just have to work my way through Agile Web Development with Rails first.