Hi, I would like to have a better understanding of Dependency Injection, in general, to start using it.
Based on the three examples below, can someone please point out what would be the pros and the cons of using one over the other?
1 - What problem could Example 1 cause if I don't do unitest? This is my current method.
2- What method of Dependency Injection is best to adopt, Example 2 ro Example 3?
3- I noticed that Example 2 enforces to provided the dependency object at instantiation time whereas Example 3 does not. Couldn't Example 3 create confusion for the programmer since if you don't provide the dependency object, the code will still compile without any warning if you call a function that relies on a method inside the injected object?
Example 1: Without Dependency Injection
class Stereo{
func volume(){
print("Adjusting volume...")
}
}
class Car{
var stereo = Stereo()
func adjustVolume(){
stereo.volume()
}
}
let car = Car()
car.adjustVolume()
Example 2: With Dependency Injection
class Stereo{
func volume(){
print("Adjusting volume...")
}
}
class Car{
var stereo: Stereo
init(stereo: Stereo){
self.stereo = stereo
}
func adjustVolume(){
stereo.volume()
}
}
let car = Car(stereo: Stereo())
car.adjustVolume()
Example 3: With Optional Dependency Injection
class Stereo{
func volume(){
print("Adjusting volume...")
}
}
class Car{
var stereo: Stereo?
func adjustVolume(){
stereo?.volume()
}
// this method can be called without injecting Stereo
func someOtherFunction(){
print("Calling some other function...")
}
}
let car = Car()
car.stereo = Stereo()
car.adjustVolume()
Thanks