I was implementing an immutable class whose structure is as below :
public final class A{
private final B bOb;
public A(){
bOb = new B();
}
public A(A a){
bOb = new B(a.bOb);
}
public A addData(Type data){ // Type - Integer,String,char,etc.
A newA = new A(this); //making a copy of the object that is calling addData method
newA.bOb.add(data);
return newA;
}
}
Is this implementation correct ? Let’s say the object bOb is a list.
It is not totally immutable, since B appears to be mutable itself (via the add method) and A contains an instance of B.
However I think it is effectively immutable (i.e. it behaves as if it was immutable from the perspective of an external observer) providing that all the following are true:
new B(B)performs a complete deep copy ofB(if not thenaddDatamay mutate something within the originalB)bObvia any other meansYou get most of the benefits of immutability from being effectively immutable so I think this design is OK providing
Typeis immutable – it’s fine to mutate an object during it’s construction providing it never gets mutated after you pass a reference to someone else. A good example of this isjava.lang.String– internally it contains a mutable array that is written to while the String is constructed but never changed after that point.