Sobes.tech
Senior

How does Dependency Inversion differ from Dependency Injection?

sobes.tech AI

Answer from AI

Dependency Inversion Principle (DIP) is one of the five SOLID principles, which states that high-level modules should not depend on low-level modules directly, but both should depend on abstractions (interfaces). Also, abstractions should not depend on details, but details should depend on abstractions.

Dependency Injection (DI) is a specific pattern or technique for implementing the dependency inversion principle, where dependencies (objects, services) are passed into a class or function from outside, rather than being created inside.

In simpler terms:

  • DIP is a design principle aimed at reducing coupling through the use of abstractions.
  • DI is a way to implement this principle, where dependencies are injected from outside (via constructor, setter, or interface).

Example in Go:

// Abstraction
 type Notifier interface {
     Notify(message string)
 }

// Detail implementing the interface
 type EmailNotifier struct {}

 func (e EmailNotifier) Notify(message string) {
     fmt.Println("Sending email:", message)
 }

// High-level module depends on abstraction
 type UserService struct {
     notifier Notifier
 }

// Dependency Injection via constructor
 func NewUserService(n Notifier) *UserService {
     return &UserService{notifier: n}
 }

 func (s *UserService) RegisterUser(name string) {
     // registration logic
     s.notifier.Notify("User registered: " + name)
 }

Here, DIP is represented by UserService depending on the Notifier interface, and DI is demonstrated by passing EmailNotifier into UserService from outside.

How does Dependency Inversion differ from Dependency… - sobes.tech