Hacker News new | past | comments | ask | show | jobs | submit login

How do module systems make IOC and DI obsolete? What's the argument?



I read that differently, like:

Some people thought ioc and di wouldn't be needed with module systems but we've now mostly realized...

Typescript at least is used with injection in Angular (and it is really nice.)


I meant why people thought it wouldn't be needed. For me they are different things so trying to understand the argument.


Well one way you avoid the need for DI is that if you are only using DI to allow you to swap out real collaborators for fakes in your tests ... to instead simply mock module imports in your tests, (to mock those collaborators). This is common with Jest in the React world. And it's easy with a good module system.

I'm building 2 large apps, with no DI, and using this approach (Jest) and I never want to use DI again. I hated the DI system in Angular 2+


Maybe I misunderstand DI when I want to have a "stateful" module, let's say a class that I export that requires some config input (think Database). I initiate it in index.js or something and then just pass it in the constructor in every other class that needs to use it. What is this called? If it's DI, how do I do that with modules only?

The reason I'm asking is because sometimes I want that dependency 10 steps deep and if the 10th class wants to use it I need to pass it through all other 10 classes. Creates a lot of bloat.


Yes, that is DI too, you can think of it something like 'injecting a shared singleton service', and yes the passing into a constructor is the basic approach you might call 'manual DI'.

And yep modules can let you avoid the need for that, you can share singletons by exporting an instance from a module, and then if you import that module from 2 other modules, both will get the same instance [1].

Though tbh that still feels a bit gross to me :) There are other solutions (like the context API [2] in React for passing some data/instance to multiple components at different levels in your 'component tree').

[1] https://k94n.com/es6-modules-single-instance-pattern [2] https://reactjs.org/docs/context.html


Thanks a lot! Learned a bunch from this single comment. :)


No probs :)

DI is something I battled to understand for a while!




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: