I've been using the Builder pattern to create objects with a large number of attributes, where most of them are optional. But up until now, I've defined them as final, as recommended by Joshua Block and other authors, and haven't needed to change their values.
I am wondering what should I do though if I need a class with a substantial number of optional but non-final (mutable) attributes?
My Builder pattern code looks like this:
public class Example {
//All possible parameters (optional or not)
private final int param1;
private final int param2;
//Builder class
public static class Builder {
private final int param1; //Required parameters
private int param2 = 0; //Optional parameters - initialized to default
//Builder constructor
public Builder (int param1) {
this.param1 = param1;
}
//Setter-like methods for optional parameters
public Builder param2(int value)
{ param2 = value; return this; }
//build() method
public Example build() {
return new Example(this);
}
}
//Private constructor
private Example(Builder builder) {
param1 = builder.param1;
param2 = builder.param2;
}
}
Can I just remove the final
keyword from the declaration to be able to access the attributes externally (through normal setters, for example)? Or is there a creational pattern that allows optional but non-final attributes that would be better suited in this case?
Best Answer
You got it other way around.
The point of Builder is to allow creation of class, which has lots of final, but optional parameters. If you didn't use Builder, then you would have to use tons of different constructors.
But if your class doesn't need those fields to be final, then there is no need for a Builder. Just make them mutable and set them after you create the instance.