发布于 2026-01-06 1 阅读
0

最重要的 ESLint 规则:max-params

最重要的 ESLint 规则:max-params

请问:你认为这段代码的作用是什么?

resizeImage(imagePath, 300, 200, true, true, 1)
Enter fullscreen mode Exit fullscreen mode

它可以调整图像大小……但它具体做了什么呢?大多数情况下,我们不查阅函数定义就无法得知。

假设您正在审核一个 PR,其中包含以下更改:

-resizeImage(imagePath, 300, 200, true, true, 1)
+resizeImage(imagePath, 300, 200, false, true, 1)
Enter fullscreen mode Exit fullscreen mode

你能自信地说出这项改变的影响是什么吗?大多数情况下……不能。你需要了解每一种立场性论点的作用。

假设你知道界面是这样的:

function resizeImage(
  imagePath: string,
  width: number,
  height: number,
  upscale: boolean,
  crop: boolean,
  quality: number,
): Promise<Buffer>
Enter fullscreen mode Exit fullscreen mode

但现在,一个 PR 引入了参数顺序的更改(例如,为了与其他函数保持一致):

function resizeImage(
  imagePath: string,
  width: number,
  height: number,
+  crop: boolean,
  upscale: boolean,
-  crop: boolean,
  quality: number,
): Promise<Buffer>
Enter fullscreen mode Exit fullscreen mode

如何审查这项变更?当然,审查接口差异很容易,但是对于更新函数调用的几十甚至几百个差异该怎么办?

-resizeImage(imagePath, 300, 200, true, false, 1)
+resizeImage(imagePath, 300, 200, false, true, 1)
resizeImage(imagePath, 300, 200, false, false, 1)
-resizeImage(imagePath, 300, 200, false, true, 1)
+resizeImage(imagePath, 300, 200, false, false, 1)
-resizeImage(imagePath, 300, 200, true, false, 1)
+resizeImage(imagePath, 300, 200, false, true, 1)
Enter fullscreen mode Exit fullscreen mode

希望问题不言自明:位置参数容易滋生难以发现、调试甚至修复的错误,尤其是在需要重构代码的时候。不过别担心,还有更好的办法。

让我们从头开始,但这次使用单对象参数:

resizeImage({
  imagePath,
  width: 300,
  height: 200,
  upscale: true,
  crop: false,
  quality: 1,
})
Enter fullscreen mode Exit fullscreen mode

你能看出这段代码背后的意图吗?是的,即使你不熟悉具体的实现方式,也能大致理解。

你可以轻松地重构接口吗?是的,如果接口不符合约定,代码检查工具会发出警告。

我们最终选择使用位置参数,是因为它们看起来最自然。然而,随着函数作用域的扩大,原本只有一两个参数的简单函数会变得难以阅读。

这时max-paramsESLint 就派上用场了。只需添加一条 ESLint 规则,限制函数参数数量不超过 X 个,就能确保代码保持清晰易读,并且随着代码库规模的扩大,也便于重构。

文章来源:https://dev.to/gajus/the-most-important-eslint-rule-max-params-349l