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 that allows objects to receive their dependencies from outside rather than creating them internally. This enhances modularity, makes testing easier, and supports code maintenance.

For example, in an iOS application, you have a ViewController class that depends on a NetworkService. Instead of creating the NetworkService inside the ViewController, you pass it through the initializer or a property:

class NetworkService {
    func fetchData() { /* ... */ }
}

class ViewController {
    let networkService: NetworkService

    init(networkService: NetworkService) {
        self.networkService = networkService
    }

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

// Usage:
let service = NetworkService()
let vc = ViewController(networkService: service)

This approach makes it easy to replace NetworkService with a mock object during testing and improves architecture flexibility.