Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 985
A.Non Avatar asked Sep 07 '16 15:09

A.Non


1 Answers

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.

like image 161
Andy Turner Avatar answered Sep 25 '22 16:09

Andy Turner