Put constants and values on the right

이 페이지는 아직 한국어로 제공되지 않으며 번역 작업 중입니다. 번역에 관한 질문이나 의견이 있으시면 언제든지 저희에게 연락해 주십시오.

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