Press ESC to close

Dependency Injection

Hello friends, in this article we will talk about what Dependency Injection is. It comes from Dependency Inversion, the last principle of Solid principles. This principle cares that the interdependence between the classes we create is as low as possible. Upper class and lower class should be independent of each other. Therefore, Dependency Injection has come to a very important point in today’s technologies.

In this article, we will talk about how we use it in the projects we develop with Swift. In the example we will do, we will create a dog class and use this dog class in the animal class. Our code is as follows. Currently the animal class actually depends on the dog class. When we try to add a cat, lion, elephant, etc. to this animal class in the future, we will have to create a separate class for all of them, and this animal class will actually depend on each separate animal class we create. When something changes here, it will be very difficult to manage. A separate effort will be required for each class.

class Animal {
    var dog: Dog?
    
    init(dog: Dog) {
        self.dog = dog
    }
    
    func play() {
        dog?.run()
        dog?.stop()
        dog?.eat()
    }
}

class Dog {
    
    func run() -> String {
        return "run"
    }
    
    func eat() -> String {
        return "eat"
    }
    
    func stop() -> String {
        return "stop"
    }
}

Instead, we can create a protocol called IAnimal and ensure that all the animals we create are managed thanks to this protocol. In this way, we can manage it more comfortably this way, rather than managing it separately for each animal.

protocol IAnimal {
    func run() -> String
    func eat() -> String
    func stop() -> String
}


class Animal {
    var dog: IAnimal?
    
    init(dog: Dog) {
        self.dog = dog
    }
    
    func play() {
        dog?.run()
        dog?.stop()
        dog?.eat()
    }
}

class Dog: IAnimal {
    
    func run() -> String {
        <#code#>
    }
    
    func eat() -> String {
        <#code#>
    }
    
    func stop() -> String {
        <#code#>
    }
}

class Cat: IAnimal {
    func run() -> String {
        <#code#>
    }
    
    func eat() -> String {
        <#code#>
    }
    
    func stop() -> String {
        <#code#>
    }
}

If you have questions, you can reach us by sending an e-mail or comment. Good work.

Leave a Reply

Your email address will not be published. Required fields are marked *