DEV Community

Cover image for Code Smell 195 - Yoda Conditions
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

6

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

  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

if (42 == answerToLifeMeaning) {
  // 
}
Enter fullscreen mode Exit fullscreen mode

Right

if (answerToLifeMeaning == 42) {
  // might be mistaken with answerToLifeMeaning = 42
}
Enter fullscreen mode Exit fullscreen mode

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

Photo by Lia on Unsplash


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

Marcus Cicero


This article is part of the CodeSmell Series.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay