mercredi 7 novembre 2018

Factory pattern with or without reflection

Today we were arguing if it was better to create factory pattern with switch or use some dynamic creation or use some reflection. We are using Laravel and here are three scenarios:

1) using switch

class SimpleFactory {
    public function make(string $slug)
    {
        switch ($slug) {
            case 'firstOption':
                return new FirstOptionProcessor();

            case 'secondOption':
                return new SecondOptionProcessor();
        }

        throw new NotFoundException();
    }
}

2) using dynamic creation:

class DynamicFactory {
    private $optionArray = [
        'firstOption' => FirstOptionProcessor::class,
        'secondOption' => SecondOptionProcessor::class
    ];

    public function make(string $slug)
    {
        if(!isset($this->optionArray[$slug])) {
            throw new NotFoundException();
        }

        return app()->make($slug);
    }
}

3) using reflection

class ReflectionFactory {
    public function make(string $slug)
    {
        $class = ucfirst($slug) . 'Processor';

        if(!class_exists($class)) {
            throw new NotFoundException();
        }

        return app()->make($class);
    }
}

There won't be more than ten slug options. I think that the easiest way is the first one. It is easy readable and maintenance is also simple. But my colleagues arguing that this is not SOLID principle and looks quite ugly.

I think that second can be also used but it isn't such a straightforward way.

And in the end I don't like third scenario because developer must keep naming convention and that can be sometimes too difficult (ie. slug will be third-option; then you have to convert it to right class name).

What do you think about it and which way are you using factory pattern?





Aucun commentaire:

Enregistrer un commentaire