Dependency Injection vs Encapsulation?
07/10/2012 2 Comments
Let me start by saying that I LOVE the concept of dependency injection (DI) and feel that it should be utilized as much as possible. However, it seems to be somewhat contradictory to a concept that was drilled into me starting with my first programming classes: encapsulation.
Let me illustrate the conflict with an example. Proper DI techniques say that you should create your classes along these lines:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php class Foo { protected $bar; protected $baz; public function __constructor($bar,$baz){ $this->bar = $bar; $this->baz = $baz; } public function myMethod($val){ $this->bar->attr = $val; } } $bar = new Bar(); $baz = new Baz(); $foo = new Foo($bar,$baz); $foo->myMethod(5); |
Where this seems to go against the concepts of encapsulation, is the fact that instances of Bar and Baz now have to exist outside of the Foo class. If interaction with those classes is not needed outside of the Foo class, wouldn’t it be better to hide it’s existence all together?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php class Foo { protected $bar; protected $baz; public function __constructor(){ $this->bar = new Bar(); $this->baz = new Baz(); } public function myMethod($val){ $this->bar->attr = $val; } } $foo = new Foo(); $foo->myMethod(5); |
The example above might seem a bit trivial, but what if the creation of a Bar instance was very complex, but still requires nothing outside of the Foo class in order to create it?
1 2 3 |
<?php $bar = new Bar($attr1,$attr2,$attr3,$attr4,$attr5); $foo = new Foo($bar); |
Am I missing something? Even if they are conflicting paradigms, I think DI is the better option, but are they really conflicting?
Recent Comments