Encapsulating and adapting third-party code

The downside of picking a third-party abstraction, especially a framework, is that you can end up changing your code base to suit the arbitrary conventions and design decisions of the abstraction's authors. Often, we are made to speak the same language of these third-party interfaces, instead of having them speak our language. Indeed, in many cases, it may be the abstraction's conventions and design that is appealing to us, and so we are more than happy for it to drive the design and nature of our code base. But, in other situations, we may want to be more protected from our chosen abstractions. We may want the option to easily swap them out for other abstractions in the future, or we may already have a set of conventions that we prefer to use.

In such cases, it may be useful to encapsulate these third-party abstractions and deal with them purely through an abstraction layer of our own. Such a layer would typically be called an Adapter:

Very simply, an Adapter will provide an interface that we design, and will then delegate to the third-party abstraction to accomplish its tasks. Imagine if we wished to use a URL-parsing utility called YOORL. We've decided it works perfectly for our needs, and has complete compliance with RFC 3986 (the URI standard). The only issue is that its API is rather burdensome and verbose:

import YOORL from 'yoorl';
YOORL.parse(
new YOORL.URL.String('http://foo.com/abc/?x=123'),
{ parseSearch: true }
).parts();

This would return the following Object:

{
protocol: 'http',
hostname: 'foo.com',
pathname: '/abc',
search: { x: 123 }
}

We would prefer it if the API was far simpler. The length and complexity of the current API, we feel, would expose our code base to needless complexity and risk (the risk of calling it the wrong way, for example). Using an Adapter would allow us to wrap up this non-ideal interface into an interface of our own design:

// URLUtils.js
import YOORL from 'yoorl';
export default {
parse(url) {
return YOORL.parse(
new YOORL.URL.String(url)
).parts();
}
};

This means that any modules within our code base can now interface with this simplified Adapter, insulating them from the unideal API of YOORL:

import URLUtils from './URLUtils';

URLUtils.parse('http://foo.com/abc/?x=123'); // Easy!

Adapters can be thought of as translation mediums, allowing our code base to speak the language of its choice, not having to be slowed down by the arbitrary and inconsistent design decisions of third-party libraries. This not only aids the usability and intuitiveness of the code base but also enables us to very easily make changes to the underlying third-party library without having to change many lines of code at all. 

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

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