Put constants and values on the right
このページは日本語には対応しておりません。随時翻訳に取り組んでいます。
翻訳に関してご質問やご意見ございましたら、
お気軽にご連絡ください。
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:
Yoda notation:
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 {
}
}