# Code Smell 195 - Yoda Conditions

            
> TL;DR: In a natural way, write your conditions.

# Problems

- Readability

- The least surprise principle violation

# Solutions

1. Write your conditions with the expected value as the second.

2. 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

[Gist Url]: # (https://gist.github.com/mcsee/530570169b351c8d411c310d9a182d1a)
```javascript
if (42 == answerToLifeMeaning) {
  // 
}
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/3a59fd09423eef0bbc5ab7857d041309)
```javascript
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

%[https://maximilianocontieri.com/code-smell-99-first-second]

# Disclaimer

Code Smells are just my [opinion](https://maximilianocontieri.com/i-wrote-more-than-90-articles-on-2021-here-is-what-i-learned).

# Credits

Photo by [Lia](https://unsplash.com/@liaphotography) on [Unsplash](https://unsplash.com/photos/2Wc_wz2k1Bs)  
  
* * *

> Any man can make mistakes, but only an idiot persists in his error.

_Marcus Cicero_

%[https://maximilianocontieri.com/software-engineering-great-quotes]

* * *

This article is part of the CodeSmell Series.

%[https://maximilianocontieri.com/how-to-find-the-stinky-parts-of-your-code]
