2 ms·
But you do know why this style exists and what benefits it has?
by klibertp 13y ago
But you do know why this style exists and what benefits it has?
- dheavy 13y agoI don't, and I'd be really grateful if anyone would enlighten me on the matter. Please excuse my ignorance!
- filearts 13y agoIf you forget to type a 2nd '=', putting a constant as the left-hand-side will allow the runtime to error instead of treating the expression like an accidental assignment with potentially disastrous side-effects.
- jaegerpicker 13y agoIn some languages sometimes but in general I think that's the use case for yoda code.
- stevehawk 13y agoit goes back further than this.. in compiled languages it is a compile time error. So you don't run through 1/2 of your application before you run into it. Instead it shows up as soon as you run make/gcc/g++/etc.
- ds_ 13y agoWikipedia gives an explanation: http://en.wikipedia.org/wiki/Yoda_conditions http://en.wikipedia.org/wiki/Yoda_conditions Seems kind of meh, especially if you're writing javascript when keywords like undefined can be redefined with no effect.
- mradmin 13y agoHmm, I've read reasons why you could code like this, but personally I would never make my code more complicated to read just to prevent errors that I can prevent with other methods, like having tests, for example. I would assume after someone has been coding for a decent amount of time, they would have the experience to spot declaration/assignment mistakes and shouldn't have to rely on yoda conditionals to prevent this. Perhaps there's other reasons I'm not aware of, and am not seeing the light because of that, care to share your thoughts?
- justinhj 13y agoI adopted this in my C days. Sure some compilers catch accidental assignment but not all and it could be disabled. As a defensive programming style I personally think the readability concerns were outweighed by the safety benefits. Not everyone agrees and I adapt my style to the project I'm working on.
- ahoge 13y agoIn most environments, writing something like `if (x = 5)` will generate a warning. E.g. if you use JSHint, you'd get: "Expected a conditional expression and instead saw an assignment." Nowadays, there usually isn't any benefit in using yoda conditions.