jeudi 21 avril 2016

Reusable object v state and new object creation

What are the implications of

// Use a setData method to populate data on the object.  This will allow data to be set multiple times with a single object
class Testy
{
    private $data = [];

    public function setData(array $data)
    {
       $this->data = $data;      
    }

    public function validate()
    {
        foreach($this->data as $data) {
            if (! isset($data['id'])) {
                return false;   
            }
        }
        return true;
    }
}

versus

// Set data using the constructor that will require multiple objects to handle multiple use cases
class Testy
{
    private $data = [];

    public function __construct(array $data)
    {
       $this->data = $data;      
    }

    public function validate()
    {
        foreach($this->data as $data) {
            if (! isset($data['id'])) {
                return false;   
            }
        }
        return true;
    }
}

versus

// Set data to be validated directly on the validate method.  This is the most concise of the 3 but the class simply becomes a wrapper for the method which may be a smell that it belongs elsewhere.
class Testy
{
    public function validate($data)
    {
        foreach($data as $data) {
            if (! isset($data['id'])) {
                return false;   
            }
        }
        return true;
    }
}

To provide some context: the example is very simplified and each $data array will contain objects used for validation. I wanted to know in a scenario where this object might be used several times in a given request, which of the examples would be considered better and if there are any implications of any of the approaches listed.

Aucun commentaire:

Enregistrer un commentaire