4 ms·
Not in this case, but Yoda conditions can be useful. The most common case is preventing accidental assignment when you are trying to check for the equality of v
by acangiano 16y ago
Not in this case, but Yoda conditions can be useful. The most common case is preventing accidental assignment when you are trying to check for the equality of values.
Say that you mean to do:
if (something == 2)
If you forget an equal sign, the resulting code can lead to subtile bugs:
if (something = 2) // Not what we meant
If you are using a Yoda condition and forget an equal sign, you'll get an error right away (so that you can correct it):
if (2 = something) // Error
There are other use cases, particularly related to nil values, but this should show you the gist of it.
- masklinn 16y ago> Not in this case, but Yoda conditions can be useful. Not in Python. Assignments as anything but stand-alone (potentially chained) statements are syntax errors. The parser will not let you write if something = 2: in the first place.
- acangiano 16y agoThat's why I said "not in this case". There are languages affected by this though (typically C-based ones). Ideally, their compiler will give you a warning about it, but that's not always the case.