Why dependency injection?

Consider that we are creating a Mobile class, and it has dependency on a camera and internet connectivity.

The code snippet of a Mobile class

In the preceding code snippet, you can see that the instances of Camera and Internet are created in the constructor of the Mobile class. These are the features of Mobile. Instead of requesting for the feature, the Mobile class created the feature by itself. This means that the Mobile class is bound to a certain version of features, such as a 2 MP camera and 2G Internet. Later, if we want to upgrade the camera to 20 MP and Internet to 3G or 4G, we need to rewrite the code of the Mobile class.

The Mobile class is dependent on Camera and Internet, and this increases the difficulty in testing. We can only test Mobile with 2G Internet and 2 MP Camera because we cannot control the dependencies as the Mobile class takes care of the instance of dependency by itself.

Now, let's modify the constructor to receive the instance of Camera and Internet as parameters, as shown in the following line of code:

constructor(public camera: Camera, public internet: Internet) { } 

Now the Mobile class will not create an instance of Camera or Internet. It just consumes the instance of Camera or Internet that is received from the constructor parameters. This means that we moved the dependencies to the constructor. The client can create a Mobile class by passing the instance of Camera and Internet to the constructor, as shown in the following code snippet:

// Simple mobile with 2MP camera and 2G internet. 
var mobile = new Mobile(new Camera2MP(), new Internet2G());

As you can see, the definitions of Camera and Internet have been decoupled from the Mobile class. We can pass any type of Camera with various megapixels and Internet with various bandwidths, such as 2G, 3G, and 4G, as long as both the Camera and Internet types passed by the client comply with the interface of Camera and Internet:

// an advanced mobile with 20MP camera and 4G internet. 
var mobile = new Mobile(new Camera20MP(), new Internet4G());

There is no change in the Mobile class to accommodate the 20 MP Camera and 4G Internet dependencies. The Mobile class is much easier to test with various combinations of Camera and Internet, as we have complete control over the dependencies. We can also use a mocking technique in testing and pass mocks of Camera and Internet to constructor so that all the necessary operations will be done against the mocks of Camera and Internet.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset