Inversion of Control
Dependency Inversion
class JSON { /*...*/ }
class DbQueryBuilder { /*...*/ }
class ApiController {
getUsers() {
const db = new DbQueryBuilder();
const users = db.query("SELECT * FROM USER;");
return JSON.stringify(users);
}
}
const jsonFormatter = JSON;
class DbQueryBuilder { /*...*/ }
const db = new DbQueryBuilder();
class ApiController {
getUsers() {
const users = db.query("SELECT * FROM USER;");
return jsonFormatter.stringify(users);
}
}
class XMLFormatter { /*...*/ }
const jsonFormatter = JSON;
const xmlFormatter = new XMLFormatter();
class DbQueryBuilder { /*...*/ }
const db = new DbQueryBuilder();
class ApiControllerJSON {
getUsers() {
const users = db.query("SELECT * FROM USER;");
return jsonFormatter.stringify(users);
}
}
class ApiControllerXML {
getUsers() {
const users = db.query("SELECT * FROM USER;");
return xmlFormatter.buildStringFrom(users);
}
}
// class ApiControllerJSON {
return jsonFormatter.stringify(users);
// class ApiControllerXML {
return xmlFormatter.buildStringFrom(users);
const formatter = YamlFormatter // will this work?
class JSON { /*...*/ }
class DbQueryBuilder { /*...*/ }
class ApiController {
getUsers() {
const db = new DbQueryBuilder();
const users = db.query("SELECT * FROM USER;");
return JSON.stringify(users);
}
}
{
"name": "one-time-secret",
...
"scripts": {
"test": "TZ=UTC jest spec",
...
},
"engines": {
"node": ">=10.0.0 <11.0.0"
},
"description": "Store secrets for one-time-access.",
"dependencies": {
"@types/winston-syslog": "^1.0.0",
"typescript": "^3.2.2",
...
{
"name": "one-time-secret",
...
"scripts": {
"test": "TZ=UTC jest spec",
...
},
"engines": {
"node": ">=10.0.0 <11.0.0"
},
"description": "Store secrets for one-time-access.",
"dependencies": {
"@types/winston-syslog": "^1.0.0",
"typescript": "^3.2.2",
...
class JSON { /*...*/ }
class DbQueryBuilder { /*...*/ }
class ApiController {
constructor(db) {
this.db = db
}
getUsers() {
const users = this.db.query("SELECT * FROM USER;");
return JSON.stringify(users);
}
}
function main() {
const db = new DbQueryBuilder();
const apiCtrl = new ApiController($db);
return apiCtrl.getUsers();
}
class ApiController {
constructor(db) {
this.db = db
}
}
const db = new DbQueryBuilder();
const apiCtrl = new ApiController($db);
class ApiController {
attachDatabase(db) {
this.db = db
}
}
const db = new DbQueryBuilder();
const apiCtrl = new ApiController();
apiCtrl.attachDatabase(db)
class ApiController {}
const db = new DbQueryBuilder();
const apiCtrl = new ApiController();
apiCtrl.db = db;