What is Dependency Injection?

Sellen Wei
2 min readApr 30, 2018

--

Dependency injection means giving an object its instance variable

  1. Instead if genterate var variableName:VariableType = variableType() inside a class, we change the definition to: var variableName: VariableType? And define it outside of the class
  2. so let Object = Class() and object.variableName = variableType()
  3. What is the benefit?

Help reducing coupling: if the variableType is protocol instead of class, we could instantiate the variable with any class inherit from the protocol and it is very easy to be changed after the class have been implement.

4. why it is good for Unit test?

it is easy for mock object, if we create an mock object inherit same protocol and set object.variableName = mockObject();// variableName is protocol type and mockObject is a class inherit same protocol type

protocol eatableFruit {
func theWayToEatFruit() -> Any?
}
class mockFruit: eatableFruit {
func theWayToEatFruit() -> Any?
}
class Apple:eatableFruit {
func theWayToEatFruit() -> Any?
}
class human {
var myFruit:eableFruit
}
let theOneWantToEatFruit = human()
human.myFruit = mockFruit()//to test the function implement in Apple or just simply test if the instantiate is successfully called.

5. Three Types of Injection

initializer injection: declare the variable in init() of class, could declare as immutable and could only be instantiate in init()

protocol eatableFruit {
func theWayToEatFruit() -> Any?
}
class Apple : eatableFruit {
func theWayToEatFruit() - Any? {
return nil
}
}
class human {
private let myFruit: eatableFruit
init (fruitName : fruitName){
self.myFruit = fruitName
}
}
let myFruit = Apple() // could change to any class that inherit eatFruit protocol
let theOneEatFruit = human(myFruit)// and the fruit type is apple here

property injection: for mutable property, could do this way, declare a variable that is mutable and instantiate it after class have been implemented

class Apple {
var color: UIColor?
}
let myApple = Apple()
myApple.color = UIColor()

method injection: take the injection as an argument

class human {
func theWayToEatFruit(with fruitName: eatableFruit) - Any? {
return nil
}
}

6. singleton increase coupling while dependency injection reduce coupling, so it could help limit the use of singleton.

Trade off

One reason we want to avoid using DI, is if the argument number is too large, usually if argument of DI is more that 5, it takes a while for a new dev to figure out what kind of argument should be initialized and pass in. This takes more time for a dev and increase the complexity. Other that that, we should use Di as much as possible in daily work.

more detail

https://www.youtube.com/watch?v=-n8allUvhw8

--

--