Last week some friends from Software Craftsmanship Gran Canaria and I practiced doing Matteo Vaccari's Open-Closed Principle kata.
Jose M. Deniz Suarez and I paired to solve it using Ruby.
We got two versions of the code.
These are the tests:
and the code of the first version:
In this first version, we used a reduce over a list of translators. Each translator might add or not a translation of the given number to
the resulting string.
To try something different from what we've tried other times, we used a template method pattern to remove the duplication between the tranlators.
Even though, we reduced the duplication, we didn't like the solution because the resulting Translator interface (public methods) had parameters that were not used by some of its derived classes.
Next, we deleted the code and try another approach. This time we used the decorator pattern.
The tests were the same except for the sayer factory method:
and this the resulting code:
Then we refactored it to remove some duplication and added a new translation whose condition didn't have to do with being multiple of some number.
This forcer us to generalize the translators passing them a predicate and a translation string through their constructors.
These are the resulting tests (only showing the new test and the sayer factory):
It was a lot of fun.
The constrainsts of this kata are very interesting to practice refactoring and understand the OCP principle.
You can find the code in this GitHub repository.
I'd like to thank Matteo Vaccari for creating it and the great people of Software Craftsmanship Gran Canaria for the fun and the interesting discussions about the different solutions we got.
PS: The "bokata de pata" was also great :)