Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setters AND ( not OR or VS ) builder patterns

I have a situation where I use a builder pattern for constructing an object. Best example to give is the pizza code

public class Pizza {
  private int size;
  private boolean cheese;
  private boolean pepperoni;
  private boolean bacon;

  public static class Builder {
    //required
    private final int size;

    //optional
    private boolean cheese = false;
    private boolean pepperoni = false;
    private boolean bacon = false;

    public Builder(int size) {
      this.size = size;
    }

    public Builder cheese(boolean value) {
      cheese = value;
      return this;
    }

    public Builder pepperoni(boolean value) {
      pepperoni = value;
      return this;
    }

    public Builder bacon(boolean value) {
      bacon = value;
      return this;
    }

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

  private Pizza(Builder builder) {
    size = builder.size;
    cheese = builder.cheese;
    pepperoni = builder.pepperoni;
    bacon = builder.bacon;
  }
}

So far so good.

Now lets assume a usecase where I need to update the cheese. That needs a setter. I have never seen a single example where builder patterns coexist with setters, making me suspicious that what I was upto was an anti-pattern.

Can setters AND builders coexist together ?

like image 402
JavaDeveloper Avatar asked Mar 14 '14 21:03

JavaDeveloper


1 Answers

You've never seen that used because most of the time, the builder pattern is used to build an immutable object.

But I don't see why they couldn't coexist. The builder builds an object, and you want the built object to be mutable, then it can have setters. But then, if it is mutable and has setters, why not build the object using a simple constructor, and call setters to change the state? The builder isn't really useful anymore, unless only one or two fields among many are mutable.

like image 124
JB Nizet Avatar answered Sep 21 '22 17:09

JB Nizet