Monday, January 10, 2011

camelCase for human beings

Reading lots of characters glued together is a very good thing for the compiler. Human beings tend to prefer spaces rather than a set of lowercase characters separated with uppercase characters to distinguish words. It's just how we were taught since we were very young...

In case of unit test in Groovy we can actually name our tests with spaces! Here's an example:
import org.junit.Test

class ExampleTests {
@Test void 'This test verifies nothing but is a good example'() {
assert 1 == 1
When later on you're reading the name of the test that failed it's a whole lot easier than to read the same in camelCase.

Converting camelCase to human text

I thought I'll give a string an additional method so that whenever I have a camelCase string I can convert it easily to something that's easier to read:
String.metaClass.humanify = {
def r = ""

delegate.eachWithIndex { c, i ->
if (i == 0) r += c.toUpperCase()
else if (c in 'A'..'Z') r += ' ' + c.toLowerCase()
else r += c

return r

From now on it's easy to read camelCase when it's humanized :D

No comments: