Sobes.tech
Junior — Middle

How is the dependency inversion principle implemented in Go compared to object-oriented programming languages?

sobes.tech AI

Answer from AI

In Go, the principle of dependency inversion is implemented not through classes and inheritance, as in object-oriented languages, but through interfaces and composition.

Instead of creating and managing dependencies within an object, dependencies are passed in as interfaces from outside (via function parameters or constructors). This allows for easy replacement of implementations and simplifies testing.

Example:

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

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

// Struct depending on Notifier
type UserService struct {
    notifier Notifier
}

func NewUserService(n Notifier) *UserService {
    return &UserService{notifier: n}
}

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

// Usage
func main() {
    emailNotifier := EmailNotifier{}
    service := NewUserService(emailNotifier)
    service.RegisterUser("Alice")
}

Thus, Go uses interfaces and composition to achieve dependency inversion without complex class hierarchies.