Sobes.tech
Junior — Middle

Can you explain the differences between the principles of Dependency Inversion and Dependency Injection and how they are related?

sobes.tech AI

Answer from AI

Dependency Inversion Principle (DIP) — is one of the SOLID principles, which states that:

  • High-level modules should not depend on low-level modules directly.
  • Both should depend on abstractions (interfaces or abstract classes).
  • Abstractions should not depend on details, but details should depend on abstractions.

Dependency Injection (DI) — is a pattern or technique that implements the inversion of dependencies principle in practice. DI means that dependencies (objects needed by a class) are passed to it from outside, rather than created inside the class.

The relationship between them:

  • DIP is a design principle that defines how to build architecture.
  • DI is a way to implement this principle, allowing easy replacement of dependencies and improving testability.

Example in Node.js using DI:

// Abstraction
class Logger {
  log(message) {
    throw new Error('Not implemented');
  }
}

// Concrete implementation
class ConsoleLogger extends Logger {
  log(message) {
    console.log(message);
  }
}

// Class depending on abstraction
class UserService {
  constructor(logger) {
    this.logger = logger; // dependency is injected from outside
  }

  createUser(name) {
    // user creation logic
    this.logger.log(`User ${name} created.`);
  }
}

const logger = new ConsoleLogger();
const userService = new UserService(logger);
userService.createUser('Alice');

Here, UserService depends on the Logger abstraction, and the concrete implementation is passed through the constructor — this is an example of Dependency Injection implementing the Dependency Inversion Principle.