Yoda conditions

From HandWiki
Revision as of 19:01, 6 February 2024 by S.Timg (talk | contribs) (link)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Short description: Computer programming style

In programming jargon, Yoda conditions (also called Yoda notation) is a programming style where the two parts of an expression are reversed from the typical order in a conditional statement. A Yoda condition places the constant portion of the expression on the left side of the conditional statement.

Yoda conditions are part of the coding standards for Symfony[1] and WordPress.[2]

Origin

The name for this programming style is derived from the Star Wars character Yoda, who speaks English with a non-standard syntax[3] (e.g., "When 900 years old you reach, look as good you will not."[4][5]). Thomas M. Tuerke claims to have coined the term Yoda notation and first published it online in 2006.[6] According to him, the term Yoda condition was later popularized by Félix Cloutier in 2010.

Example

Usually a conditional statement would be written as:

if ($value == 42) { /* ... */ }
// Reads like: "If the value equals 42..."

Yoda conditions describe the same expression, but reversed:

if (42 == $value) { /* ... */ }
// Reads like: "If 42 equals the value..."

Advantage

Error detections

Placing the constant value in the expression does not change the behavior of the program (unless the values evaluate to false—see below). In programming languages that use a single equals sign (=) for assignment expressions and not for comparison, a possible mistake is to assign a value unintentionally instead of writing a conditional statement.

if (myNumber = 42) { /* ... */ }
// This assigns 42 to myNumber instead of evaluating the desired condition

Using Yoda conditions:

if (42 = myNumber) { /* ... */ }
// A syntax error this is and compile it will not

Since 42 is a constant and cannot be changed, this error will be caught by the compiler.

Boolean myBoolean = null;
if (myBoolean == true) { /* ... */ }
// This causes a NullPointerException in Java Runtime, but legal in compilation.
// This happens because Java will try to call myBoolean.booleanValue() on a null Object.

Avoiding some types of unsafe null behavior

Yoda conditions help with unsafe behavior in some situations.

String myString = null;
if (myString.equals("foobar")) { /* ... */ }
// This causes a NullPointerException in Java

With Yoda conditions:

String myString = null;
if ("foobar".equals(myString)) { /* ... */ }
// This resolves to false without throwing a NullPointerException

Criticism

Yoda conditions are criticized for compromising readability by increasing the cognitive load of reading the code.[7][8]

Some programming languages (such as Swift, Kotlin and versions of Python below 3.8) do not allow variable assignments within conditionals—for example by requiring that assignments do not return a value, or by defining as part of their grammar the invariant that conditions cannot contain assignment statements—in which case this error is impossible to encounter (that is, it would be detected as a syntax error by the parser prior to a program ever being allowed to enter into runtime).[9] Many compilers produce a warning for code such as if (myNumber = 42) (e.g., the GCC -Wall option warns suggest parentheses around assignment used as truth value), which alerts the programmer to the likely mistake. In dynamic languages like JavaScript, linters such as ESLint can warn on assignment inside a conditional.[10] Python 3.8 introduced assignment expressions, but uses the walrus operator := instead of a regular equal sign (=) to avoid bugs which simply confuse == with =.[11]

The advantage of avoiding null behavior can also be considered a disadvantage, as null pointer errors can be hidden and only appear much later in the program.

Another disadvantage appears in C++ when comparing non-basic types as the == is an operator and there may not be a suitable overloaded operator function defined. Example: a Microsoft's CComBSTR compare against a string literal, written as if (L"Hello" == cbstrMessage), does not map to an overload function.[12]

References

  1. "Coding Standards (Contributing to Symfony)". http://symfony.com/doc/current/contributing/code/standards.html#structure. 
  2. "PHP Coding Standards | Coding Standards Handbook". https://developer.wordpress.org/coding-standards/wordpress-coding-standards/php/#yoda-conditions. 
  3. Pullum, Geoffrey K. (2005-05-18). "Yoda's Syntax the Tribune Analyzes; Supply More Details I Will!". Language Log. http://itre.cis.upenn.edu/~myl/languagelog/archives/002173.html. "One way to look at Yoda's syntax is that it shows signs of favoring OSV syntax (Object-Subject-Verb) as the basic order in the simple clause." 
  4. "The StarWars.com 10: Best Yoda Quotes". Lucasfilm, Ltd.. 2013-11-26. https://www.starwars.com/news/the-starwars-com-10-best-yoda-quotes. "When nine hundred years old you reach, look as good you will not." 
  5. "Quotes for Yoda (Character)". Amazon. https://www.imdb.com/character/ch0000015/quotes. "When nine hundred years old *you* reach, look as good *you* will not, hmm?" 
  6. "Yoda Notation (aka Yoda Condition)—Origin of the term". 2013-04-17. http://thomas.tuerke.net/on/design/?with=1249091668#msg1146181680. 
  7. Paris, Grégoire (24 January 2020). "Why using Yoda conditions you should probably not be" (in en). https://dev.to/greg0ire/why-using-yoda-conditions-you-should-probably-not. 
  8. Classic, Mike (16 August 2017). "Yoda Conditions: Why You Shouldn't Use Them" (in en). https://mikeclassic.ca/blog/yoda-conditions-why-you-shouldnt-use-them. 
  9. "Basic Operators — The Swift Programming Language (Swift 5.6)". Apple. https://docs.swift.org/swift-book/LanguageGuide/BasicOperators.html. 
  10. "disallow assignment operators in conditional statements". https://eslint.org/docs/latest/rules/no-cond-assign. 
  11. Angelico, Chris; Peters, Tim; van Rossum, Guido (2018-02-28). "PEP 572 -- Assignment Expressions" (in en). https://peps.python.org/pep-0572/. 
  12. "CComBSTR Class" (in en-us). Microsoft. 3 August 2021. https://learn.microsoft.com/en-us/cpp/atl/reference/ccombstr-class?view=msvc-170#operator_eq_eq. 

External links