Duplicate βifβ branchesΒΆ
ID: go/duplicate-branches
Kind: problem
Security severity:
Severity: warning
Precision: very-high
Tags:
- quality
- reliability
- correctness
- external/cwe/cwe-561
Query suites:
- go-security-and-quality.qls
Click to see the query in the CodeQL repository
If the βthenβ and βelseβ branches of an βifβ statement are identical, this suggests a copy-paste error where the first branch was copied and then not properly adjusted.
RecommendationΒΆ
Examine the two branches to find out what operations were meant to perform. If both the branches and the conditions that they check are identical, then the second branch is duplicate code that can be deleted. If the branches are really meant to perform the same operations, it may be clearer to just have a single branch that checks the disjunction of both conditions.
ExampleΒΆ
The example below shows a buggy implementation of the absolute-value function which checks the sign of its argument, but then returns the same value regardless of the outcome of the check:
package main
func abs(x int) int {
if x >= 0 {
return x
} else {
return x
}
}
Clearly, the βelseβ branch should return -x
instead:
package main
func absGood(x int) int {
if x >= 0 {
return x
} else {
return -x
}
}
ReferencesΒΆ
The Go Programming Language Specification: If statements.
Common Weakness Enumeration: CWE-561.