Thursday 10 May 2007

TDD on Rails on Mac

Together with Andrew, we had an instructive TDD session on Rails yesterday. It was quite a new experience especially for me as I had never had a Mac in my hands before :). It took me about 2 hours to get used to it. However, there is still one thing I don't like and can't understand - where is the 'Del' button on Mac??!! Hope there is a good explanation for not having it ...

Anyway, we started from scratch repeating the 15 TDD steps to get the basic app running. The app itself is very simple - a kind of english/polish dictionary with the guess/learn option. The next thing after the 15th step was to add some content to the database so the user can play around and have fun guessing new words. Andrew talks in more detail in his last post how we tested and implemented that. I must admit however that it was a real fun for a (still!) Java programmer like me to switch to Ruby for a while. Just see how little code we had to write to achieve the following:
  • check if a Word has a translation

def translated?
pl and en
end
  • return a random and translated word

def self.random
(Word.find(:all).select {|word| word.translated?}.sort_by {rand})[0]
end

Can you imagine how would this code be implemented in Java?

Having done some TDD before I realized again what really matters when you test drive your application. TDD changes the way of thinking of the code you are going to write. As Andrew said, it is all about design, not necessarily about testing itself. The tests you write is some sort of (positive) side effect - you just get them as you go along.

The other thing I'd like to mention here is YAGNI (You Arent Gonna Need It). Perhaps a bit off topic, nevertheless that's what came to my mind yesterday, too.
Having written many lines of good looking and performing code I had to stop worrying about code like this:


(Word.find(:all).select {|word| word.translated?}.sort_by {rand})[0]

Certainly getting all the words from the database does not look nice at first glance. But have a think - is that really going to work very slow and cause any problems? Not really, unless you have hundreds or thousands of users, which doesn't happen so quickly. So don't bother until this becomes a real problem. And what is the most important here - be productive and don't waste your precious time for improvements that don't have any business value.

No comments: