Let's say I have a class Dot
with a builder:
public class Dot {
private final Double x;
private final Double y;
private final Color color;
private Dot(Double x, Double y, Color color) {
this.x = x;
this.y = y;
this.color = color;
}
public static Builder createBuilder() {
return new Builder();
}
public Double getX() { return x; }
public Double getY() { return y; }
public Color getColor() { return color; }
public Builder getBuilder() {
return new Builder().setX(x).setY(y).setColor(color);
}
public static class Builder {
private Double x;
private Double y;
private Color color;
public Builder setX(Double x) {
this.x = x;
return this;
}
public Builder setY(Double y) {
this.y = y;
return this;
}
public Builder setColor(Color color) {
this.color = color;
return this;
}
public Dot build() {
return new Dot(x, y, color);
}
}
}
Now I see two possible ways one could instantiate the builder. Through its constructor:
new Dot.Builder().setX(...
or through a factory method:
Dot.createBuilder().setX(...
(In the latter case I would make the Builder
's constructor private
.)
Factory methods (or factories) are (to my knowledge) useful when the actual type of the returned value might change later on. This is something that is probably not going to occur with a builder.
My best argument for using a factory method would be: Say that the builder uses a final field String id
that has to be set in its constructor, but certain restrictions apply to what constitutes an ID. Throwing an exception on an illegal id string should not be done in a constructor. Therefore a factory method would be better.
However I feel like I missed some more important arguments. Does a best practice for this case exist? What other arguments exist for/against using a factory method here?