DEV Community

Discussion on: Explain Dependency Injection (DI) like I am five.

Collapse
 
ermiyaeskandary profile image
Ermiya Eskandary

Hey Mirza, literally have been in the same boat as you
Hope this helps!

In a nutshell, what it means is that any given piece of code you write should be provided everything it needs to do its job, instead of creating things for itself. So say I'm writing a forum, and I'm specifically writing the code that adds a new user record to the database and sends them an email to confirm their registration. If I used dependency injection, that piece of code would be given a data model/database connection to work with (instead of creating a new instance of one) and a external class with a pre-defined interface to send email instead of creating an SMTP client object. The reason you do this is it makes the code much easier to test in isolation. So I can replace the class instance for sending emails with one that just checks one is sent to a know address to help with unit tests. It also means that components are easier to replace later on because you can just swap out what objects you give it with objects of a different class with a matching interface.

Let me know if you need any more help :)