Boolean Compare With Literal
ID |
go.boolean_compare_with_literal |
Severity |
info |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Go |
Tags |
code-style, suspicious-comparison |
Description
Reports uses of == or != to compare a value against the boolean literals true or
false. Such comparisons are redundant: a boolean expression can be used directly or negated.
Rationale
if flag == true is just a wordier if flag, and if flag == false is if !flag. The extra
comparison adds noise without changing behaviour. In Go true and false are predeclared
identifiers, so the redundancy reads exactly like any other identifier comparison and is easy
to overlook. Using the boolean directly is shorter and clearer.
if flag == true { // FLAW — write: if flag
}
if flag != false { // FLAW — write: if flag
}
if true == flag { // FLAW — literal on the left
}
if flag { // OK — used directly
}
if x == y { // OK — not a boolean literal
}
Remediation
Use the boolean expression directly. Replace flag == true and flag != false with flag,
and replace flag == false and flag != true with !flag.