Yoda Conditions

from Wikipedia, the free encyclopedia

Yoda Conditions (also: Yoda Notations ) denote in programming jargon a form of source text formatting for conditional statements in which the two sides of the condition are swapped. The name for this programming style is derived from the character Yoda from the Star Wars universe, who tended to swap some words within a sentence.


Usually programmers write a condition, in this case a conditional statement, like this:

if (wert == 42) { /* ... */ }
// Liest sich wie: Wenn Wert gleich 42...

Yoda Conditions now designate the reverse position of the printout content:

if (42 == wert) { /* ... */ }
// Liest sich wie: Wenn 42 gleich Wert...

In this programming style, the constants are listed first and then the variable comparison value. Analogous to the pronunciation of the namesake Yoda ("You have to forget what you learned earlier"), this leads to a strange pronunciation of the condition: "If the 42same wertis ...".


Interchanging the two condition values ​​does not change the behavior of the program . Although this condition is more difficult to read for the programmer than the first example, this application has the advantage of eliminating careless errors from the condition in those programming languages ​​that allow value assignment using = in an expression and the implicit conversion of numbers into truth values to make a variable assignment:

if (wert = 42) { /* ... */ }
// Ist (unbeabsichtigt vom Programmierer) immer wahr und ändert den Inhalt von wert

if (42 = wert) { /* ... */ }
// Erzeugt einen Syntaxfehler

The example below prevents the carelessness error because an error is generated or generated during runtime or during compilation : 42 is a constant; no value can be assigned to this.

In some languages, this can also prevent the invalid dereferencing of a null value :

String wert = null;
if (wert.equals("foobar")) { /* ... */ }
// In Java tritt eine NullPointerException auf

if ("foobar".equals(wert)) { /* ... */ }
// Ist (wie erwartet) immer falsch


Critics of the notation style see the poor legibility as a predominant disadvantage, which does not outweigh the alleged problem of the carelessness described above. It is stated that modern development environments mark this line as a possible error. Some programming languages ​​also do not allow the assignment of variables within a condition anyway. In the programming language D , assignments do not have a Boolean data type and can therefore not be used as a ifcriterion.

See also

Web links

Individual evidence

  1. you have to debug - Yoda Conditions in PHP. May 10, 2010, accessed on September 22, 2011 (German).
  2. ^ Nils Langner: Yoda Conditions. July 26, 2010, accessed on September 22, 2011 (German).
  3. Why Yoda conditions are bad and usage of Java's 'final' keyword is good. May 15, 2011, accessed September 22, 2011 .