Sobes.tech
Junior — Middle

Kas saaks anda näite, kuidas rakendada sõltuvuste pööramise põhimõtet projektis?

sobes.tech AI

Vastus AI-lt

The Dependency Inversion Principle (DIP) states that high-level modules should not depend on low-level modules directly, but both should depend on abstractions (e.g., 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 depending on abstraction, not on 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 another data source, without changing the ViewModel code.