Convention and reasoning
Posted on November 11, 2008, under Coding.
When coding in the past, I rarely used the switch/select/case-conditional. However, since I started using Ruby, I’ve found it to be quite useful in some situations.
Vim formats them like this:
case foobarwhen 'something' # Do something.when 'another thing' # Do another thing.else # Do this if the above "when"s don't match.end
That indentation scheme doesn’t feel right to me. The “when” and “else” clauses are pretty much children of the “case” clause. In my opinion, “when” and “else” should be indented +1, like this:
case foobar when 'something' # Do something. when 'another thing' # Do another thing. else # Do this if the above "when"s don't match.end
But now the code within each “when” and “else” is indented +2! That’s a lot of indentation.
I brought this up in #ruby-lang on Freenode. A couple of people agreed with me, a couple didn’t care, and the rest disagreed. There was one poignant comment though:
<quix> litage: why doesn't your reasoning for if/elsif apply to case/when?
I haven’t been able to answer that yet. quix’s reasoning is sound, but I can’t shake the dirtiness that I feel when indenting “when” and “else” to the same level as “case”. It just feels wrong…