- You'll be seeing it a lot in Sparkles
- It makes the code more testable
- Decreases coupling
- Give me the stuff I need, instead of having me create it myself
- Passing dependencies (like objects) as a parameter
- 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
- Warrior class
- Has a sword created inside class
- What happens if we want to arm our warrior with a different weapon?
- Tightly coupled
- Warrior class
- Has a weapon injected
- Now it is easy to give our warrior different weapons
- 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
- 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
Made with Slides.com