DEV Community

Discussion on: Builder Design Pattern

Collapse
 
wrongabouteverything profile image
wrong-about-everything

If a class has a constructor with a lot of arguments, the problem is in this class. Using a builder pattern just masks the problem, which is even worse. So I consider a builder an anti-pattern. I'd suggest to use a decorator instead:

interface Burger
{

}

class BreadWithCumin implements Burger
{
    private $size;

    public function __construct(Size $size)
    {
        $this->size = $size;
    }
}

class WithTomatoes implements Burger
{
    public function __construct(Burger $burger)
    {
    }
}

class WithCheese implements Burger
{
    public function __construct(Burger $burger)
    {
    }
}

If you object that Bread is a Burger, how about that:

class EmptyBurger implements Burger
{
    private $bread;

    public function __construct(Bread $bread)
    {
        $this->bread = $bread;
    }
}

class WithCumin implements Bread
{
    private $size;

    public function __construct(Size $size)
    {
        $this->size = $size;
    }
}

This code is highly composable, which probably means that it's good in terms of OOP.