1

IF I have a class that uses a builder pattern for construction because most params are optional how are default values specified? For instance in the situation below, if the client builds with only the compulsory item but later queries the optional items, what happens?

  public class BClass {
    private final int compulsoryItem;
    private final int optional1;
    private final String optional2;

    public int getCompulsoryItem() { return compulsoryItem; }
    public int getOptional1() { return optional1; }
    public int getOptional2() { return optional2; }

    private BClass(Builder builder) {
       this.compulsoryItem = builder.compulsoryitem;
       this.optional1 = builder.optional1;
       this.optional2 = builder.optional2;
    }

    public static class Builder {
       private int compulsoryItem;
       private int optional1;
       private String optional2;

       public Builder(int c) { this.compulsoryItem = c; }
       public Builder opt1(int o1) { this.optional1 = o1; return this; }
       public Builder opt2(String o2) { this.optional2 = o2; return this; }

       public BClass build() { return new BClass(this); }
    }


  }
2
  • 6
    Initialise defaults in the builder? Commented Aug 5, 2014 at 3:00
  • 1
    Either that or simply assign default values on declaration. Commented Aug 5, 2014 at 3:04

1 Answer 1

1

Just specify defaults in the Builder class. They aren't final in the builder, so they can be reassigned. You can't set the defaults in the actual BClass becasue all the fields are final.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.