Problem (Object Dependency)
We have object dependency when an object ‘x’ uses an object ‘y’, we say that ‘x’ is dependent on ‘y’. Object dependency becomes a problem when object ‘x’ needs to use another object dynamically, object ‘z’, instead of ‘y’. Strong dependency mixes both object (Data) and relation (logic) in one place and result in tight coupling that render the code much harder to modify and adjust.
Solution (Loose Coupling)
Genuine solution is to implement loose coupling pattern, such as dependency injection. Indeed, dependency injection allows objects to relate to each other but through an interface so that object ‘x’ will use interface ‘i’ while both ‘y’ & ‘z’ implement the interface ‘i’. This methodology allows the isolation between the implementation, creation, and logical dependency of an object.
Pros & Cons
Pros
- Loose coupling
- Centralized configuration
Cons
- Adding additional coding to handle relations
- Linking objects together will become an overhead by itself when having too many instances
Example
Farm investor winform advisor suggests the amount of money required to have successful farm investment according to the number and type of animals raised in the farm. I did it for my grand ma “Rquia” because she has a small farm and likes cows and sheep very much. Grand hug to her!
Implementation
The code includes three examples of implementing dependency injection using:
1) Constructor
Using constructor is a good method. It does all in the creation of the object but once the dependency is set, there is no way to change it. More flexible method would be using setter.
2) Setter
Setter is very flexible in setting the dependency dynamically, but for further loosening. It is better to make the relation completely handled by interfaces. So that, it is not ‘x’ that is dependent on ‘i’ but it is ‘ix’ the interface implemented by ‘x’ that depends on ‘i’ hence we can change the dependency from both ends. It is no more class dependent on an interface but an interface dependent on an interface. This ‘high loosely coupling’ is feasible through interface dependency injection.
3) Interface
In this case, an interface is dependent on another interface which lets the objects independent from any logical relation between each other.
History
- 1st May, 2008: Initial post