Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to make JS code more elegant and maintainable

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the knowledge about "how JS code becomes more elegant and maintainable". In the actual case operation process, many people will encounter such difficulties. Next, let Xiaobian lead you to learn how to deal with these situations! I hope you can read carefully and learn something!

semantic

The first is semantics. A semanticization of variables, constants, for example:

const SUCCESS_STATUS = 200; const requestStatus = await getStatus(); console.log(requestStatus === SUCCESS_STATUS); const userRole = await getUserRole(); const GUEST_CODE = 0; const USER_CODE = 1; const ADMIN_CODE = 2; if (userRole === GUEST_CODE) { } else if (userRole === USER_CODE) { } else if (userRole === ADMIN_CODE) {}; const MAX_NUM = 10; const MIN_NUM = 0; for (let currentNum = MIN_NUM; currentNum

< MAX_NUM; currentNum++) {}; 一般的规则就是变量用小写,常量用大写,把变量名语义化,那么当你看到这段代码的时候,一眼就能知道它是做什么的,而不是非得要浪费时间看完上下文,或者是猜。 枚举 对于上面判断 userRole 的代码,其实我们可以用更优雅的方式去实现,那就是 枚举 。 按照维基百科的说明:在数学和计算机科学理论中,一个集的枚举是列出某些有穷序列集的所有成员的程序,或者是一种特定类型对象的计数。这两种类型经常(但不总是)重叠。 其实就是组织收集有关联变量的一种方式。枚举的好处在于方便多状态的管理,以及可读性更强。例如: const ROLES = { GUEST: 0, USER: 1, ADMIN: 2 }; const userRole = await getUserRole(); if (userRole === ROLES.GUEST) { } else if (userRole === ROLES.USER) { } else if (userRole === ROLES.ADMIN) {}; 通过枚举的方式归纳起来,维护起来更方便,而且要添加状态直接在 ROLES 对象里写就行,更方便快捷。 策略模式 维基百科上说:策略模式作为一种软件设计模式,指对象有某个行为,但是在不同的场景中,该行为有不同的实现算法。 上面的代码依旧是可优化的,在这里我们可以利用策略模式来做进一层的优化。 具体的例子就是如下: const ROLES = { GUEST: 0, USER: 1, ADMIN: 2 }; const ROLE_METHODS = { [ROLES.GUEST]() {}, [ROLES.USER]() {}, [ROLES.ADMIN]() {}, }; const userRole = await getUserRole(); ROLE_METHODS[userRole](); 通过上面的写法,我们可以知道,当我们需要增加角色,或者修改角色数字的时候,只需要修改 ROLES 里对应的字段,以及 ROLE_METHODS 里的方法即可,这样我们就可以将可能很冗长的 if...else 代码给抽离出来,颗粒度更细,更好维护。 更在状态 除了上面的方式之外,我们还可以利用" 状态 "的概念来写代码。在看代码之前,我们先了解下什么是 "有限状态机"。 根据维基百科的解释:有限状态机(英语:finite-state machine,缩写:FSM)又称有限状态自动机(英语:finite-state automation,缩写:FSA),简称状态机,是表示有限个状态以及在这些状态之间的转移和动作等行为的数学计算模型。 例如我们熟悉的 Promise ,它就是在状态集:PENDIN 、 FULFILLED 、 REJECTED 之间单向流转的有限状态机。 状态机的概念跟策略模式类似,实现方式也类似,这里面最大的不同是在于 "语义" 。 策略模式更适合于互不依赖,同时只能存在一个状态的场景,例如: const 吃 = { 沙县大酒店() { 吃云吞() }, 开封菜() { 吃汉堡() }, 在家() { 吃外卖() } }; 这里面如果我们肚子饿了,就只能在 沙县大酒店() , 开封菜() , 在家() 这几个状态里选。 你不能都吃,当然以下情况除外。。。 如果是状态模式,则会有这种情况: const 打工人 = { 起床() {}, 上班() {}, 加班() {}, 下班() {} }; // 早上6点 打工人.起床(); // 早上9点 打工人.上班(); // 晚上6点 打工人.加班(); // 晚上12点 打工人.下班(); 这里的打工人根据不同的时间,进行不同的任务,便是打工人模式,哦不,状态模式。这里的时间就是状态。 我们举个实际的业务例子,就是订单列表页,通常我们的订单可能有这几种状态:

不同的状态展示的 UI 也不同,所以我们以不同的状态划分好模块之后,代码写起来就会清晰很多,我们以 Vue 代码为例:

// contants.js export const ORDER_STATUS = { INIT: 0, // 初始化 CREATED: 1, // 订单创建 ARREARAGE: 2, // 待支付 PURCHASED: 3, // 已购买 SHIPPED: 4, // 已发货 COMPLETED: 5 // 已完成 };// order.vue import ORDER_STATUS from './contants'; import eq from 'lodash'; export default { computed: { /** * @func * @name orderIsInit * @desc 判断订单是否初始化的状态 * @returns {string} 判断订单是否初始化的状态 */ orderIsInit() { return eq(this.orderStatus, ORDER_STATUS.INIT); }, /** * @func * @name orderIsCreated * @desc 判断订单是否已创建的状态 * @returns {string} 订单是否已创建 */ orderIsCreated() { return eq(this.orderStatus, ORDER_STATUS.CREATED); }, /** * @func * @name orderIsArrearage * @desc 判断订单是否未付款的状态 * @returns {string} 订单是否未付款 */ orderIsArrearage() { return eq(this.orderStatus, ORDER_STATUS.ARREARAGE); }, /** * @func * @name orderIsPurchased * @desc 判断订单是否已购买的状态 * @returns {string} 订单是否已购买 */ orderIsPurchased() { return eq(this.orderStatus, ORDER_STATUS.PURCHASED); }, /** * @func * @name orderIsShipped * @desc 判断订单是否已发货的状态 * @returns {string} 订单是否已发货 */ orderIsShipped() { return eq(this.orderStatus, ORDER_STATUS.SHIPPED); }, /** * @func * @name orderIsCompleted * @desc 判断订单是否已完成的状态 * @returns {string} 订单是否已完成 */ orderIsCompleted() { return eq(this.orderStatus, ORDER_STATUS.COMPLETED); }, }, data() { return { orderStatus: ORDER_STATUS.INIT // 订单状态 } }, methods: { /** * @func * @name getOrderStatus * @desc 判断订单状态 * @returns {string} 返回当前订单状态 */ async getOrderStatus() {} }, async created() { this.orderStatus = await this.getOrderStatus(); } }

将页面组件按状态划分,实现独立自治,这样子既能防止代码耦合,方便维护 debug,也方便开发者自测,如果需要看不同状态的展示效果,只要手动给 orderStatus 赋值即可,方便快捷。

面向切面

按照维基百科的解释:面向切面的程序设计(Aspect-oriented programming,AOP,又译作面向方面的程序设计、剖面导向程序设计)是计算机科学中的一种程序设计思想,旨在将横切关注点与业务主体进行进一步分离,以提高程序代码的模块化程度。

上面这段文字估计没有什么人看,算了,直接上代码吧

Let's go back to the above scene of the worker. Suppose the boss wants to know the time before and after each state of the worker and what to do. So what should he do? At this time, it is not difficult to think of writing code directly into the state function, for example:

const worker = { Wake up () { .start(); .do(); . end(); }, Work () { .start(); .do(); . end(); }, Overtime () { .start(); .do(); . end(); }, Off duty () { .start(); .do(); . end(); } }; //6:00 am workers. Get up (); //9 am working people. Work (); //6 p.m. workers. Overtime (); //12 p.m. worker. Off duty ();

But such workers suddenly aware of the boss in monitoring his life, if you want to be undetected (does not affect business logic), then we can use AOP implementation. The code is as follows:

import eq from 'lodash'; const TYPES = { FUNCTION: 'function' } const Employee in boss monitoring = new Proxy(Employee, { get(target, key, value, receiver) { console.log ('The boss is starting to look at you ~'); const res = Reflect.get(target, key, value, receiver); const Worker Task = eq(typeof res, TYPES.FUNCTION) ? res() : res; console.log ('The boss started memorizing your small book'); return () => Worker Quest; } });

So we can see the following results:

"How to make JS code more elegant and maintainable" content introduced here, thank you for reading. If you want to know more about industry-related knowledge, you can pay attention to the website. Xiaobian will output more high-quality practical articles for everyone!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report