2

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?

gnat
20.5k29 gold badges117 silver badges308 bronze badges
asked Aug 17, 2014 at 19:47
1
  • I think you need an applicative. Tough luck about Java.. Commented Aug 17, 2014 at 20:25

1 Answer 1

1

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.

answered Aug 19, 2014 at 12:36

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.