Iterative scheme for adapting JavaScript abstractions
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:
Tips for making changes in a maintainable way
This method makes your revisions look more professional.
Let's start with a code example for the API
module. I chose this example because communicating with an external API
is one of the most basic abstractions I defined when starting the project. The idea here is to store all API
related configuration and settings (like base URL
, error handling logic, etc.) in this module.
I will write A setting API.url
, a private method API._handleError()
and a public method API.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 method API.get()
returns a Promise
. We use our abstracted API
module instead of calling Fetch API
directly through window.fetch()
. For example, get user information API.get('user')
or current weather forecast API.get('weather')
. The important thing about implementing this feature is that the Fetch 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 public
API In the .get()
method,
- ##needs to modify the
window.fetch()
call of
axios(); required Return a
Promiseagain to keep the interface consistent. Fortunately,
Axiosis based on
Promise, which is great!
- The server’s response is
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._handleError method:
- In response object The
ok
boolean 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.url remains 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);
});
}
};
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 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!???对于那些熟悉适配器模式(也被称为包装模式)的人来说,是的,那正是我们前进的方向!如果您对所有的细节感兴趣,请参阅这里我的介绍。
如下所示:
步骤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()); } };
步骤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); }); } };
现在情况不一样了!这种结构能让你处理各种不同的获取数据的场景(适配器)改。最后一步,你猜对了!写一个 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest
