Avoid Bare Return

ID

go.avoid_bare_return

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Code Smell

Language

Go

Tags

code-style, readability

Description

Reports a bare return (a return with no expressions) inside a function that declares named return values and is longer than a configurable line threshold (default 30). A bare return implicitly returns whatever the named result variables hold at that point.

Rationale

In a short function a bare return is idiomatic and easy to follow. In a long one the reader must scan the whole body to discover what is actually returned, and it is easy to leave a named result at its zero value by mistake. Returning the values explicitly documents the contract at every exit point and surfaces forgotten assignments.

// FLAW — long body, the reader cannot see what is returned here
func load(n int) (result int, err error) {
    // ... many lines ...
    return
}

// OK — short body, the named results are obvious
func small() (x int) {
    x = 1
    return
}

Remediation

Return the result values explicitly (return result, nil). If the function is genuinely large, consider splitting it so each part is short enough that a bare return is once again clear. Adjust the maxLines property to match your project standard.