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

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

Daily short news for you
  • Manus has officially opened its doors to all users. For those who don't know, this is a reporting tool (making waves) similar to OpenAI's Deep Research. Each day, you get 300 free Credits for research. Each research session consumes Credits depending on the complexity of the request. Oh, and they seem to have a program giving away free Credits. I personally saw 2000 when I logged in.

    I tried it out and compared it with the same command I used before on Deep Research, and the content was completely different. Manus reports more like writing essays compared to OpenAI, which uses bullet points and tables.

    Oh, after signing up, you have to enter your phone number for verification; if there's an error, just wait until the next day and try again.

    » Read more
  • I just found a quite interesting website talking about the memorable milestones in the history of the global Internet: Internet Artifacts

    Just from 1977 - when the Internet was still in the lab - look how much the Internet has developed now 🫣

    » Read more
  • Just thinking that a server "hiding" behind Cloudflare is safe, but that’s not necessarily true; nothing is absolutely safe in this Internet world. I invite you to read the article CloudFlair: Bypassing Cloudflare using Internet-wide scan data to see how the author discovered the IP address of the server that used Cloudflare.

    It's quite impressive, really; no matter what, there will always be those who strive for security and, conversely, those who specialize in exploiting vulnerabilities and... blogging 🤓

    » 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

The secret stack of Blog

As a developer, are you curious about the technology secrets or the technical debts of this blog? All secrets will be revealed in the article below. What are you waiting for, click now!

As a developer, are you curious about the technology secrets or the technical debts of this blog? All secrets will be revealed in the article below. What are you waiting for, click 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...