Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dependency inversion principle in JavaScript, mistake or my misunderstanding?

I found this article about DIP in JS and I have a big question about it.

class Database {
  constructor() {
    this.items = [];
  }

  add(item) {
    this.items.push(item);
  }

  get(id) {
    return this.items.find((item) => item.id === id);
  }
}

class DatabaseInterface {
  constructor(database) {
    this.database = database;
  }

  add(item) {
    this.database.add(item);
  }

  get(id) {
    return this.database.get(id);
  }
}

class UserController {
  constructor(databaseInterface) {
    this.databaseInterface = databaseInterface;
  }

  createUser(name) {
    const user = { id: Date.now(), name };
    this.databaseInterface.add(user);
    return user;
  }

  getUser(id) {
    return this.databaseInterface.get(id);
  }
}

above code is explained as:

In this fixed example, we have created an interface for the Database class, called DatabaseInterface. The UserController class now depends on the DatabaseInterface abstraction, which is implemented by the Database class. By using an abstraction, we have inverted the dependency, and now the low-level Database class depends on the high-level DatabaseInterface abstraction.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I don’t understand how the Database class depends on DatabaseInterface. I think the opposite – that DatabaseInterface depends on Database, because DatabaseInterface uses Database. Am I right?

>Solution :

You are correct, strictly speaking the Database class does not depend on the DatabaseInterface class, but it needs to implement it. I think what the author is getting at is that there is a requirement for Database to implement the methods in DatabaseInterface and is calling that a dependency.

The DatabaseInterface class depends on a database that implements add() and get(). This could be useful because you could define another class Foo that depends on DatabaseInterface, but Foo would not depend on the specific implementation of DatabaseInterface.database because you could provide different implementations of database to DatabaseInterface without changing Foo.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading