Today I Learned - Rocky Kev

TIL ELI5 for Dependency Injection

POSTED ON:

TAGS:

What is Dependency Injection?

tl;dr:

Via PhonicUK's reddit comment

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:

TIL Indirection and Swallowing the error

Op shared a tryCatch util that is problematic.

TIL reusing variables

Do not reuse variables. Do not double define variables that represent the same thing.

TIL about semaphores

A semaphore limits access to a resource to some number of consumers. Any new requests for the resource will get stalled until later, eventually to be handled.