Abstracting third-party libraries and framework code

Now that we have variables, methods, and classes abstracted, it is time to abstract third-party libraries, framework code, and those classes we just created.

Firstly, let's start with framework details. Things like DateTime, Random, and Console are best hidden behind classes that you design to fit the needs of your application. There are several reasons for this; most importantly, putting these in their own classes will allow for testing. Without abstracting these to a separate class, it is almost impossible to test with things like DateTime that change values on their own.

Next up are the third-party libraries. Anywhere the code is calling to create a new class from a third-party, you need to abstract that to a new class specifically for the purpose of utilizing that third-party library. For the moment, replace the call that instantiates the third-party library with a call that instantiates your class.

Lastly, we can now deal with the calls to new that are left in the code. Everywhere that the code is calling new needs to be replaced with dependency injection. This will allow for testing and make the code cleaner and more flexible in the future.

To create the dependency injection without modifying the signature of the class, we will be using a pattern called poor man's dependency injection, also known as property injection. Below is an example of property injection in C#. The same process can be done in JavaScript with almost no modifications:

public class Example
{
private Injected _value;
public Injected Value
{
get => _value = _value ?? new Injected();
set => _value = value;
}
}

Using this pattern, it is possible to allow the class to create its dependency lazily, when asked for it. It is also possible to set the dependencies value for tests or other purposes. Although not shown in this quick example of the pattern, it is better to have the property and backing variable be of an interface type. This will make the injection of some other value easier.

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

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