When I first started learning Test Driven Development (TDD) there were resources in the form of books (TDD by Example and Clean Code), exercises to solve using TDD (Exercism.io and Kata Catalogue), and open source projects created using TDD.  Using these resources I would get a lot of practice starting from scratch and solving a small problem where I generally knew what my code would resemble at the end.  Unfortunately, this is not the environment that I code in professionally.  Requirements change frequently and it quickly became apparent that I needed not only the ability to solve problems but to take existing solutions and safely modify them to make it easier to add the new functionality.  This is where refactoring comes into play.

Refactoring means something different to some developers so I am going to use Martin Fowler’s definition from his seminal book Refactoring, which is: “A change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior.”  It is important to note that refactoring does not include adding new functionality, rather it is more about getting the design of your code to a place where adding new functionality is easy.  This brings us back to how to build or practice your refactoring skill on existing code, but not in your production code.

The classic refactoring exercise is an implementation of movie store rental program that generates a receipt based on the movies you rented.  This exercise was created by Martin Fowler and introduced in the beginning of his book Refactoring.  The exercise is available in Java and JavaScript.  The goal is to refactor the code to follow the 4 rules of simple design and make it easy to add new functionality in the form of new movie types and different receipt formats.  Both of those projects do not start with full test coverage so remember to add tests to verify that functionality does not change for “New” and “Childrens” rentals.

If you are having trouble getting started or want to see how two world class developers approach this problem I would recommend reading Martin Fowler’s blog post on his four approaches to the problem or Robert Martin’s (author of Clean Code) screen-cast of him refactoring the solution with the added bonus of remaining green on all tests the entire time.  Robert Martin’s screen-cast is available for $14.  I found it especially helpful as he narrates his logic for making each change and does them in small steps so its easy to follow along.  Happy refactoring and remember to keep your tests green.

Share This