Convert If To Switch

ID

go.convert_if_to_switch

Severity

low

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Go

Tags

code-smell, readability

Description

Reports an if / else if chain of three or more branches where every branch is an equality test (==) of the same subject against a different value.

Rationale

When several branches all compare one value against discrete constants, a tagged switch expresses the dispatch more compactly and makes both the single subject and its set of cases obvious at a glance. The if/else if ladder hides that structure behind repeated subject == fragments.

// Bad
if x == 1 {
	return "one"
} else if x == 2 {
	return "two"
} else if x == 3 {
	return "three"
}

// Good
switch x {
case 1:
	return "one"
case 2:
	return "two"
case 3:
	return "three"
}

Remediation

Rewrite the chain as a tagged switch over the shared subject, with one case per compared value.