Dependency injection is when one part of a system gives another part exactly what it needs to work, instead of that part having to find it on its own.
Imagine you're building a sandwich. Normally, the bread has to go out and get the peanut butter by itself, that’s hard work! But with dependency injection, someone else brings the peanut butter straight to the bread. The bread just needs to know where to put it, no running around needed!
How It Works in Real Life
Why It's Useful
Without dependency injection, parts of a system have to search for what they need, like the bread searching for peanut butter. With it, everything gets what it needs quickly and clearly. This makes things easier to fix or change later, just like how you can swap out one type of peanut butter for another without changing the bread!
Examples
- Imagine you're building a robot. Instead of hardwiring the robot's brain to its sensors, you plug them together, making it easier to swap brains or sensors later.
- It’s like having a coffee machine that can use any type of coffee bean, you don’t have to change the whole machine just for a new bean.
- A chef who uses pre-made sauces instead of cooking everything from scratch, saving time and making dishes more interchangeable.
Ask a question
See also
- How Does Immutability - Computerphile Work?
- How Does Event-Driven Architecture: Explained in 7 Minutes! Work?
- How Does Python break continue pass ⛔ Work?
- How Recursion Works?
- How Does The Benefits of Functional Architectures | Systems Engineering, Part 3 Work?