I have a class that depends on another class. Rather that instantiate the depended upon class, I require it be passed in in the one and only constructor. Does this effectively inject said dependency?
So confused!
I have a class that depends on another class. Rather that instantiate the depended upon class, I require it be passed in in the one and only constructor. Does this effectively inject said dependency?
So confused!
In a sense yes. Maybe this will help you.
Quoted from the other Stack Overflow Response:
The best definition I found so far is one by James Shore:
"Dependency Injection" is a 25-dollar term for a 5-cent concept. [...] Dependency injection means giving an object its instance
variables. [...].
There is an article by Martin Fowler that may prove useful too.
You are going on right way. A good start. There is a nice article by Martin Fowler on it.
But the key is looking for the basic reason why we are doing this way. Basically we have to separate the configuration of the objects from the use of it. then it will give you the flexibility to change depending on the business rules.
For example if you have a Employee class and Employee Class have a CalculateBonus method and that method using a BonusCalculator Class to calculate bonus. If a Company Class use Employee.CalculateBonus for bonus calculation then it is the responsibility of the Company Class to initiate the BonusCalculator Class and pass to Employee class via a method,property or via the constructor .
The pay days, leave etc comes from Employ Class and BonusCalculator is external to the Employ Class so we are delegating the initializing of BonusCalculator responsibility to the calling class.
This way tomorrow the type of BonusCalculator change it would not affect the Employee Class.
Hope this helped you to understand the concept more clearly.