Tell me about the Dependency Inversion pattern (the last SOLID principle) and about composition.
sobes.tech AI
Answer from AI
The Dependency Inversion Principle (DIP) is one of the five SOLID principles, which states:
- 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 concrete implementations, we work through interfaces or abstract classes. This increases flexibility, makes testing easier, and supports code maintenance.
Example in Go:
// Abstraction
type Notifier interface {
Notify(message string)
}
// Concrete implementation
type EmailNotifier struct {}
func (e EmailNotifier) Notify(message string) {
fmt.Println("Email sent:", message)
}
// High-level module
func SendAlert(n Notifier, msg string) {
n.Notify(msg)
}
// Usage
email := EmailNotifier{}
SendAlert(email, "System down!")
Composition is a way of building complex objects from simple ones by including one object within another. Unlike inheritance, composition allows flexible behavior combination without a rigid hierarchy.
For example, instead of creating a "Square" class inheriting from "Rectangle", you can create a structure that contains a "Rectangle" field and extends its functionality.
Composition is often used together with DIP to inject dependencies through struct fields or function parameters, rather than through inheritance.