Rodrigo Machado
Rodrigo Machado

Reputation: 87

setter, validator and dependency injection

Let's say I have a Thing class, and I need to use some specific date validation that is provided by MySpecificDateValidation class that extends Zend_Validate_Abstract.

In the Thing class, I was thinking about dependency injection and wondering if this code:

public function SetDateBegin($dateBegin) {
    $dateValidator = new MySpecificDateValidation();
    if ($dateValidator->isValid($dateBegin)) {
        $this->dateBegin = $dateBegin;
    } else {
        throw new Exception /*...*/;
    }
}

should be refactored to:

public function SetDateBegin($dateBegin, MySpecificDateValidation $dateValidator) {
    if ($dateValidator->isValid($dateBegin)) {
        $this->dateBegin = $dateBegin;
    } else {
        throw new Exception /*...*/;
    }
}

or there is something like a few dependency that you can live with?

Upvotes: 2

Views: 236

Answers (1)

vascowhite
vascowhite

Reputation: 18440

Your second option will be much easier to unit test as you will be able to mock the validator and inject the mocked object instead of the real one.

If you try to unit test the first option you end up testing the Thing class plus anything it depends on, such as the validator. If a unit test fails, you then have to track the failure through all the dependencies.

The point of dependency injection is to allow you to isolate your classes from their dependencies so you test each class in isolation.

So, from a testing point of view, you should inject all dependencies, always.

Upvotes: 4

Related Questions