Optional DI in JavaScript

This was something that eluded me for a while since I went back to using global variables, and I kept thinking it was an either-or thing. Do I continue to use global variables, or write testable code. While attempting to solve some other issue, I accidentally discovered a technique that appears to be working pretty well in making code that uses global variables testable, so I’ll share it with you here.

Dependency injection is a design pattern that normally warrants a lengthy explanation in the context of statically typed OOP languages. In this article, I will show a simple version of the DI pattern that pertains to applications that use module-scope variables as module/system state and not the class-based OOP. In combination with default parameter values, we can implement a pattern I call “optional DI”. The result is a code that exhibits the characteristics of both tight and loose coupling depending on its usage.

Website