DEV Community

Cover image for Understanding Dependency Injection with Chicken Cutlets
Raisa Gandi Putri
Raisa Gandi Putri

Posted on

Understanding Dependency Injection with Chicken Cutlets

The Backstory

So I started a new job. I'm learning a new programming language and framework. And my brain is fried.

As a form of stress relief, I spent the entirety of my lunch breaks obsessively watching Nigella Lawson's cooking shows - without the intention of following her recipes, of course! During this past week, I also needed to understand the concept of dependency injection to complete my day-to-day work. By doing both things at the same time, I ended up understanding dependency injection by frying my brain... and some chicken cutlets.

Let's Get Cooking

At a minimum, I'll need:

  • 2 chicken escalopes
  • 1 egg

Well, I could get these ingredients by farming some chickens and harvesting eggs in my backyard. But, what if I suddenly decided to cook with another breed of chickens? I can't just trade my whole flock of chickens for another! That would be a disaster!

chicken farm

Instead of farming my own chickens, why don't I buy some chickens from the farmer's market? I'm now free to switch between chicken breeds whenever I like! Plus, I don't have the hassle of rearing chickens in my nonexistent backyard.

In the programming world, this concept is called inversion of control, or IoC for short. I don't have control over growing my own chickens, because I hate the idea of opening a chicken farm. Instead, I'm delegating that task to other farmers, so all I have to do is buy their produce. I make sure to only do one thing: cook the chickens.

Dependency injection, in this example, refers to the act of buying chicken escalopes from the farmer's market and then "injecting" that ready-made ingredient into our cooking, instead of making it from scratch.

And that's it! Now, it's time to eat.

Acknowledgements

Top comments (2)

Collapse
 
spiritupbro profile image
spiritupbro

super keren

Collapse
 
raisagp profile image
Raisa Gandi Putri

Terima kasih!