Nicolas FROIDURE
Web Platform Architect
Why and how?
Frontend / Backend developers
Data scientists
Embedded software engineers
The Dependency Injection pattern aims to provide the states some code depends on from some external code.
That way, the actual code is completely decoupled from its own dependencies implementation / initialization.
Dependency Injection on Wikipedia
// With Classes
class User {
constructor(db, log) {
this.db = db;
this.log = log;
}
async delete() {
const result = await this.db.query('DELETE FROM users WHERE id = $id', { id });
if (result.deletedRows) {
this.log(`User ${id} has been deleted!`);
}
}
}
// With functions
async function deleteUser(db, log, id) {
const result = await db.query('DELETE FROM users WHERE id = $id', { id });
if (result.deletedRows) {
log(`User ${id} has been deleted!`);
}
}
The Dependency Injection pattern is the only one you will never regret to implement.
If you do it with OOP do not blame DI.
Creating a simple CLI app from scratch
The Dependency Injection banana without the gorilla nor the jungle and the rest of the world.
If you really want the gorilla, the jungle and the rest of the world, you may like to use the container-ioc library or the Angular and Nest frameworks that integrates their own DI systems. They fully rely on OOP and decorators fancy.
Source: jsarch
Summary of changes done during the talk:
By Nicolas FROIDURE
Why and how to use the dependency injection design pattern with JavaScript.