Sobes.tech
Junior — Middle

Can you explain the concept of dependency injection and why it is needed in programming?

sobes.tech AI

Answer from AI

Dependency Injection (DI) is a design pattern where an object receives its dependencies from outside rather than creating them itself. This helps make the code more modular, testable, and flexible.

For example, instead of creating an instance of a service inside a class, you pass this service through the constructor or setter. This makes it easier to replace the implementation of the service, for example, with a mock for testing.

Example in Swift:

protocol Service {
    func doSomething()
}

class RealService: Service {
    func doSomething() {
        print("Doing work")
    }
}

class Consumer {
    let service: Service

    init(service: Service) {
        self.service = service
    }

    func execute() {
        service.doSomething()
    }
}

let service = RealService()
let consumer = Consumer(service: service)
consumer.execute()

Thus, dependency injection simplifies maintenance and testing.

Can you explain the concept of dependency injection… - sobes.tech