Sobes.tech
Senior

What is the key difference between Dependency Inversion and Dependency Injection?

sobes.tech AI

Answer from AI

Dependency Inversion (principle of dependency inversion) is one of the 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.

Dependency Injection is a specific pattern or technique implementing the Dependency Inversion principle. It is a way of passing dependencies (objects) into a class or function from outside, rather than creating them inside.

In other words:

  • Dependency Inversion is a concept or design principle.
  • Dependency Injection is a way to implement this concept, where dependencies are passed from outside.

Example in Go:

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

// Concrete implementation
 type EmailNotifier struct {}

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

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

// 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, the Dependency Inversion principle is maintained through dependence on the Notifier interface, and Dependency Injection is achieved by passing a specific implementation, EmailNotifier, into the UserService constructor.

What is the key difference between Dependency… - sobes.tech