[Pattern] Adapter - How to make objects work together?

[Pattern] Adapter - How to make objects work together?

Daily short news for you
  • For a long time, I have been thinking about how to increase brand presence, as well as users for the blog. After much contemplation, it seems the only way is to share on social media or hope they seek it out, until...

    Wearing this shirt means no more worries about traffic jams, the more crowded it gets, the more fun it is because hundreds of eyes are watching 🤓

    (It really works, you know 🤭)

    » Read more
  • A cycle of developing many projects is quite interesting. Summarized in 3 steps: See something complex -> Simplify it -> Add features until it becomes complex again... -> Back to a new loop.

    Why is that? Let me give you 2 examples to illustrate.

    Markdown was created with the aim of producing a plain text format that is "easy to write, easy to read, and easy to convert into something like HTML." At that time, no one had the patience to sit and write while also adding formatting for how the text displayed on the web. Yet now, people are "stuffing" or creating variations based on markdown to add so many new formats that… they can’t even remember all the syntax.

    React is also an example. Since the time of PHP, there has been a desire to create something that clearly separates the user interface from the core logic processing of applications into two distinct parts for better readability and writing. The result is that UI/UX libraries have developed very robustly, providing excellent user interaction, while the application logic resides on a separate server. The duo of Front-end and Back-end emerged from this, with the indispensable REST API waiter. Yet now, React doesn’t look much different from PHP, leading to Vue, Svelte... all converging back to a single point.

    However, the loop is not bad; on the contrary, this loop is more about evolution than "regression." Sometimes, it creates something good from something old, and people rely on that goodness to continue the loop. In other words, it’s about distilling the essence little by little 😁

    » Read more
  • Alongside the official projects, I occasionally see "side" projects aimed at optimizing or improving the language in some aspects. For example, nature-lang/nature is a project focused on enhancing Go, introducing some changes to make using Go more user-friendly.

    Looking back, it resembles JavaScript quite a bit 😆

    » Read more

Problem

Imagine you are a skilled Front-end developer who has just finished designing the interface and is only waiting to connect with the API. But on the day the Back-end team says they can't hand it over to you yet, so you have to wait until the API is available before continuing your work.

Or in another scenario, you are assigned the task of integrating the system with a partner through an API. They have provided complete documentation and you only need to connect to the data as described. But near the end, the partner informs you that they have changed the data in some places. You feel frustrated because you have to sit and review and modify code in many places in the project.

The above are two common situations in the work of every programmer. If you have encountered these situations before and felt helpless, this article will introduce a pattern called Adapter to help you overcome this pain to some extent.

Design Pattern - Adapter

Adapter is a structural design pattern that allows incompatible objects with different interfaces to work together.

The Adapter plays a role in converting the data (objects) of one object so that another object can understand it. The Adapter hides the complexity of the conversion process, and the receiving object does not even need to care about the data from the other object, as everything goes through an Adapter.

For example, a chart library only works with data received in JSON format, but the data you fetch from the system is in XML format. In this case, you need to create a function to convert the data from XML to JSON and pass it to the library. This function is called an Adapter.

... -> XML -> Adapter (function) -> JSON -> Library -> ...  

Going back to the problem, once you know about the Adapter, you are no longer completely dependent on the data from the API. What you need to do is to create an object that holds the necessary data for display or processing in the interface, and then create an Adapter function to convert the data from the API into that object, and you're done.

<template>
  <a-list item-layout="horizontal" :data-source="data.list">
    <template #renderItem="{ item }">
      <a-list-item>
        <a-list-item-meta :description="item.description" >
          <template #title>
            <a :href="item.url">{{ item.title }}</a>
          </template>
          <template #avatar>
            <a-avatar :src="item.avatar" />
          </template>
        </a-list-item-meta>
      </a-list-item>
    </template>
  </a-list>
</template>
<script lang="ts">
import { defineComponent, onMounted, reactive } from "vue";

// Data retrieved from the server has the format
// [{
//   tieu_de: "xxx",  
//   mo_ta: "xxx",  
//   anh_dai_dien: "xxx",  
//   lien_ket: "xxx"
// }]
const fetchData = () => {
  return fetch("https://api.example.com/list");
}

// Adapter function that converts data from the API into data
const convertRespToData = (resp: any) => {
  return resp.map((item: any) => {
    return {
      title: item.tieu_de,  
      description: item.mo_ta,  
      avatar: item.anh_dai_dien,  
      url: item.lien_ket
    };
  });
}

export default defineComponent({
  setup() {
    // data is the interface variable to be integrated
    const data = reactive<any>({
      list: [],  
    });

    // Fetch data and integrate into the data variable
    onMounted(() => {
      fetchData().then(resp => {
        data.list = convertRespToData(resp);
      });
    });

    return {
      data,  
    };
  },  
});
</script>

Furthermore, creating and controlling data on the client side will limit the errors that may occur from incompatible data from the API. Instead of directly accepting data from the API and integrating it directly into the interface, it's better to go through an Adapter.

Similarly, for problem 2, we should not overly depend on data from a third-party API. Instead, we should create our own data and write Adapter functions to convert data from them. Avoid receiving and using data directly, as the data they provide may not convey the correct and complete content needed for the system. Therefore, if there is a conversion function in between, it will be easier to handle and detect data-related issues at an early stage.

Adapter has many advantages, but it also has some limitations, such as the need to write more code, and the complexity of the code may increase as the number of Adapters and their interdependencies grow. Therefore, try to organize your code as neatly as possible.

Conclusion

Those were two real-life examples I presented to apply the Adapter pattern in practice, hoping it will be helpful to everyone. Adapter can have different implementations depending on the programming language and the problem being solved. For more details, please click on the reference links below.

References:

Premium
Hello

Me & the desire to "play with words"

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

View all

Subscribe to receive new article notifications

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.

Comments (0)

Leave a comment...