TIL ELI5 for Dependency Injection
POSTED ON:
TAGS: programming eli5
What is Dependency Injection?
tl;dr:
- It's about breaking the code into smaller fully-functional pieces
- It makes it easier to test in isolation
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 connecton 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.
Related TILs
Tagged: programming