Skip to content

Instantly share code, notes, and snippets.

@dbrady
Created February 26, 2011 04:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dbrady/844950 to your computer and use it in GitHub Desktop.
Save dbrady/844950 to your computer and use it in GitHub Desktop.
Semantically identical code, three idiomatic ways of expressing it
# 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."
@avdi
Copy link

avdi commented Feb 26, 2011

I start with style A and if it gets too long I switch to style C. I would have to fight with my editor to get style B, which is good, because style B is awful.

Also, I never use style A if there are side-effects involved.

@avdi
Copy link

avdi commented Feb 26, 2011

If it fits in 80 chars I occasionally do a one-line if/then/else:

if status == OK then log "OK" else log "PROBLEM" end

@dbrady
Copy link
Author

dbrady commented Feb 26, 2011

Yay! We can still be friends! I feel exactly the same way.

I've shown style C to a couple of recovering PHP programmers in the past and had them absolutely freak out over it.

By default, emacs and TextMate use style C. Sublime Text 2 (a recent addition) uses style B and it's horrific to me.

@cschneid
Copy link

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.

@dbrady
Copy link
Author

dbrady commented Feb 26, 2011

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.

@avdi
Copy link

avdi commented Feb 27, 2011

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