mosaic101 / blog

my blog (keep running~~~)
https://github.com/mosaic101/blog/issues
39 stars 6 forks source link

代码规范的二三事 #11

Open mosaic101 opened 5 years ago

mosaic101 commented 5 years ago

1. 背景介绍

1.1. 程序员应该重视4点

1.1.1. 正确性

1.1.2. 可读性

1.1.3. 高效率

1.1.4. 幸福感

1.2. 错误代码示例

不借助工具的协助,很难在开发期间发现bug,这些低级bug(非逻辑)就应该在开发期间避免

1.2.1. DEMO_01:

// 转16进制
const conversionToString = str => {
    let strRes = ''
    if (str && str.replace(/^\s*|\s*$/,'') ! = '') {
        for (let i = 0, j = str.length; i < j; i++) {
        strRes += str.charCodeAt(i).toString(16)
        }
    }
    return strRes
}

bug说明: null ! = str 感叹号后面多了空格

1.2.2. DEMO_02:

async generateQrcode () {
    try {
      const result = await request({
        method: 'POST',
        url: `${host.mbpss}/mpbss-web/wx/generateQrcode.do`,
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          appid: 'mainApp',
          page: 'pages/fourth/fourth',
          sence,
          width: '120',
          suffix: 'png' || 'jpg'
        }
      })
      const data = JSON.parse(protocol(result.data))
      if (data && data.code === '0') return data.result // url
      throw new Error('fourth:request:generateQrcode')
    } catch (err) {
      err.code = 'E001-generateQrcode'
      throw err
    }
}

bug说明: sence 变量未申明

2. 代码规范

2.1. 什么是代码规范?

2.2. 为什么需要代码规范?

2.3. 主流代码规范标准

2.4. 代码规范点

2.4.1. ESLint

2.4.2. Standard

2.4.3. 如何使用 Standard

// 安装
使用本规范最便捷的方式是全局安装,运行:

$ npm install standard --global

或者非全局的方式,针对某个项目进行安装:

$ npm install standard --save-dev

或者利用 eslint 依赖 standard 标准

$ npm install eslint -g
$ eslint --init // 选择 standard

注意:运行以上命令的前提是已经安装了 Node.js 和 Npm

// 使用

运行任何一个文件或者文件夹:

$ eslint yourfile.js --fix

2.4.4. EditorConfig

2.4.5. EditorConfig 配置文件

indent_style    设置缩进风格(tab是硬缩进,space为软缩进)
indent_size     用一个整数定义的列数来设置缩进的宽度,如果indent_style为tab,则此属性默认为tab_width
tab_width       用一个整数来设置tab缩进的列数。默认是indent_size
end_of_line     设置换行符,值为lf、cr和crlf
charset         设置编码,值为latin1、utf-8、utf-8-bom、utf-16be和utf-16le,不建议使用utf-8-bom
trim_trailing_whitespace  设为true表示会去除换行行首的任意空白字符。
insert_final_newline      设为true表示使文件以一个空白行结尾
root           表示是最顶层的配置文件,发现设为true时,才会停止查找.editorconfig文件  

2.4.6. Editorconfig 使用案例

root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
trim_trailing_whitespace = true
insert_final_newline = true

2.4.7. JSDoc


3. 团队建设展望点

4. 总结

针对团队开发中代码规范列出了一些使用心得,程序员应该擅于用工具解决问题,避免低级bug。