Why an Adapter?

Learn how to use an adapter and learn its advantages.

We'll cover the following

Adapter advantages

Using an adapter class to mediate interaction with the external service is a good idea even when, like Twitter, the external service already has a Ruby gem. The adapter encapsulates logic that is specific to the interaction between our application and the service.

An adapter is useful if our code has any or all of the following qualities:

  • The external service will be accessed from multiple points in our code.

  • The interaction with the external service has its own logic, such as authentication or type changing or common sets of options.

  • There’s a mismatch between the API’s language or metaphor and our code’s domain terms and structures.

The Twitter example doesn’t have the first quality, at least not yet. We do have the second feature: the adapter needs to manage a Twitter client object that nothing else in the application needs to care about or be aware of.

It also manages an argument to the Twitter API: the :bigger argument, which specifies the size of the image we want to download.

Whether there is a mismatch between the API and the code is a matter of interpretation, but we think there is. At the very least, the Twitter client exposes a lot of data that the application doesn’t care about, so limiting access to the full set of Twitter data seems like a good idea.

The usual experience with adapters like the one we’ve written is that they tend to attract functionality while we use them. It’s much easier for a full range of complexity to be available with the side effect at each use. For example, if we allow the adapter to the argument to image_url to represent the size, that ability is automatically available whenever the adapter is used. Attracting functionality is especially valuable for security and error handling, which are easy to leave off when creating each connection separately.

Get hands-on with 1200+ tech skills courses.