Sobes.tech
Junior — Middle

Could you provide an example of when the D principle in SOLID is applied in practice?

sobes.tech AI

Answer from AI

The Dependency Inversion Principle (D) in SOLID states that high-level modules should not depend on low-level modules directly, but both should depend on abstractions.

In practice, in Android development, this is often implemented through the use of interfaces and dependency injection. For example, instead of a class Activity directly creating a data repository object, it depends on the repository interface, and the specific implementation is passed from outside.

Example:

interface UserRepository {
    fun getUser(id: String): User
}

class UserRepositoryImpl : UserRepository {
    override fun getUser(id: String): User {
        // Fetch user from database
    }
}

class UserViewModel(private val userRepository: UserRepository) {
    fun loadUser(id: String) {
        val user = userRepository.getUser(id)
        // process user
    }
}

Here, UserViewModel depends on the abstraction UserRepository, not on a specific implementation, which makes testing and maintaining the code easier.