Sobes.tech
Junior — Middle

Can you give an example of implementing the dependency inversion principle in software design?

sobes.tech AI

Answer from AI

The Dependency Inversion Principle states that high-level modules should not depend on low-level modules, but both should depend on abstractions (interfaces). In Node.js, this can be implemented through Dependency Injection.

Example:

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

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

// High-level module
class UserService {
  constructor(logger) {
    this.logger = logger; // dependency via constructor
  }

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

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

Here, UserService depends not on a specific ConsoleLogger, but on the abstraction Logger, which facilitates testing and replacing the implementation.

Can you give an example of implementing the… - sobes.tech