Sobes.tech
Junior — Middle

Can you explain the difference between the dependency inversion principle and dependency injection in programming?

sobes.tech AI

Answer from AI

The Dependency Inversion Principle (DIP) is one of the SOLID principles, stating that high-level modules should not depend on low-level modules directly; both should depend on abstractions (e.g., interfaces). Abstractions should not depend on details; details should depend on abstractions. This helps make architecture more flexible and extendable.

Dependency Injection (DI) is a pattern or technique that implements the dependency inversion principle. DI means that an object's dependencies are provided from outside (e.g., via constructor, setter, or method), not created inside the object. This facilitates testing and component replacement.

In other words:

  • DIP is a design rule or principle.
  • DI is a way to implement this principle in practice.

Example in Swift:

protocol NetworkService {
    func fetchData()
}

class APIService: NetworkService {
    func fetchData() {
        print("Fetching data from API")
    }
}

class ViewModel {
    let networkService: NetworkService

    // Dependency injection via constructor
    init(networkService: NetworkService) {
        self.networkService = networkService
    }

    func load() {
        networkService.fetchData()
    }
}

let apiService = APIService()
let viewModel = ViewModel(networkService: apiService)
viewModel.load()