Search code examples
javaunit-testingimmutability

Unit testing for object immutability


I want to make sure that a given group of objects is immutable.

I was thinking about something along the lines of:

  1. check if every field is private final
  2. check if class is final
  3. check for mutable members

So I guess my question is: is 3. possible ?

I can check recursively whether every member of a class has its fields private final, but this is not enough since a class can have e method named getHaha(param) which adds the given param to an array for instance.

So is there a good way to check if an object is immutable or is it even possible ?

Thanks,


Solution

  • If you generate your data model and all its code, you can ensure the possible Data Value objects you create will be immutable to meet your needs.

    The problem you have is that there is different forms of immutability. Even String would fail your test Are String, Date, Method immutable? You can prove that a class is strictly immutable this way, but you are likely to be better off generating your data model.