Saturday, December 01, 2007

Object Graphs and Dependency Injection

An application is supposed to have a graph of objects as a result of the following-

1. Objects are designed to be interacting with each other following two rules of thumb "Highest Cohesion" and "Lowest coupling". So, a class instead of taking all the responsibilities only takes care of some high cohesive ones and depends on other partner classes for the rest of the services. This dependency creates a graph like structure with objects as the nodes and dependencies as the edges.

2. We expect our classes to "take only single responsibility" and "encapsulate anything that varies" to make sure we have good compact manageable classes. But this at the same time means a lot of new dependencies resulting in a complex graph of objects. The more one class is used and reused we have even more complex graph..


This dependency graph stands in a cut-point of the two conflicting interests. A class with less dependency makes it easy to "test", but a class with less dependency "looses re-usability". Because, once a class has a lot of dependencies, its hard to isolate an independent part of the class and test. On the other hand, if a class has only a few dependencies, its likely that the class is doing a lot of stuffs itself and so, has many reasons to change.

Now to break the trade-off, I consider the key points again. If a class is high cohesive, it must depend on other classes for some non-cohesive services. This will also break down the classes into smaller classes which are more likely to be reusable than the longer ones. So, I have the feeling that dependencies are not that bad.

Now, the problem boils down to testing a class with all the dependencies on other classes. Well, we cannot actually delete the dependencies, still, we can inject them!

I hope to follow up on my understanding on dependency injection soon in my future posts.