In this 6 year old question top answers say that it is not possible to verify immutability. On the other hand on the bottom there are two quite recent answers which suggest that one can use:
To detect if class is immutable.
My questions are: Are these tools useful in real life? Is there any other (better) solution? Has anything changed during these few last years?
While I'm sure there are many tools for directly testing if a class is immutable the real issue is testing immutable classes that allow fields that have an interface or abstract class declaration. Basically only sealed immutable classes can be allowed as child fields since inheritance often breaks immutability.
Its pretty hard to make composite immutable objects with out using the Java Collections API (ie not using Map
, List
or Set
, etc.
The other issue is that just because a field is final
doesn't really make it "final". Many serialization tools like Hibernate will happily construct immutable objects and set final fields through reflection.
The only really way I see is of detecting true immutability is through runtime analysis but it may take a long time before your code actually hits a specific use case where the mutability happens and I would imagine this sort of instrumentation to be rather expensive.
Another interesting sort of assumed corollary of immutable objects is that they should not change things outside when they are constructed. That is constructing an immutable object should be side effect free. This is where the tools will have a hard time. You could easily make an immutable object with a constructor that does all sorts of external nastiness like kicking off threads or setting system properties.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With