DEV Community

Discussion on: Builder Design Pattern

Collapse
 
dallgoot profile image
dallgoot

that example is so OOP overkill that i don't know where to start

first:

new BurgerBuilder(14)).addPepperoni().addLettuce().addTomato().build()

instead of

new Burger(14, false, true, true, true)

1 constructor VS 1 constructor + 4 methods call, what's the gain ?

second:
you got 2 objects creations instead of 1
what's the gain ?

third: immutability

public class Burger {
    private int size;

    private boolean cheese = false;
    private boolean pepperoni = false;
    private boolean lettuce = false;
    private boolean tomato = false;

    public Burger(BurgerBuilder builder) {
        this.size = builder.size;
        this.cheese = builder.cheese;
        this.pepperoni = builder.pepperoni;
        this.lettuce = builder.lettuce;
        this.tomato = builder.tomato;
    }
}

is already immutable and the builder is the one thas is not with the added methods
what are the "addX" methods for ? if immutability is the goal ?

this example fails to display the purpose of the builder pattern IMHO

for another idea of implementation:

new Burger(size, ingredients)

with size and ingredients being higher representation (Dict/Set/HashMap)for example:
size can be a set of "big, small, medium"
ingredients can be "pepperonni: true" or "cheese: new Cheese("gouda")"
We have to kill this trend to make code for making code and remember that code is a higher level of expressing a solution/process.