Sobes.tech
Junior — Middle

Kas on sõltuvuste sisestamine ja kuidas seda rakendatakse programmeerimises?

sobes.tech AI

Vastus AI-lt

Dependency Injection (DI) is a design pattern where an object receives its dependencies (such as other objects or services) from outside, rather than creating them itself. This helps make the code more modular, testable, and flexible.

In programming, this is usually implemented by passing dependencies into the class constructor, via setters, or through interfaces. For example, in Android, DI libraries (Dagger, Hilt) are often used to automatically create and pass the required objects.

Example in Kotlin:

class Engine {
    fun start() = println("Engine started")
}

class Car(private val engine: Engine) {
    fun drive() {
        engine.start()
        println("Car is driving")
    }
}

fun main() {
    val engine = Engine() // create dependency
    val car = Car(engine) // inject dependency
    car.drive()
}

Here, Car does not create Engine itself, but receives it from outside, which makes replacing or testing Engine easier.