oxc/branches-sharing-code

Disallow the same statements at the start or end of every branch of an if

has suggestions

When every branch of an if starts or ends with the same statements, that code runs no matter what the condition is. Repeating it hides what really differs between the branches, and a later edit can change one copy and miss the others.

The rule looks at an if that ends in an else, with any number of else if in between, where every branch is a block in braces. Without a final else, nothing is reported, because the code doesn't always run. Branches that are completely identical aren't reported either.

--fix-suggestions moves the statement out of the if when exactly one statement is shared.

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"oxc/branches-sharing-code" = "error" # or "warn"

Examples#

example.js1 problem
if (user.isAdmin) {
  showAdminMenu();
  render();
} else {
  showMenu();
  render();
}
example.jsNo problems
if (user.isAdmin) {
  showAdminMenu();
} else {
  showMenu();
}
render();

Shared code at the start is reported too:

example.js1 problem
if (format === "json") {
  const data = load(file);
  printJson(data);
} else if (format === "csv") {
  const data = load(file);
  printCsv(data);
} else {
  const data = load(file);
  printText(data);
}
example.jsNo problems
const data = load(file);
if (format === "json") {
  printJson(data);
} else if (format === "csv") {
  printCsv(data);
} else {
  printText(data);
}

When not to use it#

Moving a statement before the if makes it run before the condition is evaluated. If the condition has side effects or depends on what the statement changes, the repeated code might be what you want.