I quite like to use immutable value objects. They are really useful. However there are limits to this. Especially when it comes to objects with rich internal structures. Here you end up with a multi-line nested constructor call to create your object. I don’t think this is terribly readable.
Also I see that people make objects immutable that you would classically consider entities. The first problem I have, is that immutability makes it hard to change the objects (well that’s in the name). I don’t want to construct a new object to update a field in a form. People will argue that you can have builders, but in most practical cases I have seen the builder class was fully function dependent of the class that was being built – duplication by any other name.
Another argument for immutability is sharing. This is only partly valid. In most architectures I have seen so far object instances were not shared across threads. The sharing was being done through the database. Furthermore the whole thing is a trade-off anyway: immutable objects can be shared without copy operation, mutable objects can be changed without copy operation.
Back to the entities, there is another risk: if you copy objects whenever you change them you might actually keep a reference to a stale version. The underlying issue is that the identity of your entity (on the logical level) and the identity of your object (in the physical object space) diverge:
Car myCar = new Car(Color.BRITISH_RACING_GREEN); Car myOpenCar = myCar.openDoor(); return myCar; // <= This might be a bug...
So immutability is useful (especially for value semantics), but it does not fit every problem. Not really a surprise…
Leave a Reply