JavaScript代码可读性的重要性
对于JavaScript开发者而言,编写出美观且易于阅读的源代码,不仅能让自身维护更加轻松,也能让后续接手的同事在协作过程中实现无缝衔接。
清理废弃代码与版本控制
切勿在源码中遗留大段被注释掉的旧代码。
这些历史代码应交由Git版本控制系统来管理,否则使用Git的意义便大打折扣。
// bad
// function add() {
// const a = b + c
// return a
// }
function add() {
return a + 1000
}
// good
function add() {
return a + 1000
}
代码格式与注释的最佳实践
应当根据逻辑结构进行适当的代码换行处理。
// bad
function a() {
const {
state_a,
state_b,
state_c
} = this.state
this.setState({state_a: state_a * 2})
return 'done'
}
// good
function a() {
const {
state_a,
state_b,
state_c
} = this.state
this.setState({state_a: state_a * 2})
return 'done'
}
适度添加注释以解释复杂逻辑,但切忌过度堆砌注释。
仅对关键代码段或需要特别警示的一行代码添加注释说明。
避免冗长啰嗦的注释,高质量的代码本身应具备自解释能力。
// bad
const a = 'a' // 这是a
const b = 'b' // 这是b
const c = 'c' // 这是c
// good
/**
* 申明变量
*/
const a = 'a'
const b = 'b'
const c = 'c'
代码组织与简洁性原则
将功能相似或命名相关的代码块归拢在一起,保持逻辑聚合。
// bad
function handleClick(arr) {
const a = 1
arr.map(e => e + a)
const b = 2
return arr.length + b
}
// good
function handleClick(arr) {
const a = 1
const b = 2
arr.map(e => e + a)
return arr.length + b
}
在不改变代码原有语义的前提下,遵循‘能省则省’的极简原则。
需时刻牢记JavaScript中函数是一等公民这一核心特性。
然而,若过度简化导致代码难以理解,则属于设计失败。
当可读性与简洁性发生冲突时,应始终优先选择可读性。
function add(a) {
return a + 1
}
function doSomething() {
}
// bad
arr.map(a => {
return add(a)
})
setTimeout(() => {
doSomething()
}, 1000)
// good
arr.map(add)
setTimeout(doSomething, 1000)
函数式编程与语法糖的使用
充分利用箭头函数简化匿名函数的定义。
// bad
const a = (v) => {
return v + 1
}
// good
const a = v => v + 1
// bad
const b = (v, i) => {
return {
v,
i
}
}
// good
const b = (v, i) => ({v, i})
// bad
const c = () => {
return (dispatch) => {
// doSomething
}
}
// good
const c = () => dispatch => {
// doSomething
}
尽早从对象中提取所需属性(React开发者对此深有体会)。
// bad
const a = this.props.prop_a + this.props.prop_b
this.props.fun()
// good
const {
prop_a,
prop_b,
fun
} = this.props
const a = prop_a + prop_b
fun()
灵活且合理地运用各类表达式以提升代码效率。
// bad
if (cb) {
cb()
}
// good
cb && cb()
// bad
if (a) {
return b
} else {
return c
}
// good
return a ? b : c
// bad
if (a) {
c = a
} else {
c = 'default'
}
// good
c = a || 'default'
采用链式调用风格处理连续的操作流程。
// bad
fetch(url).then(res => {
return res.json()
}).then(() => {
// doSomething
}).catch(e => {
})
// good
fetch(url)
.then(res => {
return res.json()
})
.then(() => {
// doSomething
})
.catch(e => {
})
代码布局与视觉优化
保持代码结构的纵向延伸,避免横向无限拉长。
当发现某行代码在文件中显得尤为突兀或过长时,应及时进行换行重构。
// bad
return handleClick(type, key, ref, self, source, props)
// good
return handleClick(
type,
key,
ref,
self,
source,
props
)
// bad
const a = this.props.prop_a === 'hello' ? world : null
// good
const a = this.props.prop_a === 'hello'
? world
: null