Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensure that class is immutable

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:

  • jcabi
  • mutability detector

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?

like image 722
Marcin Szymczak Avatar asked Jan 08 '15 16:01

Marcin Szymczak


Video Answer


1 Answers

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.

like image 161
Adam Gent Avatar answered Nov 03 '22 06:11

Adam Gent