Put contants and values on the left

This page is not yet available in Spanish. We are working on its translation.
If you have any questions or feedback about our current translation project, feel free to reach out to us!

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: rtrieu/product-analytics-ui-changes