Junior — Middle
What are the advantages of applying dependency injection in real projects?
sobes.tech AI
Answer from AI
Dependency Injection (DI) helps make code more modular and testable. In real projects, it provides several advantages:
- Improved testability: dependencies can be easily replaced with mocks or stubs during testing.
- Loose coupling of components: classes and modules do not create dependencies themselves but receive them from outside, making it easier to replace and update components.
- Increased reusability: components become more versatile as they do not depend on specific implementations.
- Simplified dependency management: centralized management of dependencies simplifies configuration and scaling of the application.
Example in Node.js using a simple DI container:
class Logger {
log(message) {
console.log(message);
}
}
class UserService {
constructor(logger) {
this.logger = logger;
}
createUser(name) {
this.logger.log(`User ${name} created`);
}
}
const logger = new Logger();
const userService = new UserService(logger);
userService.createUser('Alice');
Here, UserService does not create Logger itself but receives it from outside, which simplifies replacing the logger, for example, with a test logger.