Junior — Middle
Can you give an example of a situation where the principle of dependency inversion is violated?
sobes.tech AI
Answer from AI
The Dependency Inversion Principle states that high-level modules should not depend on low-level modules directly, but both should depend on abstractions.
Example of violation:
If an Android application's Activity directly creates and uses a specific class for data access (for example, a specific repository), then the Activity depends on the concrete implementation rather than on an abstraction (interface). This complicates testing and replacing the implementation.
class UserRepository {
fun getUser() = "User"
}
class MainActivity : AppCompatActivity() {
private val userRepository = UserRepository() // Direct dependency on a specific class
fun showUser() {
val user = userRepository.getUser()
// ...
}
}
Here, the principle is violated because MainActivity depends on the concrete UserRepository rather than on an interface, which makes it difficult to replace or mock the repository.