DIP vs DI vs IoC

There can be a lot of confusion at times about these terms. Part of the reason for this I believe is that there are a lot of different descriptions floating around – just google. Also all 3 are very much related and their names and functions overlap. I guess you are also getting deep into the belly of the beast so there is a little complexity there.

Here is what they mean to me.

Inversion of Control is a generic term, meaning rather than having the application call the framework, the framework calls into the application. To my mind that is all it means really, perhaps the difficulty is visualising this in your head. Part of this might be because there are so many different ways – this is why you can be forgiven for sticking to DI. None the less, IoC is a collection of different solutions to the same problem, including Dependency Injection (DI), Factory Pattern, Strategy Pattern, Service Locator and perhaps others.

Service locator is a little controversial and considered to be an anti pattern by some – I don't know about Strategy Pattern.

Dependency Injection simply means that a class has deferred and is a type of IoC. Responsibility of obtaining or providing its own dependencies; instead that responsibility resides with whatever wants to create an instance (there might be a better description out there than this). This can be constructor, interface or property injection. We tend to do a lot of constructor injection. Interface injection leads us to the DIP.

The Dependency Inversion Principle is about abstractions and has two parts (borrowed from elsewhere):

  1. High-level modules should not depend on low-level modules. Both should depend on abstractions.
  2. Abstractions should not depend upon details. Details should depend upon abstractions.

DIP is more of a natural fit with static languages but in my opinion is often desirable irregardless. DIP does add complexity in itself though and might not be worth it in smaller scale applications (micro-services) in organisations or legacy code / code that does not change a lot.

DIP seems to be considered less desirable and actually stirs strong, (I would say unnecessary) feeling and emotion in Node. This is because Node is dynamic (difficult to implement – is easier with Typecript) and projects tend to lean towards Microservices (not worth the complexity).

Can go deeper into the principle here: https://martinfowler.com/articles/dipInTheWild.html

A final point is that IoC Containers such as (DryIoc above) tend to facilitate all 3 and looser coupling of your code. As I said before, it can be a confusing topic of conversation but I think is a great thing for a few people to discuss together.

Leave a Reply

Your email address will not be published. Required fields are marked *