Duplicate Branches

ID

csharp.duplicate_branches

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

CSharp

Tags

duplicate-code, reliability

Description

Reports an if / else if chain in which two branches have textually identical bodies. Two branches running the same code under different conditions is almost always a copy-paste mistake: either one of the bodies was intended to differ and the change was forgotten, or the branches should be merged into a single condition.

Rationale

A chain such as if (A) { X; } else if (B) { X; } collapses to if (A || B) { X; }. As written, the duplicated body suggests that the second body was meant to behave differently and a maintainer reading the chain will spend time looking for the difference that is not there. Either fix the diverging branch or fold the conditions together.

if (kind == Kind.A)                 // OK
{
    HandleA();
}
else if (kind == Kind.B)            // FLAW — body identical to the previous branch
{
    HandleA();
}
else                                // OK — distinct body
{
    HandleOther();
}

Remediation

Inspect every branch in the chain. If two branches really should do the same thing, merge them with ||. If they should differ, restore the missing behaviour in the duplicated branch.