Sobes.tech
Middle+

What is the difference between Dependency Inversion and Dependency Injection?

sobes.tech AI

Answer from AI

Dependency Inversion Principle (DIP) is a design principle that 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 principle aims to reduce coupling and increase flexibility of the code.

Dependency Injection (DI) is a specific pattern or technique for implementing DIP, where dependencies (objects, services) are passed into a class from outside rather than created inside it.

Example in Go:

// Interface (abstraction)
type Notifier interface {
    Notify(message string)
}

// Concrete implementation
 type EmailNotifier struct {}
 func (e EmailNotifier) Notify(message string) {
     fmt.Println("Sending email:", message)
 }

// Class that depends on abstraction
 type UserService struct {
     notifier Notifier
 }

// Constructor with dependency injection
 func NewUserService(n Notifier) *UserService {
     return &UserService{notifier: n}
 }

func (u *UserService) SendWelcome() {
     u.notifier.Notify("Welcome!")
}

Here, DIP is the principle we follow, and DI is the way to pass the dependency (Notifier) into UserService from outside.