Does it make sense to clone copies of dependencies (Dependency Injection)?
Maxiscool’s Question:
Say I have a class that has a few methods that depend on another object in order to carry out their duty. The difference being they all depend on the same class of object, but need different instances of the class. Or more specifically, each method needs a clean instance of the class because the methods will be modifying the state of the dependency.
Here is a simple example I had in mind.
class Dependency {
public $Property;
}
class Something {
public function doSomething() {
// Do stuff
$dep = new Dependency();
$dep->Property = 'blah';
}
public function doSomethingElse() {
// Do different stuff
$dep = new Dependency();
$dep->Property = 'blah blah';
}
}
Technically I could do this.
class Something {
public function doSomething(Dependency $dep = null) {
$dep = $dep && is_null($dep->Property) ? $dep : new Dependency();
$dep->Property = 'blah';
}
public function doSomethingElse(Dependency $dep = null) {
$dep = $dep && is_null($dep->Property) ? $dep : new Dependency();
$dep->Property = 'blah blah';
}
}
My trouble here is I constantly have to check that the dependent object being passed in is in the correct state. The state being newly created. So instead I was thinking of just doing something like this.
class Something {
protected $DepObj;
public function __construct(Dependency $dep) {
$this->DepObj = $dep && is_null($dep->Property) ? $dep : new Dependency();
}
public function doSomething() {
// Do stuff
$dep = clone $this->DepObj;
$dep->Property = 'blah';
}
public function doSomethingElse() {
// Do different stuff
$dep = clone $this->DepObj;
$dep->Property = 'blah blah';
}
}
This allows me to get one instance of an object in the correct state, and I can just copy it if I need another one. I’m just curious if this makes sense, or if I’m over looking a fundamental guideline about dependency injection and keeping code testable.
If doSomething()
and doSomethingElse()
both does similar things in two functions, then its a bad choice. It this case created a feeder function and feed two different object to this function.
But if there are both responsible for two different action requiring a clone of the dependency object, then it is not bad.