eslint/max-statements 风格
它的作用
强制限制函数中的语句数量。此规则确保函数不会超过指定的语句数量,从而促进编写更小、更专注的函数,使其更容易维护和理解。
为什么这是个问题?
有些人认为大函数是代码异味的表现。大函数往往执行过多操作,难以追踪其内部逻辑。此规则有助于避免编写过大的函数。
示例
以下是在默认配置 { "max": 10 } 下 错误 的代码示例:
js
function foo() {
const foo1 = 1;
const foo2 = 2;
const foo3 = 3;
const foo4 = 4;
const foo5 = 5;
const foo6 = 6;
const foo7 = 7;
const foo8 = 8;
const foo9 = 9;
const foo10 = 10;
const foo11 = 11; // 语句太多。
}
const bar = () => {
const foo1 = 1;
const foo2 = 2;
const foo3 = 3;
const foo4 = 4;
const foo5 = 5;
const foo6 = 6;
const foo7 = 7;
const foo8 = 8;
const foo9 = 9;
const foo10 = 10;
const foo11 = 11; // 语句太多。
};以下是在默认配置 { "max": 10 } 下 正确 的代码示例:
js
function foo() {
const foo1 = 1;
const foo2 = 2;
const foo3 = 3;
const foo4 = 4;
const foo5 = 5;
const foo6 = 6;
const foo7 = 7;
const foo8 = 8;
const foo9 = 9;
return function () {
// 10
// 内部函数中的语句不计入语句上限。
let bar;
let baz;
return 42;
};
}
const bar = () => {
const foo1 = 1;
const foo2 = 2;
const foo3 = 3;
const foo4 = 4;
const foo5 = 5;
const foo6 = 6;
const foo7 = 7;
const foo8 = 8;
const foo9 = 9;
return function () {
// 10
// 内部函数中的语句不计入语句上限。
let bar;
let baz;
return 42;
};
};请注意,此规则不适用于类的静态块,且静态块内的语句也不会计入外围函数的语句总数。
以下是在配置 { "max": 2 } 下 正确 的代码示例:
js
function foo() {
let one;
let two = class {
static {
let three;
let four;
let five;
if (six) {
let seven;
let eight;
let nine;
}
}
};
}以下是在配置 { "max": 10 }, { "ignoreTopLevelFunctions": true } 下额外的 正确 代码示例:
js
function foo() {
const foo1 = 1;
const foo2 = 2;
const foo3 = 3;
const foo4 = 4;
const foo5 = 5;
const foo6 = 6;
const foo7 = 7;
const foo8 = 8;
const foo9 = 9;
const foo10 = 10;
const foo11 = 11;
}配置
此规则接受一个包含以下属性的配置对象:
ignoreTopLevelFunctions
type: boolean
default: false
是否忽略顶层函数。
max
type: integer
default: 10
每函数允许的最大语句数。
如何使用
要通过配置文件或 CLI 启用 此规则,可以使用:
json
{
"rules": {
"max-statements": "error"
}
}bash
oxlint --deny max-statements