Here is a generic imaginary example made up for this post. Consider 6 classes
TableFactory, TableData, TableCRUD, TableSchema, DBConnect, Logger.
TableFactory
is the outer class, let's say it holds a TableData
object for a DB table.
In this TableFactory
, there are no calls to TableSchema
or DBConnect
or logger
. I am aiming for an example of inner objects not needed in outer scope.
TableData
is an inner fetches and operates on the data, so it needs TableCrud
, DBConnect
and Logger
.
TableCrud
contains TableSchema
and needs DBConnect
, and Logger
.
DbConnect
itseld, to make things fun, needs a Logger. My example is now 3 scopes deep.
My Question is pretty simple, if you have an object 3 (or more) scopes in that are not called upon by objects on outer scope, how does one send those objects from outer to inner scope without breaking the Interface Segregation Principle -> TableFactory shouldn't have to deal with DBConnect or Logger needed by inner objects.
If one respects basic OOP principles and aims for easy testability -> you would have outer objects needing injection of the 5 objects, and then have getter methods that woud pass the objects needed further up the chain. And inner scoped objects would in turn require injection of the dependencies of their inner 3-scope-deep objects, with getters for those too. This makes for outer scoped objects requiring many dependencies, and getters just to pass those on.
Is there an alternative to this object-passing methodology, something I missed along the way? Please share! Any links/comments appreciated.
If you are stumbling upon the same question check Hervey's article that hits the bulls eye
http://misko.hevery.com/2008/10/21/dependency-injection-myth-reference-passing/
In case the article vanishes in future here is the excerpt
"Every object simply knows about the objects it directly interacts with. There is no passing of objects reference just to get them into the right location where they are needed."
So what one need to do is instead of creating a deep nested object graph with passing the dependencies fro top to bottom, go horizontal and manage dependencies elsewhere.
It's a common misconception that dependencies need to be passed through the object graph. To summarize the example Miško Hevery gives in Clean Code: Don't look for things, a House that needs a Door, doesnt need to know about the Lock in the Door:
As you can see, House is completely oblivious of the fact that the Door in it requires a lock. It's the responsibility of the HouseBuilder to create all the required dependencies and stack them together as they are needed. From the inside out.
Consequently, in your scenario you have to identify which objects should operate on which dependencies (cf Law of Demeter). Your Builder then has to create all collaborators and make sure the dependencies are injected into the appropriate objects.
Also see How to Think About the “new” Operator with Respect to Unit Testing