Yoda was a great teacher except for his word sequence. For programmer exists the yoda condition :
if (value == 42) { ... }
As yoda condition written:
if (42 == value) { ... }
I found some discussions on stackoverflow.com and collected pro and contras.
prevent an assignment
if (value = 42) { ... }
If you make this typo in javascript the condition is true and value is changed. In C your compiler would give you an warning, as yoda condition this would not work and your compiler will throw a compiler error.
if (42 = value) { ... }
null checks
if (myString != null && myString.equals(“yes”)) { ... }
This typical double check in java is tiring and will be shorter as yoda condition:
if (“yes”.equals(myString)) { ... }
in-operator
With javascript the in-operator can find an attribute in myObject:
myObject = {name: "Christian Harms" }; if ("name" in myObject) { ... }
The variant using value as first part is ok. A more object oriented variant will ask the container if the attribute is true.
if (myObject["name"]) { ... }
The same example in python with a list (because the example wont work with javascript Array):
myList = [1, 2, 3] if 1 in myList: ...
The yoda condition can used with a list method:
myList = [1, 2, 3] if myList.count(1): ...
conclusion
yoda says: “Try not. Do or do not, there is no try.”

Christian Harms

Latest posts by Christian Harms (see all)
- google code jam 2013 – tic-tac-toe-Tomek solution - April 16, 2013
- Google code jam 2013 – the lawnmower - April 14, 2013
- code puzzles and permutations - April 11, 2013