Dependency Injection | Swift | Quick Note

A short answer is, it’s scary terms for a very simple idea!!! See this lines of code.

class Engine {

}

class Car {
    let engine: Engine? = nil
    init() {
        self.engine = Engine()
    }
}

we are creating dependency internally but the object can be also received from outside with lots of benefits like the object become instantly testable, Testing becomes possible without any frameworks, No runtime effects, This makes the whole system more loosely coupled.

class Car {
    let engine: Engine? = nil
    init(engine: Engine) {
        self.engine = engine
    }
}

There are three common types of dependency injections.

Setter, Interface, Constructor based.

In iOS Constructor based is preferable one, it’s when dependency passed to the client in the initializer and don’t change during the whole client life and the biggest advantage of this type could be that it makes the violation of the single responsibility programming principle, if an object takes all dependencies in the initializer and if it has more than three parameters so it means refactoring is needed.

Thanks for reading!!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s