Playing with the shoulda testing framework, I came across a small but useful trick. Because the tests are written inside closures, local class variables are available inside should blocks. They're only evaluated once, so they don't take the place of setup blocks, but they are a nice way of storing test-wide values. Somehow, I like the look of this better than using instance variables or constants—the tests seem to be more uniform and balanced.
birth = Date.parse("2003-05-02")
now = Date.parse("2008-06-15")
assert_equal 5, AgeCalculator.age_given_dates(now, birth)
end
now = Date.parse("2008-06-15")
assert_equal 5, AgeCalculator.age_given_dates(now, birth)
end
now = Date.parse("2008-04-15")
assert_equal 4, AgeCalculator.age_given_dates(now, birth)
end
now = Date.parse("2008-05-01")
assert_equal 4, AgeCalculator.age_given_dates(now, birth)
end
end




That looks to me like a "clever" trick that's due to bite you in the butt in the long run, especially if you have more than one programmer working one the code over a long period of time. I did a little Google on clever programing and came up with these gems:
Everyone knows that debugging is twice as hard as writing a program in the first place. So if you are as clever as you can be when you write it, how will you ever debug it? -Kernighan
The competent programmer is fully aware of the strictly limited size of his own skull; therefore he approaches the programming task in full humility, and among other things he avoids clever tricks like the plague. -Dijkstra
Writing intention-revealing code is much more important than being clever. -Anonymous
Source: http://www.cse.iitb.ac.in/~kart/Quotes%20-%20Dev.html
Posted by: Ted | May 15, 2008 at 06:34 AM
Ted:
I'd be interested to know exactly what you feel makes this code hard to maintain, or “clever.” My personal believe is that it reads better than the alternatives.
Dave
Posted by: Dave Thomas | May 15, 2008 at 09:28 AM
Would be interested to hear why this is bad, "clever" usage. It's a simple, clear example of a closure; nothing scary, overly fancy, or hard to maintain/explain about it. It also looks like a pretty useful little approach.
If a person knows what a closure is, this should make immediate sense; if they don't know what a closure is, they should.
Posted by: Bruce Williams | May 15, 2008 at 01:30 PM
We use this technique liberally when developing custom shoulda macros. I'm not sure how to post code snippets, but if you look at the lib/shoulda/active_record.rb file, you'll find plenty of examples.
And I can understand how some people may find that technique to be tricky, but I'd encourage them to learn more about and make more use of ruby blocks. It's really an aspect of the language that sets it apart.
Cheers,
Tammer
Posted by: Tammer Saleh | May 15, 2008 at 05:49 PM