Yoda Conditions

ID

go.yoda_conditions

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 "Yoda condition": an equality comparison (== or !=) whose left operand is a constant literal and whose right operand is not — for example if 42 == x or if "" == name.

Rationale

Putting the literal first is a habit carried over from languages where if (x = 42) is a real hazard. Go forbids assignment in a condition, so the idiomatic and more readable order is to put the value first: x == 42. Only equality comparisons are flagged; relational operators are left alone because flipping them changes the reading direction. A literal-vs-literal comparison and the already-idiomatic order are not flagged.

func fn(x int, name string) {
    if "" == name { // FLAW — flip to name == ""
    }
    if x == 42 { // OK — idiomatic order
    }
}

Remediation

Put the variable or expression on the left and the literal on the right.