Why are IOC containers unnecessary with dynamic languages

IoC provides a mechanism to break the coupling you get when an object calls ‘new’ on another class. This coupling ties the calling object with the instantiated implementation of whatever interface it implements.

In static languages when you reference a class by name (to call new on it), there is no ambiguity. This is a tight coupling to a specific class.

In dynamic languages calling new X is a placeholder for “instantiate whatever class is defined as X at the point of execution”. This is a looser coupling, as it’s only coupled to the name X.

This subtle difference means that in a dynamic language you can usually change what X is, so the decision as to which class is instantiated is still modifiable outside of the calling class.

However, personally I find there are two advantages to IoC that I don’t get by relying on the dynamic language to allow injection.

One of the side effects of passing dependencies in through constructors is that you end up with “building block” classes that are very decoupled, reusable and easy to test. They have no idea what context they are intended to be used in, so you can reuse them all over the place.

The other result is having explicit code to do the wiring. Done correctly this cleanly represents the structure of your application and it’s decomposition into subsystems and life-cycles. This makes people explicitly decide which life-cycle or subsystem they want to associate their class with (when writing the wiring code), and concentrate on the behavior of the object when writing the class.

Like Jörg W Mittag said.. “Those tools are unnecessary, the design principles aren’t.” I believe they are unnecessary, but done right, still valuable.

Leave a Comment