JavaScript 可读性
1.日志级别和语义方法
console.log("hello world")
console.warn("this is a warning")
console.error("this is an error")
console.info("this is info")
console.debug("this is debug")
console.trace("show trace")
//原代码:
console.log("Error: API key should not be empty")
//改进后的代码:
console.error("Error: API key should not be empty")
- 避免对布尔变量使用否定意义的名称
原代码:
const isInvalidApiKey = apiKey === null
if (isInvalidApiKey) {}
//改进后
const isValidApiKey = apiKey != null
if (!isValidApiKey) {}
- 避免使用标记位参数 原代码:
renderResult(true)
function renderResult(isAuthenticated) {
if (isAuthenticated) {
return <p>App</p>
} else {
return <p>Please login</p>
}
}
使用对象参数:
renderResult({isAuthenticated: true})
function renderResult({isAuthenticated}) {
if (isAuthenticated) {
return <p>App</p>
} else {
return <p>Please login</p>
}
}
使用2个函数:
function renderAuthenticatedApp() {
return <p>App</p>
}
function renderUnAuthenticatedApp() {
return <p>Please login</p>
}
isAuthenticated ? renderAuthenticatedApp() : renderUnAuthenticatedApp()
- 使用卫语句
if (statusCode === 200) {
// success
} else {
if (statusCode === 500) {
// Internal Server Error
} else if (statusCode === 400) {
// Not Found
} else {
// Other error
}
}
//使用卫语句改进后:
if (statusCode === 500) {
// Internal Server Error
}
if (statusCode === 400) {
// Not Found
}
if (statusCode !== 200) {
// Other error
}
// success
- 让代码一目了然
例如:
// verify that user has added a credit card
function verify(user) {}
//改进后
function verifyThatUserHasAddedCreditCard(user) {}
if (country !== 'finland' &&
country !== 'germany' &&
country !== 'vietnam' &&
country !== 'russia'
) {
return Promise.reject('Not available')
}
//改进后
const isInAvailableCountries = (
country === 'finland' ||
country === 'germany' ||
country === 'vietnam' ||
country === 'russia'
)
if (!isInAvailableCountries || hasBoom) {
return Promise.reject('Not available')
}
- 不可能的状态就让它不可能
例如:
isLoading: true
isError: false
isLoading: false
isError: true
// imposible states
isLoading: true
isError: true
//改进后:
const LOADING_STATE = 'LOADING_STATE'
const ERROR_STATE = 'ERROR_STATE'
const state = LOADING_STATE
再看一个例子:
const [isLoading, setIsLoading] = React.useState(false)
const [error, setError] = React.useState(null)
const [coffee, setCoffee] = React.useState(null)
function handleButtonClick() {
setIsLoading(true)
setError(null)
setCoffee(null)
getCoffee('cappuccino', 'small', 'finland', true).then(coffee => {
setIsLoading(false)
setError(null)
setCoffee(coffee)
}).catch(error => {
setIsLoading(false)
setError(error)
})
}
//改进后:
const state = {
idle: 'idle',
loading: 'loading',
error: 'error',
success: 'success',
}
const [error, setError] = React.useState(null)
const [coffee, setCoffee] = React.useState(null)
const [status, setStatus] = React.useState(state.idle)
function handleButtonClick() {
setStatus(state.loading)
getCoffee('cappuccino', 'small', 'finland', true).then(coffee => {
setStatus(state.success)
setCoffee(coffee)
}).catch(error => {
setStatus(state.error)
setError(error)
})
}
7.参数个数太多,可以用对象代替
例如:
function getBox(type, size, price, color) {}
getBox('carry', undefined, 10, 'red')
//改进后:
function getBox(options) {
const {type, size, price, color} = options
}
getBox({
type: 'carry',
price: 10,
color: 'red'
})
- 使用Object.assign赋默认值 例如:
function getBox(options) {
options.type = options.type || 'carry'
options.size = options.size || 'small'
options.price = options.price || 10
options.color = options.color || 'red'
const {type, size, price, color} = options
}
//改进后:
function getBox(customOptions) {
const defaults = {
type: 'carry',
size: 'small',
price: 10,
color: 'red',
}
const options = Object.assign(defaults, customOptions)
const {type, size, price, color} = options
}
原代码:
export function getCoffee(type, size, country, hasIce) {
type = type || 'cappuccino'
size = size || 'small'
country = country || 'finland'
hasIce = hasIce || false
}
可以用以下3个方法改进:
function getCoffee(customOptions) {
const defaultOptions = {
type: 'cappuccino',
size: 'small',
country: 'finland',
hasIce: false
}
const options = Object.assign(defaultOptions, customOptions)
}
function getCoffee(options = {}) {
const {
type = 'cappuccino',
size = 'small',
country = 'finland',
hasIce = false
} = options
}
function getCoffee({
type = 'cappuccino',
size = 'small',
country = 'finland',
hasIce = false
} = {}) {
}
- 用对象字面量替换switch语句
例如:
let drink
switch(type) {
case 'cappuccino':
drink = 'Cappuccino';
break;
case 'flatWhite':
drink = 'Flat White';
break;
case 'espresso':
drink = 'Espresso';
break;
default:
drink = 'Unknown drink';
}
//改进为:
const menu = {
'cappuccino': 'Cappuccino',
'flatWhite': 'Flat White',
'espresso': 'Espresso',
'default': 'Unknown drink'
}
const drink = menu[type] || menu['default']