Junior — Middle
Could you explain the dependency injection mechanism and its role in ensuring code flexibility?
sobes.tech AI
Answer from AI
Dependency Injection (DI) is a design pattern in which an object receives its dependencies from outside rather than creating them itself. This increases the flexibility and testability of the code, as dependencies can be easily replaced or substituted, for example, with mock objects during testing.
In Node.js, this is often implemented by passing dependencies into constructors or functions:
class UserService {
constructor(userRepository) {
this.userRepository = userRepository;
}
getUser(id) {
return this.userRepository.findById(id);
}
}
// When creating an object, pass a specific implementation
const userRepository = new UserRepository();
const userService = new UserService(userRepository);
This approach allows for easy swapping of the userRepository implementation without changing UserService, making the code more flexible and maintainable.