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

1

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

Dashed answered 7/9, 2016 at 15:12 Comment(2)
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.Lori
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.Dashed
L
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.

Lori answered 7/9, 2016 at 15:24 Comment(2)
If you want a mutable object, there is less need for the builder. Builders are good for more than just immutability.Mcclelland
@AndyTurner I have similar question on Builder pattern here. Wanted to see if you have can help me out over there.Hydrodynamics

© 2022 - 2024 — McMap. All rights reserved.