Dependency Injection
Why should I care?
- You'll be seeing it a lot in Sparkles
- It makes the code more testable
- Decreases coupling
In plain English
- Give me the stuff I need, instead of having me create it myself
- Passing dependencies (like objects) as a parameter
ELI5
- When you are hungry, you have a dependency on food.
- Without DI, you would go to the kitchen and make yourself dinner
- With DI, you would call the restaurant and get the food delivered
Example
- Warrior class
- Has a sword created inside class
- What happens if we want to arm our warrior with a different weapon?
- Tightly coupled
Example - DI
- Warrior class
- Has a weapon injected
- Now it is easy to give our warrior different weapons
Why is this useful?
- Testing!
- What if our weapon was actually a call to a database, or an API
- If we want to test our warrior class, every time we run the test we are hoping that the API is still online.
- We also assume that the API does not change the return value
Testability
- Now we inject the API
- This allows us to mock and stub the API
- To hard code the return value
- It means we aren't testing against a depency
- Our unit test is truly testing a single unit
Dependency Injection
By Tom Dane
Dependency Injection
- 328