闽公网安备 35020302035485号
.使用行业/团队范式命名。加上像is、has、can 或should这样的词,让布尔值变得更明确。类或者构造函数首字母大写。
// 好的变量命名方式 var maxCount = 10; var tableTitle = 'LoginTable'; // 不好的变量命名方式 var setCount = 10; var getTitle = 'LoginTable';2).函数命名规范
|
动词 |
含义 |
返回值 |
|
can |
判断是否可执行某个动作 |
函数返回一个布尔值。true:可执行;false:不可执行 |
|
has |
判断是否含有某个值 |
函数返回一个布尔值。true:含有此值;false:不含有此值 |
|
get |
获取某个值 |
函数返回一个非布尔值 |
|
set |
设置某个值 |
无返回值、返回是否设置成功或者返回链式对象 |
|
load/query |
加载某些数据 |
无返回值或者返回是否加载完成的结果 |
|
save/update |
保存或修改某些数据 |
无返回值或者返回是否操作成功的结果 |
// 好的函数命名方式
function queryProductList() {
// ...
}
// 不好的函数命名方式
function productList() {
// ...
}
3).常量命名规范// 好的常量命名方式 const MAX_IMAGE_SIZE = 10 * 1024 * 1024; // 堆代码 duidaima.com // 不好的常量命名方式 const MaxImageSize = 10 * 1024 * 1024; const maximagesize = 10 * 1024 * 1024; const maxImageSize = 10 * 1024 * 1024;4).类或构造函数命名规范
// 构造函数名
function Student(name) {
var _name = name; // 私有成员
// 公共方法
this.getName = function () {
return _name;
}
// 公共方法
this.setName = function (value) {
_name = value;
}
}
2.2 恰如其分的注释// 不好的 // 删除表格中指定id的订单数据 delete(id) 应该把名字改好 // 好的 deleteOrderItemById(id)声明高层次的意图而非细节。不要描述显而易见的现象,永远不要用自然语言翻译代码,而应当解释代码为什么要这么做,或者是为了让代码文档化。比如 为接口提供功能说明,为复杂的实现提供逻辑说明,以阐述为什么是这样而不是那样,标注代码中的缺陷,解释读者意料之外的行为等。
// 不好的
// 这是 Account类 的定义
class Account {
// 给 profile 赋予新的值
setProfile(profile);
}
说明背后为什么是它,而不是其他写法// 好的 // 权衡图片大小/质量,图片质量设置的最佳值为0.72 image_quality =0.72;公布可能得陷阱,提供总结性注释。难免在实现中引入hack代码或考虑但未处理的边界场景,此时应为后来者显示标注,以便后续回溯和修复。在大块长函数前,总结其用途和用法。
// 不推荐
var active = true; // is current tab
// 推荐
// is current tab
var active = true;
// 不推荐
function getType() {
console.log('fetching type...');
// set the default type to 'no type'
var type = this.type || 'no type';
return type;
}
// 推荐
function getType() {
console.log('fetching type...');
// set the default type to 'no type'
var type = this.type || 'no type';
return type;
}
使用 /** ... */ 作为多行注释,包含描述、指定所有参数和返回值的类型和值。若开始 /* 和结束 */ 都在一行,【应该】采用单行注释。若至少三行注释时,【应该】第一行为 /*,最后行为 */,其他行以 * 开始,并且注释文字与 * 保留一个空格。// make() returns a new element
// based on the passed in tag name
//
// @param {String} tag
// @return {Element} element
function make(tag) {
// ...stuff...
return element;
}
推荐/**
* make() returns a new element
* based on the passed in tag name
*
* @param {String} tag
* @return {Element} element
*/
function make(tag) {
// ...stuff...
return element;
}
推荐/**
* merge cells
* @param grid {Ext.Grid.Panel} Grid that needs to be merged
* @param cols {Array} Index array that need to be merged; counting from 0.
* @return void
* @author ben 2021/11/11
* @example
* _________________ _________________
* | age | name | | age | name |
* ----------------- mergeCells(grid,[0]) -----------------
* | 18 | jack | => | | jack |
* ----------------- - 18 ---------
* | 18 | tony | | | tony |
* ----------------- -----------------
*/
function mergeCells(grid: Ext.Grid.Panel, cols: Number[]) {
// Do Something
}
使用 // @TODO 标注问题及问题的解决方式;function Calculator() {
// @TODO: total should be configurable by an options param
this.total = 0;
return this;
}
2.3 合理地组织代码// 不好的 if (10 <= length) // 好的 if (length >= 10)2).优先处理条件为true的逻辑、简单的情况、有趣和可疑的情况
fs.readFile('/file-does-not-exist', (err, data) => {
if (err) {
// 优先处理error
} else {
// 其次处理data
}
})
3).通过提早返回来减少嵌套if (user_result == 'SUCCESS') {
if (permission_result != 'SUCCESS') {
// 成功且有权限时,逻辑处理
return
}
// 成功且无权限时,逻辑处理
}else{
// 用户操作失败时,逻辑处理
}
if (user_result != 'SUCCESS') {
// 用户操作失败时,逻辑处理
return
}
if (permission_result != 'SUCCESS') {
// 成功且无权限时,逻辑处理
return
}
// 成功且有权限时,逻辑处理
4).拆分过长的表达式// 嵌套过深的运算符
mode === 'multi' ? hasSelectedAll ? '已选中所有项' : '未选中所有项' : mode === 'single' ? '仅可单选' : null
if (
state === 'INIT' && sign_state === ''
|| state === 'CHECKING' && sign_state === 'NOT_SIGNABLE'
|| state === 'AUDITING' && sign_state === 'SIGNED'
) {
return '此状态下返回的文案'
}
使用易懂的临时变量,或封装成函数if (request.user.id == document.owner_id){
// 用户有编辑权限时,逻辑处理
}
const user_owns_document = (request.user.id = document.owner_id)
5).别引入无谓的变量,减小变量的作用域const now = Data.now() const isCurrent = timestamp === now缩小变量的作用域,让你的变量对尽量少的代码可见,防止命名空间污染。
const name = 'foo'
function getUserName () {
const name = 'bar'
return name
}
只写一次的变量更好,不断变化的值让人难以理解,跟踪这种变量的值很有难度,善用typescript与const。if (response.data.user.status === 1) {
// 逻辑处理
} else if (response.data.user.status === 2) {
// 逻辑处理
} else if (response.data.user.status === 3) {
// 逻辑处理
} else {
// 逻辑处理
}
const status = response.data.user.status;
enum STATUS_MAP {
PROCESSING = 1,
ACTICATED = 2,
DISABLED = 3
}
switch (status) {
case STATUS_MAP.PROCESSING:
// 逻辑处理
break;
case STATUS_MAP.ACTICATED:
// 逻辑处理
break;
case STATUS_MAP.DISABLED:
// 逻辑处理
break;
default:
// 逻辑处理
break;
}
提取重复且通用的函数,以提供更好的可读性、可维护性、及复用的可能。一段代码一次只做一件事,可以通过拆分为段落/函数/类,让其更清晰。function errorHandler(error) {
alert('服务器繁忙,请稍后再试')
log('axios response err', error)
}
async function getUser() {
try {
const response = await axios.get('/user?ID=12345')
console.log(response)
} catch (error) {
errorHandler(error)
}
}
组件的封装,遵循物料规范封装。