jeudi 17 janvier 2019

"Changing" complex immutable object

This is the code:

class A{
prop1, prop2, prop3, prop4, ...

 private A(ABuilder b){
   this.prop1 = b.prop1;
   ...
 }

 A changeProp2(){
   //easiest way to return new immutable A?
 }

 class ABuilder{
   withProp1()
   withProp2()
   withProp3()
   ...
   build()
 }

}


A a = new ABuilder().withProp1().withProp2().build();
A newA = a.changeProp2();

I have immutable object (A in this case), that is constructed using Builder ABuilder. Now, when I want new A object from existing complex A object, in my case I can call method changeProp2(). This method should copy all the inner properties of object a, change only property2 to new value, and return new object newA.

What is the best way to do this?

Options I found so far are:

Inside changeProp2() method, I could copy all the properties - but this seems too much, and also not reusable if I have in future changeProp2() method.

//option1
return new ABuilder().withProp1(this.prop1).withProp2(this.prop2)....build();

Adding copy constructor to Builder, that will init Builder with values from existing object A, like this:

//option2
class ABuilder{
  ABuilder(A a){
    this.prop1 = a.prop1;
    ...
  }
}

return new ABuilder(this).withProp2(this.prop2).build();

This seems more reasonable for me in this case.

Are there any more options than this?

Aucun commentaire:

Enregistrer un commentaire