Merge Conditional Assignment

ID

go.merge_conditional_assignment

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Code Smell

Language

Go

Tags

CWE:1164, code-style, readability

Description

Reports a boolean variable given an initial literal value and then conditionally overwritten with the other literal in a following if.

Rationale

The pair collapses to a single assignment from the condition itself, which states the intent directly and removes the duplicated variable name. The two literals must differ; when both are the same the conditional is a different concern and is left alone, as are forms with an else, an extra body statement, or an assignment to a different variable.

func fn(cond bool) {
    x := false // FLAW — collapse to x := cond
    if cond {
        x = true
    }
    _ = x
}

Remediation

Replace the declaration and if with x := <condition> (or x := !<condition> when the initial value was true).