Junior — Middle
Can you give an example of implementing the dependency inversion principle in a project?
sobes.tech AI
Answer from AI
The Dependency Inversion Principle (DIP) states that high-level modules should not depend on low-level modules directly, but both should depend on abstractions (such as protocols or interfaces).
Example in Swift for iOS:
// Abstraction
protocol DataService {
func fetchData() -> String
}
// Concrete implementation
class NetworkDataService: DataService {
func fetchData() -> String {
return "Data from network"
}
}
// Class that depends on abstraction, not on a concrete implementation
class ViewModel {
private let dataService: DataService
init(dataService: DataService) {
self.dataService = dataService
}
func getData() -> String {
return dataService.fetchData()
}
}
// Usage
let networkService = NetworkDataService()
let viewModel = ViewModel(dataService: networkService)
print(viewModel.getData()) // Outputs: Data from network
Here, ViewModel depends on the DataService protocol, not on the concrete class NetworkDataService. This allows easy swapping of the service implementation, for example, for testing or using a different data source, without changing the ViewModel code.