Put contants and values on the left

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

Metadata

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

Language: Go

Severity: Info

Category: Best Practices

Description

The reason why we should write if something == 42 { } and not if 42 == something { } is to avoid a common programming mistake known as a “Yoda condition”.

A Yoda condition is when a conditional statement is written with the constant value on the left side of the equality comparison. This practice is named after the character Yoda from the Star Wars franchise, known for his distinctive way of speaking.

The purpose of writing if something == 42 { } rather than if 42 == something { } is to prevent accidental assignment instead of comparison.

In some programming languages, a single = operator is used for assignment, while a double == operator is used for comparison. By writing the variable or expression on the left side of the comparison, it helps catch potential mistakes if a single = is mistakenly used instead of == because the code won’t compile or an error will be thrown.

Moreover, most modern programming languages support compiler warnings or static analysis tools that can help identify these issues. By following this best practice of writing the variable or expression on the left side of the comparison, we can ensure cleaner and less error-prone code.

To summarize, writing if something == 42 { } instead of if 42 == something { } helps prevent accidental assignment and improve the readability and maintainability of the code.

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

PREVIEWING: esther/docs-9518-update-example-control-sensitive-log-data