Skip to main content

Dependency injection pattern explained like you're 5

Jose CerrejonLess than 1 minuteDeveloper

Dependency injection pattern explained like you're 5

dep injection
Why did I choose that example for explaining dependency injection?. Generated with AI.

Today I was asked this question in a job interview, and I found it to be a very simple way to explain dependency injection. Here's the explanation I gave, a bit more detailed (I'm sure it blew my interviewer's mind):

Imagine you're preparing a turkey for a special dinner. The turkey needs to be stuffed to have a delicious flavor. You could put the stuffing directly inside the turkey, but that would limit your options. If you wanted to change the stuffing, you would have to take out the entire turkey and start over.

Instead, you decide to use a bag for the stuffing. You put the stuffing in the bag and then put the bag inside the turkey. Now, if you ever want to change the stuffing, you can simply take out the bag and put in a new one with a different stuffing. You don't need to dismantle the whole turkey.

In programming, "dependency injection" is like using the bag for the stuffing. Instead of putting the dependencies (the stuffing) directly in your code (the turkey), you put them in something that can be easily changed (the bag). This makes your code more flexible and easier to change or reuse in the future.