TomB
March 9, 2015, 9:06am
264
tony_marston404:
You have just confirmed what I have been claiming all along that there is no single document called “best practices” which is universally accepted by all programmers. Instead there is a vast collection of documents written either by individuals, groups or organisations which do nothing more than identify what “best practices” means to them. S
None of those millions of sites say that creating a 9000 line class that mixes 10+ responsibilities is a good idea. The fact that dozens or more professional and/or academic well respected programmers all independently come to the same conclusion actually gives it more weight .
TomB:
The problem with this quite loose approach to the definition of encapsulation is that here:
new A(new B));
The calling code knows that A needs B, which by that definition is “broken encapsulation”. The problem is, from the other perspective:
class A {
public function __construct() {
$this->b = new B;
}
}
Has just moved the issue. The A class, and the author of the A class know which exact implementation of B is being used. Which, by the same definition is “broken encapsulation” from the other end of the program: A knows about the implementation of B when it shouldn’t.
It really is an issue of perspective:
If you’re looking at encapsulation between A and B from the perspective of the A class itself, then DI has better encapsulation because A knows nothing about the implementation of B.
If you’re looking at encapsulation between A and B from the perspective of the code constructing A, then constructing B in A’s constructor has better encapsulation because the calling code doesn’t know anything about the dependencies of A.
The fundamental issue here is that you need to express the relationships between objects somewhere. The advantage of DI is that it’s only one place: The program entry point, not spread among every class.
So no then. None of these posts do what I asked. I am still waiting for an example of when DI is inferior and for you to explain the metric you are using to measure the difference. Until you do this, I’m going to assume you can’t, which makes your opinion void.
TomB:
To do this, you need to provide:
A (complete, minimal, self-contained) code example where you are using DI to achieve a goal
A (complete, minimal, self-contained) code example where you using another approach that meets the same goal that you claim an improvement has been made over the DI version of the code
A brief explanation of the metric you are using to define “improved”.
Until you do this, your argument is moot and no amount of shouting about definitions to quoting me out of context is going to help you make your point.