- 필수 기능
- 시작하기
- Glossary
- 표준 속성
- Guides
- Agent
- 통합
- 개방형텔레메트리
- 개발자
- API
- Datadog Mobile App
- CoScreen
- Cloudcraft
- 앱 내
- 서비스 관리
- 인프라스트럭처
- 애플리케이션 성능
- APM
- Continuous Profiler
- 스팬 시각화
- 데이터 스트림 모니터링
- 데이터 작업 모니터링
- 디지털 경험
- 소프트웨어 제공
- 보안
- AI Observability
- 로그 관리
- 관리
ID: go-best-practices/avoid-yoda-conditions
Language: Go
Severity: Info
Category: Best Practices
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.
func main() {
if 51 == something {
}
if "myValue" == something {
}
if 0.0 == myValue && 0 == plop {
}
if 0.0 < myValue {
}
}
func main() {
if something == 51 {
}
if something == "myValue" {
}
if myValue == 0.0 && plop == 0 {
}
if 0.0 < myValue {
}
}