6

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

A.Non
  • 71
  • 1
  • 3
  • 8
    The whole point about using a builder is to build immutable objects: the builder is mutable, the thing it builds isn't. If you delegate to the builder, your instance is mutable again: anybody who has a reference to the same instance of `ObjectBuilder` can change your `ObjectA`. If you want a mutable object, there is no need for the builder: just have setters on your `ObjectA`. – Andy Turner Sep 07 '16 at 15:14
  • That's a pretty good answer. It's true I don't want A to be changed after the constructor. That's why I used the builder in the first place. – A.Non Sep 07 '16 at 15:21

1 Answers1

9

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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • 3
    If you want a mutable object, there is _less_ need for the builder. Builders are good for more than just immutability. – jaco0646 Sep 07 '16 at 17:47
  • @AndyTurner I have similar question on Builder pattern [here](http://stackoverflow.com/questions/41206286/how-to-clone-old-builder-to-make-a-new-builder-object). Wanted to see if you have can help me out over there. –  Dec 20 '16 at 00:27