This three-part series on using coding katas in practice Behavior Driven Development was written by the late Jamie Phillips, a well-known member of Boston's Agile and .NET communities. When we saw the first draft of this article we were all eager to publish it, but he passed away before we could finish the editing process. With the permission of wife Diana, we proudly present his final work.
I’m good, but couldn’t I be better?
Using Coding Katas, BDD and VS2010 Project Templates.
Regardless of your technical expertise, knowledge and experience there are always opportunities to strengthen your skills and be the “black belt” of your “coding dojo”. Through the use of Coding Katas to practice Behavior Driven Development and implementing a new VS2010 project template, we can hone our skills and “get better”.
This three part article will cover the topics of Coding Katas, Behavior Driven Development (BDD) and Project Template Wizard in VS 2010 and is intended to take the reader on a recent journey of discovery that improved my skills even after 8 years of writing C# code.
Part 1: Coding Katas
Even for seasoned software developers there are always areas that we can improve when it comes down to actually coding the design that we want to produce for any given requirement. The fact of the matter is that many times we make those adjustments to our coding best practice on code that we intended to go in to production; which is a natural state of affairs on our line of work. But if you project that idea into a different scenario all together and look at it from the point of view of martial arts; you wouldn’t exactly want to start adjusting your particular style of martial arts in a defensive scenario on the street! You might come out worse off than you intended. Instead, you would practice and refine your movements on a repetitive basis and hone your skills to the point that they became second nature. You would no longer have to think about the style or form, but the situation at hand. In many martial arts, practitioners will work on the same form (movements) repeatedly in order to engrain those movements into their memory, thus making it second nature to the practitioner.
Coding Katas (a term coined by Dave Thomas co-author of The Pragmatic Programmer) refers to a similar theory in software development. Here the developer takes a benign problem (such as the Fibonacci series) and works on producing throw away code that will resolve the problem, concentrating on the style and technique used more than the actual resolution of the problem. It has been pointed out that this approach to self improvement is for the “sandal-wearing hippies of the software world” and maybe they are right, however the instant payback that I had when I started practicing Katas surprised even my skeptical self – although as a practitioner of Tai Chi I did relate to the idea. So where does BDD and VS 2010 Project Template Wizard fit in to all of this? Well, quite simply it was a journey, an evolution if you like.
My first port of call was the concept of Coding Kata and the implementation of the Bowling Kata as I saw it being demonstrated at a session of TechEd 2010. David Starr and Ben Day gave an excellent interactive session that went through the Bowling Kata and dissected the “movements” into small chunks so that the audience could appreciate the test, code, refactor cycle that was involved. And that was it! As a Unit Test evangelist it made perfect sense! What better way to build up good working practices than to actually practice the steps that lead to robust code! As soon as I could (actually during the session) I started trying it out. My first attempts were not great as I was still concentrating on the problem itself and not the how I was writing the code; and that was my first lesson. In order to really reap the benefits of Katas you need to repeat the same Katas until you feel that the whole, test, code, refactor cycle is as tight and complete as you will get. Once you have done that then you can move on to another Kata.
The Kata that I first worked on was the Bowling Kata as shown to me at TechEd by Dave and Ben and originates from Uncle Bob (Robert C. Martin). The idea is to create a mechanism to score a game of ten pin-bowling. Without going in to too much detail of the scoring (you can easily search for it online), a player has 2 opportunities in each go (Frame) to knock down all of the pins (10 pins to be exact – hence the name “10 Pin Bowling”). If they knock them all down in one throw of the ball, it is considered a Strike. If they use both throws of the Frame to knock down all the pins, then it is considered a Spare. A game consists of 10 Frames, with Frame 10 being an opportunity to throw the ball 3 times if the player manages a strike or spare within the first 2 throws. I created the following “matrix” of scenarios to help me figure out how to score a game:
From this I can start to take a look at the Use Case scenarios for writing a 10 Pin Bowling Game Score Engine:
- Use Case 1: When bowling all zeros, the score should equal 0.
- Use Case 2: When bowling all ones, the score should equal 20.
(we did not throw a Strike or a Spare in the final frame – so no bonus ball) - Use Case 3: When bowling all strikes, the score should equal 300.
- Use Case 4: When bowling all spares, the score should equal 150.
- Use Case 5: When bowling a strike in the first frame and 8 pins in frame 2 and the remainder are zero, the score should equal 26.
For those of you that are familiar with SCRUM and TFS, this would typically be listed in as Conditions of Acceptance in the Product Backlog Item. Now we have our Use Cases we can start to look at writing the unit tests that we want to create for each scenario, and in true TDD fashion, without having the code of the engine itself written. The starting point of the Kata is to create a Unit Test project and take the first scenario and write the test for it:
/// <summary> /// Unit test methods for testing the bowling game engine /// </summary> [TestClass]
public class BowlingTests { /// <summary> /// Given that we are playing bowling
/// When I bowl all gutter balls
/// Then my score should be 0 /// </summary> [TestMethod] public void Bowl_all_gutter_balls() { // Arrange // Given that we are playing bowling Game game = new Game(); // Act
// when I bowl all gutter balls for (int i = 0; i < 10; i++) { game.roll(0); game.roll(0); } // Assert
// then my score should be 0 Assert.AreEqual(0, game.score()); } }
In order for this code to compile, the game engine class (Game) and the methods, roll and score, need to be created (hence they are shown red in the code snippet). The methods don’t necessarily have to do anything and nor should they – after all, in TDD we fail first.
Coding Tip:In VS 2010 we can now create classes whilst in the code by simply hitting CTRL + . (Period) when the caret is next to an undefined keyword (as in the case above with Game):
The advantage of this method of creating the class in this way is that the focus remains on the code where you are as opposed to other methods that force the focus on the newly created class. This same keyboard shortcut can also be used for methods as well:
So if we have approached TDD in its truest sense, our implementation class should look like this:
public class Game { public void roll(int p) { throw new NotImplementedException(); } public int score() { throw new NotImplementedException(); } }
And of course when we run the unit test it will fail (fail first, remember?):
So now we go back and implement only what is needed to pass the test:
public class Game { public void roll(int p) { // throw new NotImplementedException();
} public int score() { return 0; } }
Now, when we run all of the unit tests, we should be green:
We then take on the next scenario and write the test first:
/// <summary> /// Given that we are playing bowling /// When I bowl all single pins /// Then my score should be 20 /// </summary> [TestMethod] public void Bowl_all_single_pins() { // Arrange
// Given that we are playing bowling
Game game = new Game(); // Act
// when I bowl all single pins for (int i = 0; i < 10; i++) { game.roll(1); game.roll(1); } // Assert
// then my score should be 20 Assert.AreEqual(20, game.score()); }
When we run this test, it will fail (obviously):
So we return to the implementation and make the necessary changes, making sure we don’t break the previous tests:
public class Game { private int[] _rolls = new int[21]; private int _currentFrame = 0; public void roll(int pinsKnockedDown) { _rolls[_currentFrame++] = pinsKnockedDown; } public int score() { int retVal = 0; for (int index = 0; index < _rolls.GetUpperBound(0); index++) { retVal += _rolls[index]; } return retVal; } }
We run all of our tests to check the changes made:
This cycle continues throughout the Kata until all scenarios have been coded and all of the tests pass:
At this stage you can consider your Kata complete if you have refactored as much as possible, removing duplicate code, whilst retaining the integrity of the functionality – i.e. your tests keep passing after each refactor.
To truly benefit from the Kata, it is worth noting that the same Kata should be repeated for a few sessions until you are confident that you have refactored and optimized your code as much as possible. You must always start from scratch (or at least the minimum base for your environment), the reason is that we are doing the Katas to build up the coding strengths and in order to do that; you must go through all of the “movements” to get to your end product – a working solution – and therefore jumping steps in your approach is counterproductive as you are not getting the full benefit of the exercise. You will see, as I explain later on in this series, that there will be commonalities when you change Katas and those commonalities can actually be “baked in” to your approach through generic macros or better still – Project Templates.