Sobes.tech
Junior — Middle

Can you explain what dependency injection pattern means in programming?

sobes.tech AI

Answer from AI

Dependency Injection (DI) is a way of organizing code where an object receives its dependencies (such as other objects or services) from outside, rather than creating them itself. This increases modularity, makes testing easier, and simplifies component replacement.

For example, instead of a class creating a database object internally, it receives it through a constructor or setter:

class UserRepository(private val database: Database) {
    fun getUser(id: String) = database.queryUser(id)
}

// When creating a UserRepository object, we pass a specific implementation of Database
val db = SqlDatabase()
val repo = UserRepository(db)

This approach allows easy substitution of dependencies, for example, with mock objects during testing.