6 ms·
"Yoda Conditions" takes the cake. It's pretty interesting how a commutative operation such as `==` still has certain conventions. Then again, `==` isn't guarant
by RegEx 14y ago
"Yoda Conditions" takes the cake. It's pretty interesting how a commutative operation such as `==` still has certain conventions. Then again, `==` isn't guaranteed to be commutative in Ruby, since it can be overridden (which I'm not a big fan of).
- BadassFractal 14y agoCan't stand Yoda conditions, although I'm sure someone somewhere has an explanation why they're so good for me.
- dllthomas 14y agoif(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.
- DHowett 14y agoWhat 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.
- dllthomas 14y agoThe 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.
- jimrandomh 14y agoThey 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.
- deleted 14y ago[deleted]
- ralfn 14y agoThey 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.
- suresk 14y agoIn 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")){
- Wilya 14y agoThey (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.
- Ralith 14y agoOf course, this applies to most languages where the concept of "equality" can be extended, from C++ to Haskell. You just have to rely on the implementer of the interface to obey the appropriate laws. This is part of why dependent typing (as seen in Idris and co.) is so interesting: you can actually require, for example, that implementations of the equality interface are commutative, and this will be statically checked by the compiler.