Factorial Kata

_config.yml

All the katas previously attempted were similar. This time I thought to go for a direct recursion within a method. Is it a good approach? Direct and explicit recursions should be avoided where ever possible IMO. It is needlessly complex.

We could have done something like this (the Simple version):

But adopting the TDD approach (and after some painful refactoring) this was the solution I ended up with (please see below - the Complex version):

Notice how it looks startlingly similar to all the previous Katas we’ve gone through. We’ve got a method which produces the desired behaviour. But then we have different implementations of that behaviour. Enter polymorphism. And with polymorphism comes a factory method: perhaps the reader would do well to study the below and compare it with the code snippet above. Two solutions that look different: one employs three classes. The other manipulates numbers directly in just one method.

The simple one looks easier to read. It’s shorter and more easily understandable. But perhaps it is less amenable to change than the more complicated one which employs polymorphism. For the moment, what would I have done? Perhaps I would have stuck to the simple version. But the polymorphic solution looks very nice and is an OOP’s dream scenario.

Which one is better? What do you think? And why?

Any questions, please feel free to ask.

Written on April 25, 2017