Junior — Middle
Can you explain the concept of dependency inversion and its role in system design?
sobes.tech AI
Answer from AI
Inversion of Control (IoC) is a design principle where the management of dependencies between system components is delegated to an external container or framework, rather than being created directly within the components.
Role in system design:
- Enhances modularity and testability, as components do not depend on specific implementations but receive them externally.
- Simplifies replacement and extension of components without changing the code that uses them.
Example: instead of the class creating the dependency object itself, it receives it through a constructor or setter. This allows easy substitution of implementations, for example, for testing.
protocol Service {
func doWork()
}
class RealService: Service {
func doWork() { print("Work completed") }
}
class Client {
let service: Service
init(service: Service) {
self.service = service
}
}
let service = RealService()
let client = Client(service: service)
Here, Client does not create RealService itself but receives it from outside — this is the essence of inversion of control.