DEV Community

Discussion on: The Node.js way - DI vs Module Require?!

Collapse
 
fergek profile image
Fernando Gekdyszman

A common misunderstanding is to say DI and be actually referring to IoC. Dependency injection is one of the ways to get inversion of control pattern applied on your app. Implementation details are easy: You receive already constructed interfaced instances as parameters in your constructors. Inversion of control is the pattern that we all know is good to have and it means resolving dependencies in some other place that is not the piece of code that actually uses the dependant component, this is how you low down your coupling (my favorite way to approach IoC is Property Resolution, but that's another discussion I'd guess).

I see NPM modules as a way to add plumbing code or frameworks (as your router, your MQTT or eventually a dependency injector 😉).

If you get to implement n-tiers on your project (e.g. controllers, builders, models, services, etc) IoC will be beneficial and will allow you to change implementations depending on the context (the typical example is mocking for unit tests and real implementations got production).

If what you are suggesting is to package your code in some sort of local npm registry and requiring them (removing the literals) that's something I'd like to hear how it ends.

Thanks ☺

Collapse
 
imthedeveloper profile image
ImTheDeveloper

To follow up on these comments I've spent the last couple of days working through my code, refactoring my structure and in general just giving different methods a try. I've actually found a nice middle ground between injecting some dependencies to ensure loose coupling and easy testability vs hard locking things together with directly required modules.

Overall quite happy with the route I've gone. I can imagine in the future if my App were to grow and grow the benefits of an IoC and registering all of the dependencies in a central store.

For anyone looking for a good guide on all of this I forgot I had actually got a copy of "Node.js design patterns" which has a chapter specifically discussing all of this topic named "Wiring Modules". I've also noticed google and other searches react well to the same phrase.