mercredi 20 avril 2016

Composition or inheritance

interface DoSomething
{
    public function do();
    public function getId();
}

class DoSomethingGood implements DoSomething 
{
    private $dependency;

    private $id;

    public function __construct($id, $dependency)
    {
        $this->dependency = $dependency;
        $this->id = $id;
    }

    public function do()
    {
        if ($this->dependency->isActive()) {
            return true;
        }

        return false;
    }

    public function getId()
    {
        return $this->id;
    }
}

class DoSomethingBad implements DoSomething 
{
    private $id;

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

    public function do()
    {
        return false;
    }

    public function getId() {
        return $this->id;
    }
}

Should I be using composition here or would inheritance be better? The difference is in how these classes implement the do() method. The first class has a dependency it requires and some internal logic to decide whereas the other is simpler.

Aucun commentaire:

Enregistrer un commentaire