Junior — Middle
Could you explain the advantages and disadvantages of using dependency inversion in programming?
sobes.tech AI
Answer from AI
Dependency Inversion is a principle where high-level modules do not depend on low-level modules, but both depend on abstractions.
Advantages:
- Improves modularity and testability of the code, as dependencies can be easily replaced.
- Increases flexibility and scalability of the application.
- Reduces coupling between components.
Disadvantages:
- Complicates architecture, especially in small projects.
- Requires additional time for designing abstractions.
- May lead to an excessive number of interfaces and classes.
Example in Swift:
protocol DataService {
func fetchData() -> String
}
class APIService: DataService {
func fetchData() -> String {
return "Data from API"
}
}
class ViewModel {
private let service: DataService
init(service: DataService) {
self.service = service
}
func getData() -> String {
return service.fetchData()
}
}
let apiService = APIService()
let viewModel = ViewModel(service: apiService)
print(viewModel.getData())
Here, ViewModel depends on the abstraction DataService, not on the specific implementation APIService.