Junior — Middle
Could you give an example of principle D from SOLID principles demonstrating its practical application?
sobes.tech AI
Answer from AI
The Dependency Inversion Principle (D) of SOLID states that:
- High-level modules should not depend on low-level modules. Both should depend on abstractions.
- Abstractions should not depend on details. Details should depend on abstractions.
Example in Android:
Suppose you have a class that retrieves data from the network (lower level) and a class that displays this data (upper level). Instead of the display class depending directly on a specific network implementation, you create an interface (abstraction) that describes data retrieval.
interface DataSource {
fun getData(): String
}
class NetworkDataSource : DataSource {
override fun getData() = "Data from network"
}
class DataPresenter(private val dataSource: DataSource) {
fun present() {
println(dataSource.getData())
}
}
fun main() {
val networkDataSource = NetworkDataSource()
val presenter = DataPresenter(networkDataSource)
presenter.present()
}
This approach allows easy swapping of data sources (e.g., to a local database or a mock for tests) without changing the display logic, which aligns with the dependency inversion principle.