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);
});
}
};
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 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!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools