Redundant Nil Check
ID |
go.redundant_nil_check |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Code Smell |
Language |
Go |
Tags |
code-style, readability |
Description
Reports the redundant nil-guard-around-a-return shape
if x != nil { return x } else { return nil } (and its else-less twin
if x != nil { return x } return nil). The whole construct collapses to a single return x.
Rationale
When the value being checked is exactly what the non-nil branch returns and the other branch
returns the same nil the check tests for, the guard decides nothing: returning x directly has
the identical result because x already holds nil in the false case. Collapsing the construct to
return x removes a branch and a level of nesting.
This rule covers only the return-collapse shape. The nil-check-before-range shape
(if s != nil { for _, v := range s {…} }) is handled by go.omit_redundant_nil_check.
if err != nil { // FLAW — collapses to: return err
return err
} else {
return nil
}
if err != nil { // FLAW — collapses to: return err
return err
}
return nil