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 in
JavaScript
the 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.
Introduce modules. Write the module or reuse the module in the project;
Adjust the module. Adjust modules at any time;
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:
This method makes your revisions look more professional.
Let's start with a code example for theAPI
module. I chose this example because communicating with an externalAPI
is one of the most basic abstractions I defined when starting the project. The idea here is to store allAPI
related 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); }); } };
in In this module, the public methodAPI.get()
returns aPromise
. We use our abstractedAPI
module instead of callingFetch API
directly 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:
Changes: In the publicAPI In the .get()
method,
window.fetch()call of
axios(); required Return a
Promiseagain to keep the interface consistent. Fortunately,
Axiosis based on
Promise, which is great!
JSON. Parse the response data through
Fetch APIand by chaining
.then( res => res.json())statements. With
Axios, the server response is in the
dataattribute and we don't need to parse it. Therefore, we need to change the
.thenstatement to
.then(res => res.data).
API._handleErrormethod:
okboolean flag is missing, however, there is also a
statusTextattribute. We can string through it, and if its value is
OK, then everything will be fine (P.S.
OKis
inFetch API
trueis different from
statusTextin
Axioswhich is
OK, but for ease of understanding and not being too broad, no advanced information is introduced. Error handling.)
API.urlremains the same, we will catch errors and alert them in a pleasant way.
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); }); } };
Axios, you will find that there is a feature that does not apply to XMLHttpRequests (
Axios's method of getting data), but before using the
Fetch API's newer browsers work just fine. What should we do now?
我们的技术负责人说,让我们使用旧的API
实现这个特定的用例,并继续在其他地方使用Axios
。你该做什么?在源代码管理历史记录中找到旧的API
模块。还原。在这里和那里添加if
语句。这样听起来并不太友好。
必须有一个更容易,更易于维护和可扩展的方式来进行更改!那么,下面的就是。
重构的需求马上来了!让我们重新开始,我们不再删除代码,而是让我们在另一个抽象中移动Fetch
的特定逻辑,这将作为所有Fetch
特定的适配器(或包装器)。
HEY!???对于那些熟悉适配器模式(也被称为包装模式)的人来说,是的,那正是我们前进的方向!如果您对所有的细节感兴趣,请参阅这里我的介绍。
如下所示:
将跟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()); } };
重构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); }); } };
现在情况不一样了!这种结构能让你处理各种不同的获取数据的场景(适配器)改。最后一步,你猜对了!写一个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); } };
在API
模块中,将默认适配器改为AxiosAdapter
:
class API { constructor(_adapter = new /*FetchAdapter()*/ AxiosAdapter()) { this.adapter = _adapter; /* ... */ } /* ... */ };
真棒!如果我们需要在这个特定的用例中使用旧的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');
所以下次你需要改变你的项目时,评估下面哪种方法更有意义:
删除代码,编写代码。
重构代码,写适配器。
总结请根据你的场景选择性使用。如果你的代码库滥用适配器和引入太多的抽象可能会导致复杂性增加,这也是不好的。愉快的去使用适配器吧!
相关推荐:
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!