Sobes.tech
Junior — Middle

Kas saaksite selgitada sõltuvuste pööramise printsiibi ja sõltuvuste sisestamise erinevusi?

sobes.tech AI

Vastus AI-lt

Dependence Inversion Principle (DIP) — is one of the SOLID principles, which 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.

This is a design principle aimed at reducing coupling and increasing code flexibility.

Dependency Injection (DI) — is a pattern or technique that implements this principle in practice. DI means that dependencies (objects needed by a class to operate) are passed from outside, rather than created inside the class.

Example:

protocol Service {
    func doSomething()
}

class RealService: Service {
    func doSomething() { print("Service work") }
}

class Client {
    let service: Service

    // Dependency injection via constructor
    init(service: Service) {
        self.service = service
    }

    func execute() {
        service.doSomething()
    }
}

let service = RealService()
let client = Client(service: service)
client.execute()

Here, DIP is the idea that the Client depends on the abstraction Service, not on the concrete implementation RealService. DI is the way to pass the concrete implementation to the Client from outside.

Summary:

  • DIP — a design principle.
  • DI — a way to implement this principle.