In the previous post I presented a solution of Conway's Game of Life in Clojure.
I've refactored that code in order to eliminate some duplication from the game rules.
First of all, I coded using TDD a new function will-have-a-cell? that later substituted both will-go-on-being-a-cell? and will-be-a-cell?.
These are the tests for the game rules after deleting the obsolete functions (will-go-on-being-a-cell? and will-be-a-cell?):
and this is the new function's code:
Once I had the new function I used it inside both keep-being-cells and new-cells functions to highlight the duplication between them:
Then I eliminated that duplication by using will-have-a-cell? directly in next-cells function, which made both keep-being-cells and new-cells obsolete:
Notice how will-have-a-cell? is used to filter all the possible locations (the current cells and their neighbors) which are given by the new all-neighbors-locations function.
Then I eliminated all the obsolete functions and their tests and did some renaming of the remaining functions, local bindings and parameters.
These are the resulting tests:
and this is the resulting code:
which is slightly shorter than the one in the previous version.
As usual I commited the code after every passing test and every refactor.
You will notice a problem I had with Midje :autotest not reacting properly after some of the renamings I did. I had to restart it so that it could take into account the changes.
If you want to follow the whole process, you can find the commits step by step here.
You can also find the resulting code in GitHub.
No comments:
Post a Comment