mardi 10 avril 2018

Arguments validation in factory constructor?

About the class

I have a class. Its constructor has some parameters. Inside the constructor, one or more values passed as arguments at the instantiation time are validated. If one of them is not valid, an exception is thrown.

About the factory

I also have a factory class, whos factory method should create an object of the above type. The factory constructor has some of the parameters defined in the class above. The other parameters, needed for creating the object, are defined in the factory method.

Question

Should I validate the arguments passed to the factory constructor, too?

Thank you for your time and patience. Feel free to ask me anything.


Here is an example:

Question: Should I define a validateColor method in the HatFactory too, although the identical validation already happens in the Hat class?

test.php

<?php

use Tests\HatFactory;

$hatFactory = new HatFactory('yellow');

$hat1 = $hatFactory->createHat('AdiDix');

$hat2 = $hatFactory->createHat('NiKy');

echo '<pre>' . print_r($hat1, TRUE) . '</pre>';

echo '<pre>' . print_r($hat2, TRUE) . '</pre>';

Tests/Hat

<?php

namespace Tests;

class Hat {

    /**
     * Hat brand.
     *
     * @var string
     */
    private $brand;

    /**
     * Hat color.
     *
     * @var string
     */
    private $color;

    /**
     * @param string $brand Hat brand.
     * @param string $color Hat color.
     */
    public function __construct(string $brand, string $color) {
        $this->validateColor($color);

        $this->brand = $brand;
        $this->color = $color;
    }

    /**
     * Validate the hat color.
     *
     * @param string $color Hat color.
     * @throws Exception Color not allowed.
     */
    private function validateColor(string $color) {
        if ($color !== 'red' && $color !== 'blue') {
            throw new Exception('The selected color is not allowed!');
        }
    }

}

Tests/HatFactory.php

<?php

namespace Tests;

use Tests\Hat;

class HatFactory {

    /**
     * Hat color.
     *
     * @var string
     */
    private $color;

    /**
     * @param string $color Hat color.
     */
    public function __construct(string $color) {
        $this->validateColor($color);

        $this->color = $color;
    }

    /**
     * Create a hat.
     *
     * @param string $brand Hat brand.
     */
    public function createHat(string $brand) {
        return new Hat($brand, $this->color);
    }

    /**
     * Validate the hat colour.
     *
     * @param string $color Hat color.
     * @throws \Exception Color not allowed.
     */
    private function validateColor(string $color) {
        if ($color !== 'red' && $color !== 'blue') {
            throw new \Exception('The selected color is not allowed!');
        }
    }

}

Aucun commentaire:

Enregistrer un commentaire