Code Smell 195 - Yoda Conditions
Best is to put the expected value last, if conditions you want to write.

TL;DR: In a natural way, write your conditions.
Problems
Readability
The least surprise principle violation
Solutions
Write your conditions with the expected value as the second.
Name the variables accordingly.
Context
Most programmers write the variable or condition first and the test value second.
In fact, this is the correct order for assertions.
In some languages, this style is used to avoid accidental assignment instead of equality comparison, which can result in a logic error in the code.
Sample Code
Wrong
if (42 == answerToLifeMeaning) {
//
}
Right
if (answerToLifeMeaning == 42) {
// might be mistaken with answerToLifeMeaning = 42
}
Detection
[X] Semi-Automatic
We can check for constant values on the first side of the comparison.
Tags
- Readability
Conclusion
Reliable, direct, and clear be when conditions your writing.
Relations
Disclaimer
Code Smells are just my opinion.
Credits
Any man can make mistakes, but only an idiot persists in his error.
Marcus Cicero
This article is part of the CodeSmell Series.
About the author
I’m a senior software engineer loving clean code, and declarative designs. S.O.L.I.D. and agile methodologies fan.
Comments
Join the discussionI’ve always thought of Yoda conditions as a horrible practice, but, unfortunately, I still encounter those from time to time. Encountering those breaks code reading flow totally.
Code Smells
In this series, we will see several symptoms and situations that make us doubt the quality of our developments. We will present possible solutions. Most are just clues. They are no hard rules.





