Created
February 26, 2011 04:48
-
-
Save dbrady/844950 to your computer and use it in GitHub Desktop.
Semantically identical code, three idiomatic ways of expressing it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Coders from from C often like this style: | |
log status == OK ? "OK" : "PROBLEM" | |
log "All done." | |
# But since if returns a value in ruby, you can spell it out: | |
log if status == OK | |
"OK" | |
else | |
"PROBLEM" | |
end | |
log "All done." | |
# I favor this style, because it pushes the whole expression out and preserves the vertical registration of if/else/end | |
log if status == OK | |
"OK" | |
else | |
"PROBLEM" | |
end | |
log "All done." |
Oh, that's interesting. In that context, I generally favor
if status==OK; log "OK"; else log "PROBLEM"; end
But I note that I'm in a very different context there--I am coding at a bash prompt (with ruby -e) or at an IRC entry window, and when I'm thinking in one-liner mode I go for the semicolon as fast as possible.
Hmm, I'd probably still do
log(if status==OK; "OK"; else; "PROBLEM"; end)
But only if it was long and complicated, like with multiple nested ifs; otherwise I'd probably just use the ternary ?: operator.
If we're still doing Ruby you don't need any of those semicolons:
puts(if status==OK then "OK" else "PROBLEM" end)
works just fine.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I strongly prefer style C. I suppose I prefer the haskell/python style of indentation of control blocks. The close of a block should never be at a different indent level than the open of it in my mind.