Monday, November 10, 2014

Kata: Refactoring Tennis in Ruby

We practiced with the Refactoring Tennis kata in the last Barcelona Ruby meetup.

There were three different versions of the original code. I refactored the first one.

This is the original code:

First, I tried to refactor the code to the State Pattern as I did once before in C++. Then I realized checking the tests that the code was not meant to model a real tennis game. It's just focused in displaying the current score.

So I decided to try to separate the code that was keeping the tennis game score from the code that was displaying its score. I also wanted to be able to display the score in different languages.

This is the resulting code after the refactoring:

The TennisGame has two collaborators: the GameScore and the ScoreDisplayer.

The GameScore keeps track of the two Players in order to answer questions about the game score, whereas the ScoreDisplayer is in charge of displaying the score.

By default the ScoreDisplayer uses an English GameVocabulary, but the GameVocabulary can be injected through its accessor in order to display the score a different language (check the tests to see how the score is displayed in Spanish).

You can check the code and its tests in this GitHub repository.

I also committed after every tiny refactoring step so you can follow the process (especially the changes of mind I had and the dead-ends I found).

This kata was a great puzzle to practise and think.

I'd like to thank David Vrensk for his great work facilitating the kata and the interesting talk about Deliberate Practice that he gave before.

No comments:

Post a Comment