As a programmer, typos are part of your daily workflow. Problems arise though when the typo is proper syntax and neither the IDE nor interpreter alert you to it. Unexpected behavior will happen if it is not fixed. For one specific typo, the Yoda conditions programming style seeks to remedy this problem.
In this article, Tonya explains the Yoda conditions programming style. She discusses its intent and the problem it seeks to solve. A handy guide and litmus test are included to help you decide when to use it in your programs. Both PHP and JavaScript examples are provided to test your knowledge.
Introduction
A question I’m asked frequently is: “When and why should I format code using the Yoda conditions?” Like everything in software, a deep understanding of it and what problem it seeks to solve will help you know when to implement it. And in case confusion arises, this article includes a handy guide and litmus test to help you decide.
What is covered in this discussion:
- The What
- The Why
- The When – To Yoda or Not to Yoda?
- The Handy Guide
- Bad Practices and Myths
- The Where – Popularity
- The Critics
- The Alternatives
The What
The Yoda conditions programming style (or “Yoda notation”) inverts the variable and constant, literal, or function in an equality conditional expression.
Typical conditional structure
if ( $post_type == 'post' ) { // do stuff }
Yoda conditions
if ( 'post' == $post_type ) { // do stuff }
The Why
Why would you want to invert the operands? What purpose does it serve? What is its intent?
The Yoda conditions programming style’s intent is to avoid unexpected behavior. It does so by forcing a syntax error when the programmer makes a typo by using an assignment operator (
=
) when s/he meant to do an equality operator.
The Typo in Action
Let’s take a look at what happens with the typical structure when an assignment typo occurs. Consider the following code. What happens when this function is called?
// this is a typo, since it should be '==' and not '=' if ( $post_type = 'post' ) { // do stuff }
When the code runs, here is the execution:
- Line 2 – The value
'post'
is assigned to the variable$post_type
. - Line 2 – The
if
evaluates to true. - Line 3 – The code within the code block executes.
Why is this a bad thing? Think about it. The function’s behavior is now unexpected. Why? The intention was for the function to evaluate if the $post_type
is a 'post'
. Instead, we mistakenly assign the value of 'post'
to the $post_type
when we use =
instead of ==
. This changes the intended behavior of the function and causes the if
block to execute every time.
Quality code alert: Code should always be repeatable and perform as intended.The programmer did not intend for the code inside of the if
block to execute when the post type is not a post.
Unexpected behavior is a bad thing in programming. Code should always be repeatable and perform as intended. For example, if you use is_array()
, then you expect it to tell you if the variable is an array or not. You expect it to be right every time you run it. If it tells you that a variable is an array when it’s not, your code will potentially fail.
The When – To Yoda or Not to Yoda?
When should you use Yoda conditions? What is the litmus test?
Remember, this programming style only serves one purpose and intent: to catch an assignment when you mean to do a comparison. You only use it when there is a chance of a variable accidentally being assigned a new value. That’s it.
Litmus test – use it when a mistake could mean changing the variable’s value.Therefore, the litmus test for determining whether to use Yoda conditions or not is: use it when a mistake could mean changing the variable’s value.
Let’s Test Your New Knowledge
Let’s test your new knowledge and see if you can select when to use Yoda conditions. Look at each example code snippet and think about how it executes. Then, decide if it should or should not use Yoda conditions.
Example 1
Should this conditional expression use Yoda conditions? Look at the code and think about how it executes.
if ( get_post_type() == 'post' ) { // do stuff }
-
Answer
Example 2
For the given code, should this one use it?
if ( $number_of_posts >= 5 ) { // do stuff }
-
Answer
Example 3
For the given JavaScript code, should this one use Yoda conditions?
if ( cartTotal != calculateTotal() ) { // do stuff }
-
Answer
Example 4
How about this snippet of JavaScript code? Should it use it?
if ( typeof currency == "undefined" ) { // do stuff }
-
Answer
Example 5
For the given code, should this one use it?
if ( $post_type == $post->post_type ) { // do stuff }
-
Answer
The Handy Guide
*Yoda is a fictional character in the Star Wars space opera franchise created by George Lucas. Copyright protected 1980 by Lucasfilm Ltd. Wikipedia
Bad Practices and Myths
Let me take a few moments to talk about some bad practices and myths.
Bad Practice: When in Doubt, Yoda
Quality code alert: You want your code to be as readable as possible.I advise you to resist this temptation. Yoda conditions may make code harder to read for some developers. Part of your job as a software professional is to write quality code. You want your code to be as readable as possible.
Take the time to learn when to apply any design pattern or methodology. It is another step towards deeply knowing the code and improving the quality of your code.
Myth: Yoda makes your program run faster
This is a myth. It’s wrong. Yoda conditions does not make your program run faster. Why? Why is this a myth?
Think about an equality comparison expression. It follows the commutative property in math, where a == b is the same as b == a.
You need to evaluate both sides of the comparison in order to determine the result. Just because the variable is on one side and the value on the other, both of these operands are needed to determine if they equal one another or not. The order does not matter.
Within the CPU, both operands are loaded into memory and then the comparison occurs. Think about the order. If both are loaded into memory, how could the order matter?
Myth: Yoda improves optimization
This one is a myth for the same reasons as the one above.
The Where – Popularity
If you’ve read any of these popular programming books, you may be confused as the code examples and techniques do not use Yoda conditions.
- The Programatic Programmer: From Journeyman to Master
- Clean Code: A Handbook of Agile Software Craftsmanship
- Design Patterns: Elements of Reusable Object-Oriented Software
- Code Complete: A Practical Handbook of Software Construction, Second Edition
Even sites such as PHP: The Right Way show traditional conditional expression structures and not Yoda conditions.
So where is it used? Let’s take a look at what frameworks, applications, libraries, and languages actively use the Yoda conditions programming style.
Actively use Yoda
- WordPress (PHP and JavaScript)
- Symfony
Do not use Yoda
- jQuery
- Zend
- Laravel
- React
- Underscore
- AngularJS
- Backbone.js
- React
- Closure
- Ruby on Rails (RoR)
- CakePHP
- and many more including C#, VB, C++, Python, and more.
The Critics
There are many critics to this programming style. Readability is cited as the primary reason for not using it.
“Code that protects the author at the expense of the reader is flawed code.” ~Uncle BobOne critic is Uncle Bob (Robert C. Martin). On his blog, he says: “I dislike any statement in code that causes the reader to do a double-take. Code that protects the author at the expense of the reader is flawed code.”
Whether you are for or against Yoda conditions, when working in Symfony or WordPress, you should follow the coding standards.
The Alternatives
Testing is an alternative, as it negates the need for Yoda conditions. Properly written unit tests ensure each portion of your software is performing as intended and expected. Typos are found when running tests. For the case of the assignment typo, unit tests flush out this mistake as the test will fail.
Wrap it Up
Yoda conditions is one programming style to deal with one specific problem. It does not profess to solve other problems. When properly applied, it can minimize the effects of typos for assignment when you meant to compare. Practitioners know its trade-off is readability.