I will use example as its easier to show what I want to do. I have three classes X, Y and Z, and I would like to be able to have them as immutable objects. Here they are.
Class X :
public class X{
private int id;
private String dataX;
private Collection<Y> collectionOfY;
private Collection<Z> collectionOfZ;
/* Constructors */
/* Getters */
/* "with" functions */
}
Class Y :
public class Y{
private int id;
private String dataY;
private Collection<X> collectionOfX;
private Collection<Z> collectionOfZ;
/* Constructors */
/* Getters */
/* "with" functions */
}
Class Z :
public class Z{
private int id;
private String dataZ;
private Collection<X> collectionOfX;
private Collection<Y> collectionOfY;
/* Constructors */
/* Getters */
/* "with" functions */
}
So they are linked with each other and form a graph with a cyclic structure. I would like to have immutable object if possible. I've implemented "With" functions which will send back a copy of a given object with just one property changed.
But, if I implement a total immutability, I will possibly cause a replication of every data linked (directly or indirectly) to the object I changed : Changing "dataZ" usually means that I want to replace the old object by the newly created one in linked X and Y. Which will be replicated due to the change, etc ...
Another solution would be to render Collections which link the three classes not immutable (and only have a partial immutability) but then I lost almost all interest of trying to have immutability.
Anyone have a good idea ? Or am I asking for the impossible ? Should I return to the old setter (even if it means more complex concurrency management) ?
Thanks in advance ;)