On Immutability

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…


Posted

in

by

Tags:

Comments

One response to “On Immutability”

  1. toni Avatar

    I Agree, there’s too much obsession about “immutable are good”, I’m afraid that in the java-world sometimes a getters/setters object (an entity) that goes in the DB does the job, even if it lacks of design.

    On the other hand, the biggest problem in Java is that you can’t really be totally immutable (imagine that you really need it, in a multi-thread application). You declare something final, like a Collection but surprise, people can still change the objects inside! Or what if you have list of lists, how can you declare that list inside final? You can’t.

    Scala might be better, but I’m still not sure, the JVM is behind the scenes, who knows…

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.