A.Non A.Non - 2 months ago 9
Java Question

When using a Builder Pattern why shouldn't I reuse the builder-object to access the object configuration?

when using a Builder Pattern why shouldn't I reuse the builder-object to access the object configuration?
For example:

Normal way:

ObjectA(ObjectBuilder b) {
this.a = b.getA();
}
public Object getA(){
return this.a;
}


But why can't I just use this:

ObjectA(ObjectBuilder b) {
this.builder = b;
}
public Object getA(){
return this.builder.getA();
}


Thanks :)

Answer

A large reason for using a builder is to build an immutable object: the builder is mutable, the thing it builds isn't (necessarily).

If you delegate to the builder, your instance would be mutable again: anybody who has a reference to the same instance of ObjectBuilder can change your ObjectA. This means that any checks you do on the validity of the state of the ObjectA at construction time can be invalidated.

If you want a mutable object, there is no need for the builder: just have setters on your ObjectA.

Comments