Iterative scheme for adapting JavaScript abstractions

小云云
Release: 2017-12-08 14:03:05
Original
1495 people have browsed it

In this article, we introduce to you the iterative plan for adjusting JavaScript abstraction, hoping to help you. To make it clearer, let's assume that inJavaScriptthe abstraction is a module.

The initial implementation of a module is only the beginning of their long (and perhaps long-lasting) life cycle process. I divide the life cycle of a module into 3 important stages.

  1. Introduce modules. Write the module or reuse the module in the project;

  2. Adjust the module. Adjust modules at any time;

  3. Remove modules.

In my previous article, the focus was on the first point. And in this article, I will focus on the second point.

Module changes are a problem I often encounter. Compared with introducing modules, the way developers maintain and change modules is equally or even more important to ensure the maintainability and scalability of the project. I've seen a well-written, well-abstracted module get completely ruined after multiple changes over time. I myself am often one of those responsible for that damaging change.

When I say destructive, I mean destructive in terms of maintainability and scalability. I also understand that when faced with the pressure of project deadlines, slowing down to make better revisions to the design is not a priority.

There may be many reasons why developers make non-optimal changes. I would like to highlight one in particular here:

Tips for making changes in a maintainable way

This method makes your revisions look more professional.

Let's start with a code example for theAPImodule. I chose this example because communicating with an externalAPIis one of the most basic abstractions I defined when starting the project. The idea here is to store allAPIrelated configuration and settings (like baseURL, error handling logic, etc.) in this module.

I will write A settingAPI.url, a private methodAPI._handleError()and a public methodAPI.get():

class API { constructor() { this.url = 'http://whatever.api/v1/'; } /** * API 数据获取的特有方法 * 检查一个 HTTP 返回的状态码是否在成功的范围内 */ _handleError(_res) { return _res.ok ? _res : Promise.reject(_res.statusText); } /** * 获取数据 * @return {Promise} */ get(_endpoint) { return window.fetch(this.url + _endpoint, { method: 'GET' }) .then(this._handleError) .then( res => res.json()) .catch( error => { alert('So sad. There was an error.'); throw new Error(error); }); } };
Copy after login

in In this module, the public methodAPI.get()returns aPromise. We use our abstractedAPImodule instead of callingFetch APIdirectly throughwindow.fetch(). For example, get user informationAPI.get('user')or current weather forecastAPI.get('weather'). The important thing about implementing this feature is that theFetch API is not tightly coupled to our code.

Now, we face a modification! The technical director asked us to switch the method of obtaining remote data to Axios. How should we respond?

Before we start discussing the methods, let’s summarize what is unchanged and what needs to be modified:

  1. Changes: In the publicAPI In the .get()method,

  • ##needs to modify the

    window.fetch()call ofaxios(); required Return aPromiseagain to keep the interface consistent. Fortunately,Axiosis based onPromise, which is great!

  • The server’s response is

    JSON. Parse the response data throughFetch APIand by chaining.then( res => res.json())statements. WithAxios, the server response is in thedataattribute and we don't need to parse it. Therefore, we need to change the.thenstatement to.then(res => res.data).

  • Change: In private

    API._handleErrormethod:

    • In response object The

      okboolean flag is missing, however, there is also astatusTextattribute. We can string through it, and if its value isOK, then everything will be fine (P.S.OKisinFetch APItrueis different fromstatusTextinAxioswhich isOK, but for ease of understanding and not being too broad, no advanced information is introduced. Error handling.)

  • Stay unchanged:

    API.urlremains the same, we will catch errors and alert them in a pleasant way.

  • End of explanation! Now let’s dive into the actual method of applying these modifications.

    Method 1: Delete the code. Write code.

    class API { constructor() { this.url = 'http://whatever.api/v1/'; // 一模一样的 } _handleError(_res) { // DELETE: return _res.ok ? _res : Promise.reject(_res.statusText); return _res.statusText === 'OK' ? _res : Promise.reject(_res.statusText); } get(_endpoint) { // DELETE: return window.fetch(this.url + _endpoint, { method: 'GET' }) return axios.get(this.url + _endpoint) .then(this._handleError) // DELETE: .then( res => res.json()) .then( res => res.data) .catch( error => { alert('So sad. There was an error.'); throw new Error(error); }); } };
    Copy after login

    Sounds reasonable. Submit, upload, merge, complete.

    However, in some cases, this may not be a good idea. Imagine the following scenario: after switching to

    Axios, you will find that there is a feature that does not apply to XMLHttpRequests (Axios's method of getting data), but before using theFetch API's newer browsers work just fine. What should we do now?

    我们的技术负责人说,让我们使用旧的API实现这个特定的用例,并继续在其他地方使用Axios。你该做什么?在源代码管理历史记录中找到旧的API模块。还原。在这里和那里添加if语句。这样听起来并不太友好。

    必须有一个更容易,更易于维护和可扩展的方式来进行更改!那么,下面的就是。

    方法二:重构代码,做适配!

    重构的需求马上来了!让我们重新开始,我们不再删除代码,而是让我们在另一个抽象中移动Fetch的特定逻辑,这将作为所有Fetch特定的适配器(或包装器)。

    HEY!???对于那些熟悉适配器模式(也被称为包装模式)的人来说,是的,那正是我们前进的方向!如果您对所有的细节感兴趣,请参阅这里我的介绍。

    如下所示:
    Iterative scheme for adapting JavaScript abstractions

    步骤1

    将跟Fetch相关的几行代码拿出来,单独抽象为一个新的方法FetchAdapter

    class FetchAdapter { _handleError(_res) { return _res.ok ? _res : Promise.reject(_res.statusText); } get(_endpoint) { return window.fetch(_endpoint, { method: 'GET' }) .then(this._handleError) .then( res => res.json()); } };
    Copy after login

    步骤2

    重构API模块,删除Fetch相关代码,其余代码保持不变。添加FetchAdapter作为依赖(以某种方式):

    class API { constructor(_adapter = new FetchAdapter()) { this.adapter = _adapter; this.url = 'http://whatever.api/v1/'; } get(_endpoint) { return this.adapter.get(_endpoint) .catch( error => { alert('So sad. There was an error.'); throw new Error(error); }); } };
    Copy after login

    现在情况不一样了!这种结构能让你处理各种不同的获取数据的场景(适配器)改。最后一步,你猜对了!写一个AxiosAdapter

    const AxiosAdapter = { _handleError(_res) { return _res.statusText === 'OK' ? _res : Promise.reject(_res.statusText); }, get(_endpoint) { return axios.get(_endpoint) then(this._handleError) .then( res => res.data); } };
    Copy after login

    API模块中,将默认适配器改为AxiosAdapter

    class API { constructor(_adapter = new /*FetchAdapter()*/ AxiosAdapter()) { this.adapter = _adapter; /* ... */ } /* ... */ };
    Copy after login

    真棒!如果我们需要在这个特定的用例中使用旧的API实现,并且在其他地方继续使用Axios?没问题!

    //不管你喜欢与否,将其导入你的模块,因为这只是一个例子。 import API from './API'; import FetchAdapter from './FetchAdapter'; //使用 AxiosAdapter(默认的) const API = new API(); API.get('user'); // 使用FetchAdapter const legacyAPI = new API(new FetchAdapter()); legacyAPI.get('user');
    Copy after login

    所以下次你需要改变你的项目时,评估下面哪种方法更有意义:

    • 删除代码,编写代码。

    • 重构代码,写适配器。

    总结请根据你的场景选择性使用。如果你的代码库滥用适配器和引入太多的抽象可能会导致复杂性增加,这也是不好的。愉快的去使用适配器吧!

    相关推荐:

    JavaScript工作体系中不可或缺的函数

    JavaScript中filter函数的详细介绍

    JS实现的计数排序与基数排序算法示例_javascript技巧

    The above is the detailed content of Iterative scheme for adapting JavaScript abstractions. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!