loading...

re: Dependency Injection in JavaScript 101 VIEW POST

FULL DISCUSSION
 

Some say that an IoC container isn't necessary in javascript since it already has a module system. I don't exactly agree with those people because when you use a IoC container the functions/classes that you make have a diferent "design". Still, the container does the job of a module system, which make it seem like is a bit redundant.

 

I'll start by saying that this is a great introduction to dependency injection for those who understand Javascript, but I do agree with those who say an IoC container isn't necessary. In my personal experience, it added unneeded complexity in files where implementations were instantiated and registered. It also threw off other Javascript developers as it's not exactly a widely used paradigm within the Javascript development scene. Below I'll briefly address some of the initial motivations behind the usage of an IoC container in Javascript, and attempt to make a case that shows it may not be helpful when building Javascript applications.

To address each point:

1.) "If you attempt break each component (wheel, piston, etc.) into its own file, you will have to ensure everything is included in the right order for it to work"

I'm not sure this is true in a system like Javascript where the convention is to import all dependencies at the top of each file.

2.)"The tight coupling means it's not possible to have a developer working on engines while another is working on pistons. "

Again, a module system can easily allow something akin to a mock to be passed in.

3.)"The components create their own dependencies so there is no way to effectively test them without dependencies."

At least on the server side there are testing frameworks like "jest" that allow you to change the default behavior of require statements to retrieve a mock instead of actual implementations.

 

Absolutely. Your point is a good one because JavaScript doesn't adhere to the same rules more strictly typed, object-oriented languages do. Angular chose the approach of injecting dependencies but JavaScript (and TypeScript, for that matter) have better support for aspect-oriented programming in my opinion. To illustrate, for C# if I want a logger the common way to do this is to inject it. I pass my logger instance into the component and then I can swap it out as needed. I can't take a static dependency on Logger.Something because then I've have a hard-coded reliance on Logger. In JavaScript, however, I can just call to Logger.Something because "Logger" is changeable depending on what module I load. I could probably be convinced that in the JavaScript world, we can talk about dependencies strictly by discussing modules and not have to bring IoC/DI into the picture at all unless we're using a framework that takes that approach. Might write another article to expand on that in more detail, thanks for taking the time to respond!

Code of Conduct Report abuse