让我们拓展上一个例子让它包含两个条件。
1.如果没有传入参数 fruit,抛出错误
2.接受 quantity 参数,并且在 quantity 大于 10 时打印出来
function test(fruit, quantity) {
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
// 条件 1: fruit 必须有值
if (fruit) {
// 条件 2: 必须是red的
if (redFruits.includes(fruit)) {
console.log('red');
// 条件 3: quantity大于10
if (quantity > 10) {
console.log('big quantity');
}
}
} else {
throw new Error('No fruit!');
}
}
// 测试结果
test(null); // error: No fruits
test('apple'); // print: red
test('apple', 20); // print: red, big quantity
在上面的代码, 我们有:
- 1个 if/else 语句筛选出无效的语句
- 3层if嵌套语句 (条件 1, 2 & 3)
遵循的规则一般是在发现无效条件时,尽早Return。
/_ 当发现无效语句时,尽早Return _/
function test(fruit, quantity) {
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
// 条件 1: 尽早抛出错误
if (!fruit) throw new Error('No fruit!');
// 条件 2: 必须是红色的
if (redFruits.includes(fruit)) {
console.log('red');
// 条件 3: 必须是大质量的
if (quantity > 10) {
console.log('big quantity');
}
}
}
这样一来,我们少了一层嵌套语句。这种编码风格非常好,尤其是当你有很长的if语句的时候(想象你需要滚动到最底层才知道还有else语句,这并不酷)
我们可以通过 倒置判断条件 & 尽早return 进一步减少if嵌套。看下面我们是怎么处理判断 条件2 的:
/_ 当发现无效语句时,尽早Return _/
function test(fruit, quantity) {
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
// 条件 1: 尽早抛出错误
if (!fruit) throw new Error('No fruit!');
// 条件 2: 当水果不是红色时停止继续执行
if (!redFruits.includes(fruit)) return;
console.log('red');
// 条件 3: 必须是大质量的
if (quantity > 10) {
console.log('big quantity');
}
}
通过倒置判断条件2,我们的代码避免了嵌套语句。这个技巧在我们需要进行很长的逻辑判断时是非常有用的,特别是我们希望能够在条件不满足时能够停止下来进行处理。
而且这么做并不困难。问问自己,这个版本(没有嵌套)是不是比之前的(两层条件嵌套)更好,可读性更高?
但对于我,我会保留先前的版本(包含两层嵌套)。这是因为:
代码比较短且直接,包含if嵌套的更清晰
倒置判断条件可能加重思考的负担(增加认知载荷)
因此,应当尽力减少嵌套和尽早return,但不要过度。如果你感兴趣的话,可以看一下关于这个话题的一篇文章和 StackOverflow 上的讨论。
Avoid Else, Return Early by Tim Oxley
StackOverflow discussion on if/else coding style