Put constants and values on the right

Cette page n'est pas encore disponible en français, sa traduction est en cours.
Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.

Metadata

ID: go-best-practices/avoid-yoda-conditions

Language: Go

Severity: Info

Category: Best Practices

Description

A “Yoda condition” is a notation style that places the constant or value on the left side of an equality check.

Standard notation:

if something == 42 { }

Yoda notation:

if 42 == something { }

This is sometimes used in interpreted programming languages to avoid the problem of accidental assignment. For example, in JavaScript, if (something = 42) assigns something to 42 instead of checking equality, and so using Yoda notation would throw a runtime error instead of introducing a logic error.

The Go compiler prevents this kind of mistake, so the more idiomatic standard notation should be preferred.

Non-Compliant Code Examples

func main() {
    if 51 == something {

    }

    if "myValue" == something {

    }

    if 0.0 == myValue && 0 == plop {

    }


    if 0.0 < myValue {
        
    }
}

Compliant Code Examples

func main() {
    if something == 51 {

    }

    if something == "myValue" {

    }

    if myValue == 0.0 && plop == 0 {

    }


    if 0.0 < myValue {
        
    }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis