Sobes.tech
Junior — Middle

Explain the principle of dependency injection in software and how it is used to improve code modularity.

sobes.tech AI

Answer from AI

Dependency Injection (DI) is a design principle where an object receives its dependencies (such as other objects or services) from outside, rather than creating them itself. This increases the modularity and testability of the code, as components become loosely coupled and easily replaceable.

In Node.js, DI is often implemented by passing dependencies into constructors or functions, or using special libraries (for example, InversifyJS).

An example of simple dependency injection:

class Logger {
  log(message) {
    console.log(message);
  }
}

class UserService {
  constructor(logger) {
    this.logger = logger; // dependency is passed from outside
  }

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

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

This approach makes it easy to replace Logger with another, for example, for testing or changing the logging method.