Skip to content
← Back to rules

oxc/branches-sharing-code Pedantic

💡 A suggestion is available for this rule.

它的作用

检查 ifelse 代码块中是否包含可以移出这些代码块的共享代码。

为什么这不好?

重复代码的可维护性较差。从分支中提取公共代码可以使代码更加 DRY(不要重复自己) 并且更易于维护。

示例

以下是此规则的错误代码示例:

javascript
if (condition) {
  console.log("Hello");
  return 13;
} else {
  console.log("Hello");
  return 42;
}

if (condition) {
  doSomething();
  cleanup();
} else {
  doSomethingElse();
  cleanup();
}

以下是此规则的正确代码示例:

javascript
console.log("Hello");
if (condition) {
  return 13;
} else {
  return 42;
}

if (condition) {
  doSomething();
} else {
  doSomethingElse();
}
cleanup();

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "rules": {
    "oxc/branches-sharing-code": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "oxc/branches-sharing-code": "error",
  },
});
bash
oxlint --deny oxc/branches-sharing-code

版本

此规则在 v1.22.0 中加入。

参考资料