Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Can't stand Yoda conditions, although I'm sure someone somewhere has an explanation why they're so good for me.


They were invented to defend against a (mis)feature of C and some other programming languages, where you can use '=' in an expression when you meant to use '==', getting an assignment instead of a comparison. If there's a constant on the left, then this would be an error. However, most compilers now generate warnings in all of the cases where Yoda conditions would've helped, but conventions tend to outlast their purpose.


In Java, at least, it can be useful when the value you are comparing a String constant with can be null:

if("test".equals(environment)){

vs

if(environment != null && environment.equals("test")){


They protect against accidental assignment. They also protect against unexpect classes having the compare/equality method begin overridden.

So, no, not that important. But i actually think it looks nice.


if(x = 3)

if(3 = x)

If you make a habit of making the left side of == immutable, the compiler will let you know when you type = instead. Of course, gcc throws a warning unless you type if((x = 3)) if you genuinely want to do the assignment inside the if, which works just as well but requires tool support.


What tool support does it require? I certainly hope there are no tools generating assignments in conditional expressions, and the only other tools that need to support it clearly understand parentheses.


The warning itself is dependent on your compiler squawking when it sees "if(x = 5)". The C spec doesn't require this. On the other hand, "if(5 = x)" will be thrown out by any C compiler.


They (also) exist for basic Java strings.

aString.equals("SOMETHING") will throw an exception if aString is null, while "SOMETHING".equals(aString) will just return false.

In some cases, that's one 'if' less to write.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: