Are Dependency Injection Frameworks Useful in Dynamically Typed Languages

dependency-injectiondynamic-typingframeworks

A while ago I was investigating dependency injection frameworks for a project I'm working on in Python (part of a full-time job, moderately large and complex). I found some projects such as dependency_injector that look interesting but many of them look somewhat abandoned. The examples from those projects make dependency injection frameworks appear to use the same amount of code (or more) than simply putting a dependency between two classes/objects in the first place.

I did some more reading and it looks like a similar situation has happened with DI frameworks in Ruby as well; it turned out to be easier to use dependencies directly than to code with some frameworks.

Is it useful to use DI frameworks in languages that dynamically typed? I know such frameworks are often used with statically typed languages such as Java or C#. What about dynamic languages like Python or Ruby?

Best Answer

The main benefit of a DI framework is that it moves construction into a different language (xml, json, whatever). This enforces not mixing construction code with behavior code. It's a poor programming team that needs that, but it works.

DI doesn't require a framework. Simply not mixing these responsibilities is enough. Construction also doesn't have to be done procedurally in main. You're entitled to use every feature of the language. Creational patterns have come a long way. It's when you mix use and construction that you find yourself hard coding dependencies with no way to override.

Good defaults are extremely easy to override as needed in a language with named parameters. This makes a much bigger impact to DI then dynamic typing. DI works well in dynamic languages. Even prototypical languages can benefit. That's because DI's is more then just mechanical. It actually makes code easier to read, if you're doing it right.

I recommend everyone learn how to do DI without a framework before trying to evaluate what any one framework provides. Some are useful even when you have the skill to live without them. Some are just something else trying to convince you to become dependent on it. Use with caution.

Related Topic