by crazygringo · 14y ago · 0 comments
do_something(with, these, args) if im_supposed_to
I mean, the processor/interpreter always needs to evaluate the "if" first, so what purpose does it ever serve to put it after the "then"? To me, it just confuses things because it feels like code is getting executed backwards -- like crossing an intersection, and then checking to see if the light is green.I know it works "in English" ("do this if that"), but when I scan other people's code I'll sometimes completely miss the "if" (sometimes it's just off the screen).
Are there any examples where this reverse-if actually helps, instead of harming, code intelligibility?
read(file)
write(file) unless terriblyUnlikelyThingHappens
return results
... it helps to keep the expected main-line flow of your instructions reading smoothly -- much the same as the way you'd tend to use it in English. Doing it the "normal" way instead: read(file)
if (!terriblyUnlikelyThingHappens) {
write(file)
}
return results
... makes it a bit more difficult to follow what should be going on in the function.When scanning and I see
If (condition) { perform_some_action(foo, bar, baz); }
And I know condition is false I can ignore what follows but perform_some_action foo, bar, baz if condition
I now have to stop and parse the entire line. But not only that, because it can appear at the end I need to parse every line to make sure I don't get caught by some if or unless. Short lines are easy sure but it's still annoying to me. if (some condition that doesn't hold on that configuration) ...
You can avoid everything inside that if statement if you know that's not important for the case you're considering. myfn = (arg) ->
return 1 if arg is "one"
return 2 if arg is "two"
return arg.toInt()
This is obviously a little contrived with such a short method, but helps when you have stuff to do between conditional returns. throw 'error' if badness
return null unless goodness
Since it doesn't make sense to return or throw unconditionally it is makes it pretty clear that you should look for the if/unless. if badness throw 'error'
unless goodness return null
to be more readableAnd anytime there's code after a return, it had better be connected to a conditional. :)
if badness
throw 'error'
unless goodness
return null value = cache[key]
if value?
return value
return file.readContents() unless not file.exists()