JS代码优化浅谈

2021-03-12  本文已影响0人  Lisa_Guo

本文主要介绍一下如何让代码整洁可读的几点建议,总体是为了让代码逻辑及结构更加清晰,增加可读性。

一、命名
一切命名都要使其有意义

1 名字要自说明
变量、函数、类等的名称应当具备告诉你:它为什么存在、它做了什么事、应该怎么用、等。

【如果名称需要注释来说明,需考虑是否更换名字】

意义不够的变量命名,带来阅读的困难度

// 不清晰的变量命名
public List getThem() {
    List list1 = new Array();
    for(int[] x: theList) {
        if(x[0] == 4) {
            list1.add(x)
        }
    }
   return list1
}
// 有意义的变量命名
public List getFlaggedCells() {
    List flaggedCells = new Array()
    for(int[] cell: gameBorad){
        if(cell[STATUS_VALUE] == FLAGGED) {
            flaggedCells.add(cell)
        }
    }
    return flaggedCells
}
// 适当的封装提升逻辑清晰度
public List getFlaggedCells() {
    List flaggedCells = new Array()
    for(int[] cell: gameBorad){
        if(cell.isFlagged()) {  // 判断使用函数封装
            flaggedCells.add(cell)
        }
    }
    return flaggedCells
}

2 使用读得出来的名称
以一个记录日期的类为例,该类的变量记录不同的时间

// 修改前
class DatRcd02 {
     Date genymdhms
     Date modymdhms;
     String pazqint = '102'
}
 
// 修改后
class Customer {
 Date generationTimestamp;
 Date modificationTimestamp;
 String recordId = '102'
}

3 有意义的数字或字符串字面值,用枚举/常量/变量/函数封装

switch (userStatus){
     case 101:
     case 100:
     case 200:
}
 
// 封装后
const USER_STATUS = {
    LOGGED: 100,
    INVALID: 101,
    DELETED: 200,
}
// 使用
if(userStatus == USER_STATUS.LOGGED){}

4 类名或对象名应该是名词或名词短语
Customer, WikiPage, AddressParser

5 方法名应当是动词或动词短语
deletePage, getCustomerAddress

6 善用行业名词

二、函数

设计原则

  1. 短小
  2. 只做一件事
    3/ 描述功能的名字

逻辑原则
写代码像写文章一样,能顺利通畅的表达思路

  1. 自顶而下设计
    让代码读起来像是一系列自项向下的TO起头段落是保持抽象层级协调一致的有效技巧。


    image.png
  2. 函数内语句在同一个抽象层级上

function reloadData() {
    this.total = 0;
    this.name = '';
    this.tip: '';
  
    const responseData = await api.getOrders(this.userId)
    if(responseData){
        this.name = responseData.name
        this.tip = responseData.tip
        reponseData.list.forEach(order => this.total += order.total)
    }
}
 
// 抽象后
function reloadData() {
     this.resetData()
     this.loadData()
}
  
function resetData() {
  this.total = 0;
    this.name = '';
    this.tip: '';
}
  
funtion loadData() {
    const responseData = await api.getOrders(this.userId)
    if(responseData){
        this.name = responseData.name
        this.tip = responseData.tip
        reponseData.list.forEach(order => this.total += order.total)
    }
}

参考地址: 《代码整洁之道》

上一篇 下一篇

猜你喜欢

热点阅读