Hacker News new | ask | show | jobs
by wcoenen 4883 days ago
It turns out that there is a problem with instantiating everything manually in main if you have a lot of components: it becomes non-trivial to figure out the order of instantiation.

This problem will typically surface whenever you add a dependency between existing components. If the dependency is currently instantiated after the changed component, it will have to be moved up so it is instantiated earlier. But then it turns out the dependencies of that component also need to be moved up etc.

To deal with this you then have to calculate a "dependency rank" for each component (i.e. 0 for components without dependencies, and x+1 for components where the max rank among the dependencies is x) just to figure out a new order that works.

This problem doesn't exist if you use a dependency injection container with configuration in code, because the order of component registration is not important.

1 comments

Yeah, what you'd end up recreating is a directed graph of dependencies, and make it needlessly fragile.

You don't need the big machinery for smaller projects, though. What I end up doing in Python is having builder methods in __init__.py which can instantiate objects from the package (possibly instantiating objects from sub-packages in the process), with any dependency not in the package or sub-packages being a parameter. You get some granularity in your dependency injection, you avoid magic and you don't need to use the builder methods if you don't want to. It may not scale to large class hierarchies, but for mid-size projects it's fine.