Design Patterns: Adapter
Tags: computerscience, beginners, programming, architecture
Published: 2021-08-09 03:34:08

<!-- wp:paragraph -->
<p>In the last article, we have finished the first chapter in our design pattern series.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Today, we start a new chapter, where we will go over the structural design pattern.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>"But, what's structural?" you may ask.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>While creational patterns focus on how objects are created, structural patterns focus on how efficient do objects <strong>combine</strong> to create other <strong>complex</strong> objects.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>A real-life analogy would be a fruit salad, you can make fruit salads in many different ways with all sorts of different fruits, but there are some combinations that are superior to others. Structural design patterns help use effectively and flexibly combine objects together to form complex structures.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To begin, the first of these patterns would be the Adapter pattern.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>Today you will learn:</strong></p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Core concepts behind the Adapter pattern</li><li>How to implement the adapter pattern</li><li>How to recognize opportunities the adapter pattern</li><li>The benefits and downsides of the adapter pattern</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Definition</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>We have a ritual in this series, to start googling things.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>So let's google: "what is the adapter pattern?"</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You would get a Wikipedia answer that would look something like this:</p>
<!-- /wp:paragraph -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>In software engineering, the adapter pattern is a software design pattern that allows the interface of an existing class to be used as another interface. It is often used to make existing classes work with others without modifying their source code</p></blockquote>
<!-- /wp:quote -->

<!-- wp:paragraph -->
<p>Why does Wikipedia make everything sound so damn complicated?</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In a nutshell, the <strong>adapter pattern allows classes with incompatible interfaces to work with each other.</strong></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>But what do you mean by incompatible interfaces?</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Good question, lemme give you an example</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><em>PS. I'm taking this example from refactoring.guru, they are a great resource, and most of my research comes from there. You can check them out <a href="https://refactoring.guru/">here</a>.</em></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Imagine that you have a stock monitoring app.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The app currently has two components:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>The third-party library you use to get stocks data.</li><li>A client that monitors, and visualizes the data.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>One day you come across a new library, that provides analytics.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You get all excited and begin coding.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You eventually realize that your current code isn't compatible with the analytics library.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Your code, works on XML, while the analytics library works in JSON.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Your stock provider only works with XML, while the analytics only works with JSON.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This may be the end...</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":658,"sizeSlug":"full","linkDestination":"none"} -->
<div class="wp-block-image"><figure class="aligncenter size-full"><img src="https://softwareadventuring.com/wp-content/uploads/2021/07/1-9.png" alt="" class="wp-image-658"/><figcaption>Source: <a href="https://refactoring.guru/design-patterns/adapter"></a><a href="https://refactoring.guru/design-patterns/adapter">https://refactoring.guru/design-patterns/adapter</a></figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>At this point you have two options:</p>
<!-- /wp:paragraph -->

<!-- wp:list {"ordered":true} -->
<ol><li>Get all grumpy and quit</li><li>Toughen up and find a solution</li></ol>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>For the sake of this article, let's say you went with option number two.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>After a while, you come across an article, about the adapter pattern, and soon realize it's a perfect opportunity to use it.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You just have to create an <em>Adapter</em> class, that transforms XML to JSON.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":659,"sizeSlug":"full","linkDestination":"none"} -->
<div class="wp-block-image"><figure class="aligncenter size-full"><img src="https://softwareadventuring.com/wp-content/uploads/2021/07/2-8.png" alt="" class="wp-image-659"/><figcaption>Source: <a href="https://refactoring.guru/design-patterns/adapter"></a><a href="https://refactoring.guru/design-patterns/adapter">https://refactoring.guru/design-patterns/adapter</a></figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>The adapter has to <em>wrap</em> around the XML object and transform it into JSON.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The XML class doesn't even know it's being wrapped.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Seems simple enough, let's implement this!</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Implementation</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Currently, our client looks something like this:</p>
<!-- /wp:paragraph -->

<!-- wp:enlighter/codeblock {"language":"js"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import stock_data_providor from "third-party-stock-library"

class Client {

	public function main(){
		const xml_stocks = stock_data_provider.get_all_stocks()

		this.visualize(xml_stocks)
	}

	public function visualize(){
		// visualization code
	}

}
</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:paragraph -->
<p>There are currently only two components, the stock data and client.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's try adding the analytics library:</p>
<!-- /wp:paragraph -->

<!-- wp:enlighter/codeblock {"language":"js"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import stock_data_providor from "third-party-stock-library"
import analytics from "third-party-analytics-library"

class Client {

	public function main(){
		const xml_stocks = stock_data_provider.get_all_stocks()

		this.visualize(xml_stocks)
		analytics.analyze(xml_stocks)
	}

	// rest of code

}
</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:paragraph -->
<p>This will throw an error because the <code>analyze</code> function only accepts a JSON.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To fix that, we have to transform the XML into JSON.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's create an adapter class:</p>
<!-- /wp:paragraph -->

<!-- wp:enlighter/codeblock {"language":"js"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class XmlToJsonAdapter(){
	const xml_data

	constructor(xml_data){
			this.xml_data = xml_data
	}

	public function get_json() {
		// return json version of xml
		// out of the scope of this article 
	}

}
</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:paragraph -->
<p>Our adapter class accepts <code>xml_data</code> and with the help of the <code>get_json</code> function, it returns a JSON version of the XML.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's update our client:</p>
<!-- /wp:paragraph -->

<!-- wp:enlighter/codeblock {"language":"js"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import stock_data_providor from "third-party-stock-library"
import analytics from "third-party-analytics-library"
import XmlToJsonAdapter from "./xml_adapter"

class Client {

	public function main(){
		const xml_stocks = stock_data_provider.get_all_stocks()
		const json_format = new XmlToJsonAdapter(xml_stocks)

		this.visualize(xml_stocks)
		analytics.analyze(json_format)
	}

	// rest of code

}
</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:paragraph -->
<p>Our code is finally working, good job in implementing the adapter pattern.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>A key to learning design patterns is to know when to use them.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's go over opportunities on when to use this pattern.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>When to use this pattern?</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li><strong>Incompatible Interfaces</strong> — When you want to integrate two or more classes with incompatible interfaces, you can use the adapter pattern to make it work.</li><li><strong>Code Reuse</strong> — Use the adapter pattern when you want to reuse legacy code without making any modifications to the original code.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Benefits</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Throughout this article, we have covered the technical aspects of the adapter pattern.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's take a step back, and think about why is this pattern useful:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li><strong>Single Responsibility Principle</strong> — You separate the data conversion code, from the underlying business logic.</li><li><strong>Open Closed Principle</strong> — You can easily introduce new adapters, without breaking the existing client code, as long as they work with a common interface.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Downsides</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Time to hit reality, it's not all sunshine and rainbows.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's go over the downsides in using the adapter pattern:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li><strong>Complexity</strong> — The overall complexity of the code increases, due to the addition of extra classes and interfaces. Sometimes it's easier to change the code in the services. But keep in mind, <strong>the path of least resistance isn't always the best.</strong></li><li><strong>Adapter Chain</strong> — Sometimes many different adapters are required, causing an adapter chain. This kind of code simply gets very messy and hard to debug.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Conclusion</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>I would like to end it off with a question.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>What do you think about this pattern?</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Do you ever see yourself using it?</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Can't wait to see your answers down in the comments.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This has been Tamerlan, I would appreciate it if you would follow me on Twitter <a href="https://twitter.com/tamerlan_dev">@tamerlan_dev</a> and check out my blog <a href="http://softwareadventuring.com">softwareadventuring.com</a> for more content like this.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>Today you learned:</strong></p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Definition and implementation of the adapter pattern.</li><li>When to use the adapter pattern.</li><li>The benefits and downsides of using the adapter pattern.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Thanks for reading!</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Further Readings</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>If you want to learn more about the design patterns, I would recommend&nbsp;<a href="https://refactoring.guru/design-patterns">Diving into Design Patterns</a>. It explains all 23 design patterns found in the GoF book, in a fun and engaging manner.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Another book that I recommend is&nbsp;<a href="https://www.amazon.com/Head-First-Design-Patterns-Brain-Friendly/dp/0596007124">Heads First Design Patterns: A Brain-Friendly Guide</a>, which has fun and easy-to-read explanations.</p>
<!-- /wp:paragraph -->