Junior — Middle
Can you explain the principle of dependency inversion and how it is applied in software system design?
sobes.tech AI
Answer from AI
The Dependency Inversion Principle (DIP) is one of the five SOLID principles, which states that:
- High-level modules should not depend on low-level modules. Both should depend on abstractions.
- Abstractions should not depend on details. Details should depend on abstractions.
This means that instead of directly creating and using specific classes or modules, we work through interfaces or abstract classes. This increases flexibility and makes testing and maintaining the code easier.
In software system design, this is applied as follows:
- Components depend on interfaces, not on concrete implementations.
- Implementations can be changed without modifying the code that uses them.
- It allows dependency injection through constructors, setters, or factories.
Example in Node.js:
// 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;
}
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, not on the specific ConsoleLogger. This allows easy replacement of the logger with another, for example, for file logging, without changing UserService.