Las condiciones Yoda
Gracias a la lectura de What lame things do programmers often argue about? he descubierto el término Yoda condition:
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. The name for this programming style is derived from the Star Wars character named Yoda, who spoke English in a non-standard syntax.
Yoda conditions are part of the WordPress and Symfony coding standards.
Al principio no entendía la ventaja que podía ofrecer este estilo de programación, pero:
In programming languages that use a single equals sign (=) for assignment 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) { /* … */ }
// This is a syntax error and will not compile
Since 42 is a constant and can not be changed, this error will be caught by the compiler.
Deja un comentario