35 ms·
Yoda Conditionals: Why you should use them
- PaulHoule 4y agoA related pattern in Java is that if you write x.equals(“five”) you can get a null pointer exception if x is null, but “five”.equals(x) returns false if x is null which is probably what you want because it is not equal to “five”; it is a good thing though to import static java.util.Objects.equals And then write equals(x,y) And never get a null pointer exception. Other languages have other problems that make Yoda conditionals more appealing. In PHP the compiler won’t stop you from writing if(x=y) … where = is the assignment operator instead of the equality test, but if x is a literal the compiler will balk.
- bediger4000 4y agoWhen I wrote a lot of C I used Yoda Conditionals because the compiler catches some typos. I'm skeptical of increased readability of them.