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:
[lint.rules]
"oxc/branches-sharing-code" = "error" # or "warn"
Examples
Reported:
if (user.isAdmin) {
showAdminMenu();
render();
} else {
showMenu();
render();
}
Not reported:
if (user.isAdmin) {
showAdminMenu();
} else {
showMenu();
}
render();
Shared code at the start is reported too:
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);
}
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.