Last active
April 25, 2020 00:49
-
-
Save scally/ae57968b2b42c6d4d979a464a379186a to your computer and use it in GitHub Desktop.
Please don't use dependency injection frameworks in modern Typescript/Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
If you are using dependency injection in Typescript/Javascript under the pretense that | |
you are doing anything other than overengineering and making your life and your team's life | |
harder, please read this. | |
*/ | |
// The code below doesn't care what `logger` is, only that it exports `log`! | |
// This creates a test seam / interface behind which you can replace it with ANYTHING! | |
// You only care that the thing being exported has a `log` function! | |
import { log } from './logger' | |
// The code below doesn't care what `db` is, only that it exports `exec`! | |
import { exec } from './db' | |
const saveRecord = () => { | |
exec("update widgets etc...") | |
log("did the thing") | |
} | |
// some things `exec` could be... | |
// export const exec = (sql) => { | |
// doARealDbThing(sql) | |
// } | |
// export const exec = (sql) => { | |
// doAMockedDbThing(sql) | |
// } | |
// export const exec = (sql) => { | |
// if (someCondition) { | |
// doARealDbThing(sql) | |
// } else { | |
// doAMockedDbThing(sql) | |
// } | |
// } | |
// jest.mock('./exec) // Hey, look, Jest does this too without constuctor-injection | |
/* | |
Note that I never: | |
* Pushed all dependencies in via constructor | |
* Used a class as a module container (or at all) | |
* Had to create several layers of dependency injection configuration | |
* Imported any exotic dependencies to replace ES6 import/export | |
Typescript/Javascript isn't Java or C#! | |
Angular and NestJS and anything else doing DI in javascript/typescript is unnecessary. | |
They are reinventing an additional module system on top of ES6's module system. | |
This might have been more helpful back before es2015, but it's been 6 years; it's time to let it go. | |
Programming is hard enough without making things harder for no real gain. | |
Pass it on. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment