<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule">

<channel>
	<title>Thinking Inside a Bigger Box &#187; video</title>
	<atom:link href="http://johannesbrodwall.com/category/video/feed/" rel="self" type="application/rss+xml" />
	<link>http://johannesbrodwall.com</link>
	<description>Johannes Brodwall&#039;s Musings on Software Architecture and Programming</description>
	<lastBuildDate>Mon, 03 May 2010 20:24:08 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>		<item>
		<title>Six ideas that improve your software design</title>
		<link>http://johannesbrodwall.com/2010/05/02/six-ideas-that-improve-your-software-design/</link>
		<comments>http://johannesbrodwall.com/2010/05/02/six-ideas-that-improve-your-software-design/#comments</comments>
		<pubDate>Sun, 02 May 2010 23:00:39 +0000</pubDate>
		<dc:creator>Johannes Brodwall</dc:creator>
				<category><![CDATA[Extreme Programming]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[video]]></category>

		<guid isPermaLink="false">http://johannesbrodwall.com/?p=536</guid>
		<description><![CDATA["Design" is a verb, not a noun. If I want to create a good program, studying the process of getting there is much more important than the resulting software. This is why I use coding katas as a form of study. I find an interesting problem problem and then solve the same problem over and over again. In this blog post, I will focus on six principles of software design. I will illustrate each with a screencast from a kata.

One of my favorite problems is that of creating a Java EE application from scratch. I call this kata "The Java EE Spike Kata". In order to understand the role of frameworks, I use no web frameworks in the process of creating this application. I've completed this particular exercise about forty times on my own and more than ten times with various pair-programming partners. The whole exercise takes me about 90 minutes, and I still learn new things.

The total time of the screencasts is around 40 minutes, so you may want to pick and choose. Each section provides a link to the starting point for the source code if you want to follow along.

<em><strong>Please notice</strong>: The videos are accompanied by loud, pounding music. Keep you headphones on or your volume down if you share offices with someone else. Or mute the videos if you dislike the music.</em>


<h3>Idea 1: Build your software from the outside-in</h3>

<embed src="http://blip.tv/play/AYHWhGIA" type="application/x-shockwave-flash" width="480" height="380" allowscriptaccess="always" allowfullscreen="true"></embed>

(10 minutes, <a href="http://github.com/jhannes/java-ee-spike-kata/tree/1-outside-in">github starting point</a>)

I start building the application by writing tests that access the application over HTTP and looks at the resulting HTML. As you might have gathered, when I start this test, there is no web application. Only when the tests require a web application to continue do I start creating it. In this example, I had created a basic sketch of the interaction between the three web pages in the application before I started coding. No further design was necessary.

This particular approach uses <a href="http://code.google.com/p/selenium/wiki/GettingStarted">WebDriver</a> and <a href="http://jetty.codehaus.org/jetty/">Jetty</a> to run. The cute assertion library that you may have noticed at the end of the video is <a href="http://fest.easytesting.org/assert/">FEST-assert</a>.


<h3>Idea 2: Specify behavior rather than implementation</h3>

<embed src="http://blip.tv/play/AYHWhF4A" type="application/x-shockwave-flash" width="480" height="380" allowscriptaccess="always" allowfullscreen="true"></embed>

(6 minutes, <a href="http://github.com/jhannes/java-ee-spike-kata/tree/2-1-servlet-test">github starting point</a>)

I don't make much of a distinction between different types of tests. All good tests try to describe <em>what</em> the software should do at some level, rather than <em>how</em> the software does it. But the <em>how</em> at some level may be the <em>what</em> at another level. My first test specified the interaction between the web browser and the server. In this test, one step may be to fill in the form element of a web page. This second video shows <em>how</em> this form works in terms of actual HTML. But the details of what framework (if any) is used, is not visible in the test.

The second thing you'll notice in the video is that I run the tests more frequently. And each test run is much quicker. As our tests move close to the code, the rate of feedback improves.

This particular test uses <a href="http://mockito.org/">Mockito</a> to mock out the Servlet API. The assertions use <a href="http://fest.easytesting.org/assert/">FEST-assert</a>.


<h3>Idea 3: Increase the rate of feedback</h3>

<embed src="http://blip.tv/play/AYHWhCEA" type="application/x-shockwave-flash" width="480" height="380" allowscriptaccess="always" allowfullscreen="true"></embed>

(5 minutes, <a href="http://github.com/jhannes/java-ee-spike-kata/tree/3-equals-test">github starting point</a>)

This video illustrates the frequency of feedback. The example test-drives creating an <code>equals</code>-method. This task is often not worth test-driving. The resulting method is usually simple and/or generated by your IDE. But it is a good example to of how quick the cycle between test and production code <em>can</em> be when you're writing tests that are close to the problem at hand. When I pair program this part of the kata, we usually use a technique called ping-pong programming: One programmer writes a failing test (or failing assertion) and hands the keyboard to his partner, the other programmer makes the test pass and writes another failing test before passing the keyboard back. On a good run, we will switch who's got the keyboard more often than once per minute.

Notice that I also focus on the <em>behavior</em> of the <code>equals</code>-method in this test.


<h3>Idea 4: Grow the API rather than designing it up front</h3>

<embed src="http://blip.tv/play/AYHWhEwA" type="application/x-shockwave-flash" width="480" height="380" allowscriptaccess="always" allowfullscreen="true"></embed>

(8 minutes, <a href="http://github.com/jhannes/java-ee-spike-kata/tree/4-search-for-people">github starting point</a>)

As the web application grows under my fingers, I discover the need for a Data Access Object (DAO). However, as this represents a major internal interface in my application, I use Mockito to mock the implementation until I'm done with the behavior of my servlet. When this is done, I test-drive the implementation of the DAO in a separate test class.

The video also illustrates another important lesson: The code is getting ripe for a refactoring. But it's important to resist the urge to refactor until the tests are green. If you refactor on red tests, you have much higher chances of running down a dead-end road and you'll have to throw away your progress, wondering what went wrong.

The example uses <a href="http://mockito.org">Mockito</a> to mock out the DAO API.

If you want to see how I implement the DAO with Hibernate, you can see the video on <a href="http://jhannes.blip.tv/file/3487456/">blip.tv</a>.


<h3>Idea 5: Grow the design rather than speculating</h3>

<embed src="http://blip.tv/play/AYHWhEsA" type="application/x-shockwave-flash" width="480" height="380" allowscriptaccess="always" allowfullscreen="true"></embed>

(3 minutes, <a href="http://github.com/jhannes/java-ee-spike-kata/tree/5-2-refactoring">github starting point</a>)

The video is only a partial example of this principle. Throughout the whole application, I've been refactoring, gradually pulling out structure to more well-structured methods and classes. The video illustrates some of the power of IDE's when it comes to refactoring. Using the IDE to massage your code into a better design makes evolutionary design much easier to do in practice. Make sure to learn your IDE's most useful refactorings!

The kata may seem like a non-realistic example at this time, but I've actually grown a very successful architecture on my current project using much the same approach. If you want to explore where to go next, the next step needed for this application is to factor out the views into separate classes and then use either a <a href="http://martinfowler.com/eaaCatalog/templateView.html">View Template</a> language (like Velocity) or a <a href="http://martinfowler.com/eaaCatalog/transformView.html">View Transformer</a> (using, for example dom4j) to generate the HTML. (Let me know if you'd like to see the screencast of this as well).


<h3>Idea 6: It's supposed to work the first time around</h3>

<embed src="http://blip.tv/play/AYHWhF8A" type="application/x-shockwave-flash" width="480" height="380" allowscriptaccess="always" allowfullscreen="true"></embed>

(5 minutes, <a href="http://github.com/jhannes/java-ee-spike-kata/tree/6-getting-it-to-work">github starting point</a>)

In this video, I return to the first test, <code>PersonWebTest</code>, to finish the configuration of the application. I discover a few mistakes I made in the web test as I complete the exercise. Then I try out the code in the browser. And all the scenarios I had planned for work out of the box.

When you try out your code for the first time, it should work. When you master test-driven development, you will probably forget how you programs <em>didn't</em> use to work the first time. Only when you occasionally run into an unexpected error during manual testing it becomes clear how test-driven development changes you life.

If you want to see the whole, uninterrupted 75 minute code kata, the video is available at <a href="http://jhannes.blip.tv/file/3487566/">blip.tv</a>. You can also take a look at the finished source code at <a href="http://github.com/jhannes/java-ee-spike-kata/tree/commit_per_test">github</a>.

Happy programming!


<hr />

<em>A big thanks to Trond, Thomas, Ram and Christian who helped improve this post. Thank you to Finn-Robert, Øistein, Mats, Anders, Siv, Peyman, Ivar, Øystein, Cecilia, Nicolay, and Karianne who have pair-programmed this exercise with me. I especially appreciate how Ivar and Karianne both helped influence the way the application is wired together and showed me that even after 30 iterations, I still had things to learn; and how Øistein showed me how two trained developers could complete the exercise faster with pair-programming than alone. And thank you to Nicolay who graciously brought food to our pair-programming exercise.</em>

The videos were made with the excellent (and free!) <a href="http://www.bbsoftware.co.uk/BBFlashBack_FreePlayer.aspx">BB FlashBack Express</a>. The keyboard echo is courtesy of <a href="http://katastrophos.net/magnus/blog/2008/08/01/keypose-flavour-your-screencasts-with-shortcuts/">KeyPosé</a> by Magnus Jungsbluth.]]></description>
			<content:encoded><![CDATA[<p>&#8220;Design&#8221; is a verb, not a noun. If I want to create a good program, studying the process of getting there is much more important than the resulting software. This is why I use coding katas as a form of study. I find an interesting problem problem and then solve the same problem over and over again. In this blog post, I will focus on six principles of software design. I will illustrate each with a screencast from a kata.</p>
<p>One of my favorite problems is that of creating a Java EE application from scratch. I call this kata &#8220;The Java EE Spike Kata&#8221;. In order to understand the role of frameworks, I use no web frameworks in the process of creating this application. I&#8217;ve completed this particular exercise about forty times on my own and more than ten times with various pair-programming partners. The whole exercise takes me about 90 minutes, and I still learn new things.</p>
<p>The total time of the screencasts is around 40 minutes, so you may want to pick and choose. Each section provides a link to the starting point for the source code if you want to follow along.</p>
<p><em><strong>Please notice</strong>: The videos are accompanied by loud, pounding music. Keep you headphones on or your volume down if you share offices with someone else. Or mute the videos if you dislike the music.</em></p>
<h3>Idea 1: Build your software from the outside-in</h3>
<p><embed src="http://blip.tv/play/AYHWhGIA" type="application/x-shockwave-flash" width="480" height="380" allowscriptaccess="always" allowfullscreen="true"></embed></p>
<p>(10 minutes, <a href="http://github.com/jhannes/java-ee-spike-kata/tree/1-outside-in">github starting point</a>)</p>
<p>I start building the application by writing tests that access the application over HTTP and looks at the resulting HTML. As you might have gathered, when I start this test, there is no web application. Only when the tests require a web application to continue do I start creating it. In this example, I had created a basic sketch of the interaction between the three web pages in the application before I started coding. No further design was necessary.</p>
<p>This particular approach uses <a href="http://code.google.com/p/selenium/wiki/GettingStarted">WebDriver</a> and <a href="http://jetty.codehaus.org/jetty/">Jetty</a> to run. The cute assertion library that you may have noticed at the end of the video is <a href="http://fest.easytesting.org/assert/">FEST-assert</a>.</p>
<h3>Idea 2: Specify behavior rather than implementation</h3>
<p><embed src="http://blip.tv/play/AYHWhF4A" type="application/x-shockwave-flash" width="480" height="380" allowscriptaccess="always" allowfullscreen="true"></embed></p>
<p>(6 minutes, <a href="http://github.com/jhannes/java-ee-spike-kata/tree/2-1-servlet-test">github starting point</a>)</p>
<p>I don&#8217;t make much of a distinction between different types of tests. All good tests try to describe <em>what</em> the software should do at some level, rather than <em>how</em> the software does it. But the <em>how</em> at some level may be the <em>what</em> at another level. My first test specified the interaction between the web browser and the server. In this test, one step may be to fill in the form element of a web page. This second video shows <em>how</em> this form works in terms of actual HTML. But the details of what framework (if any) is used, is not visible in the test.</p>
<p>The second thing you&#8217;ll notice in the video is that I run the tests more frequently. And each test run is much quicker. As our tests move close to the code, the rate of feedback improves.</p>
<p>This particular test uses <a href="http://mockito.org/">Mockito</a> to mock out the Servlet API. The assertions use <a href="http://fest.easytesting.org/assert/">FEST-assert</a>.</p>
<h3>Idea 3: Increase the rate of feedback</h3>
<p><embed src="http://blip.tv/play/AYHWhCEA" type="application/x-shockwave-flash" width="480" height="380" allowscriptaccess="always" allowfullscreen="true"></embed></p>
<p>(5 minutes, <a href="http://github.com/jhannes/java-ee-spike-kata/tree/3-equals-test">github starting point</a>)</p>
<p>This video illustrates the frequency of feedback. The example test-drives creating an <code>equals</code>-method. This task is often not worth test-driving. The resulting method is usually simple and/or generated by your IDE. But it is a good example to of how quick the cycle between test and production code <em>can</em> be when you&#8217;re writing tests that are close to the problem at hand. When I pair program this part of the kata, we usually use a technique called ping-pong programming: One programmer writes a failing test (or failing assertion) and hands the keyboard to his partner, the other programmer makes the test pass and writes another failing test before passing the keyboard back. On a good run, we will switch who&#8217;s got the keyboard more often than once per minute.</p>
<p>Notice that I also focus on the <em>behavior</em> of the <code>equals</code>-method in this test.</p>
<h3>Idea 4: Grow the API rather than designing it up front</h3>
<p><embed src="http://blip.tv/play/AYHWhEwA" type="application/x-shockwave-flash" width="480" height="380" allowscriptaccess="always" allowfullscreen="true"></embed></p>
<p>(8 minutes, <a href="http://github.com/jhannes/java-ee-spike-kata/tree/4-search-for-people">github starting point</a>)</p>
<p>As the web application grows under my fingers, I discover the need for a Data Access Object (DAO). However, as this represents a major internal interface in my application, I use Mockito to mock the implementation until I&#8217;m done with the behavior of my servlet. When this is done, I test-drive the implementation of the DAO in a separate test class.</p>
<p>The video also illustrates another important lesson: The code is getting ripe for a refactoring. But it&#8217;s important to resist the urge to refactor until the tests are green. If you refactor on red tests, you have much higher chances of running down a dead-end road and you&#8217;ll have to throw away your progress, wondering what went wrong.</p>
<p>The example uses <a href="http://mockito.org">Mockito</a> to mock out the DAO API.</p>
<p>If you want to see how I implement the DAO with Hibernate, you can see the video on <a href="http://jhannes.blip.tv/file/3487456/">blip.tv</a>.</p>
<h3>Idea 5: Grow the design rather than speculating</h3>
<p><embed src="http://blip.tv/play/AYHWhEsA" type="application/x-shockwave-flash" width="480" height="380" allowscriptaccess="always" allowfullscreen="true"></embed></p>
<p>(3 minutes, <a href="http://github.com/jhannes/java-ee-spike-kata/tree/5-2-refactoring">github starting point</a>)</p>
<p>The video is only a partial example of this principle. Throughout the whole application, I&#8217;ve been refactoring, gradually pulling out structure to more well-structured methods and classes. The video illustrates some of the power of IDE&#8217;s when it comes to refactoring. Using the IDE to massage your code into a better design makes evolutionary design much easier to do in practice. Make sure to learn your IDE&#8217;s most useful refactorings!</p>
<p>The kata may seem like a non-realistic example at this time, but I&#8217;ve actually grown a very successful architecture on my current project using much the same approach. If you want to explore where to go next, the next step needed for this application is to factor out the views into separate classes and then use either a <a href="http://martinfowler.com/eaaCatalog/templateView.html">View Template</a> language (like Velocity) or a <a href="http://martinfowler.com/eaaCatalog/transformView.html">View Transformer</a> (using, for example dom4j) to generate the HTML. (Let me know if you&#8217;d like to see the screencast of this as well).</p>
<h3>Idea 6: It&#8217;s supposed to work the first time around</h3>
<p><embed src="http://blip.tv/play/AYHWhF8A" type="application/x-shockwave-flash" width="480" height="380" allowscriptaccess="always" allowfullscreen="true"></embed></p>
<p>(5 minutes, <a href="http://github.com/jhannes/java-ee-spike-kata/tree/6-getting-it-to-work">github starting point</a>)</p>
<p>In this video, I return to the first test, <code>PersonWebTest</code>, to finish the configuration of the application. I discover a few mistakes I made in the web test as I complete the exercise. Then I try out the code in the browser. And all the scenarios I had planned for work out of the box.</p>
<p>When you try out your code for the first time, it should work. When you master test-driven development, you will probably forget how you programs <em>didn&#8217;t</em> use to work the first time. Only when you occasionally run into an unexpected error during manual testing it becomes clear how test-driven development changes you life.</p>
<p>If you want to see the whole, uninterrupted 75 minute code kata, the video is available at <a href="http://jhannes.blip.tv/file/3487566/">blip.tv</a>. You can also take a look at the finished source code at <a href="http://github.com/jhannes/java-ee-spike-kata/tree/commit_per_test">github</a>.</p>
<p>Happy programming!</p>
<hr />
<p><em>A big thanks to Trond, Thomas, Ram and Christian who helped improve this post. Thank you to Finn-Robert, Øistein, Mats, Anders, Siv, Peyman, Ivar, Øystein, Cecilia, Nicolay, and Karianne who have pair-programmed this exercise with me. I especially appreciate how Ivar and Karianne both helped influence the way the application is wired together and showed me that even after 30 iterations, I still had things to learn; and how Øistein showed me how two trained developers could complete the exercise faster with pair-programming than alone. And thank you to Nicolay who graciously brought food to our pair-programming exercise.</em></p>
<p>The videos were made with the excellent (and free!) <a href="http://www.bbsoftware.co.uk/BBFlashBack_FreePlayer.aspx">BB FlashBack Express</a>. The keyboard echo is courtesy of <a href="http://katastrophos.net/magnus/blog/2008/08/01/keypose-flavour-your-screencasts-with-shortcuts/">KeyPosé</a> by Magnus Jungsbluth.</p>
]]></content:encoded>
			<wfw:commentRss>http://johannesbrodwall.com/2010/05/02/six-ideas-that-improve-your-software-design/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Why TDD makes a lot of sense for Sudoko</title>
		<link>http://johannesbrodwall.com/2010/04/06/why-tdd-makes-a-lot-of-sense-for-sudoko/</link>
		<comments>http://johannesbrodwall.com/2010/04/06/why-tdd-makes-a-lot-of-sense-for-sudoko/#comments</comments>
		<pubDate>Tue, 06 Apr 2010 15:59:02 +0000</pubDate>
		<dc:creator>Johannes Brodwall</dc:creator>
				<category><![CDATA[Extreme Programming]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[video]]></category>

		<guid isPermaLink="false">http://johannesbrodwall.com/?p=526</guid>
		<description><![CDATA[My colleague Thomas sent me a <a href="http://devgrind.com/2007/04/25/how-to-not-solve-a-sudoku/">very interesting link</a> about attempts to solve Sudoku using test-driven development. The article, somewhat unfairly, pits Ron Jeffries' explorations of Sudoku using test-driven development against Peter Norvig's "design driven" approach.

I found both attempts lacking. However, while Ron Jeffries freely admitted that he didn't even know the rules of Sudoku when he started, both Norvig himself and his readers fawn over his solution. I didn't find it very understandable.

So I took it upon myself to examine the problem myself. I did some up-front thinking in the shower and on the subway, then attacked the problem with TDD. I ended up with a solution that works in <em>all</em> cases (unlike Norvig). My implementation has readable code, readable tests, and solves the problem reasonably fast.

<h3>Observations and conjectures</h3>

Here are a few things I learned from the exercise:

<ul>
  <li>When you're using TDD to solve a tricky algorithm, you have to think about both the algorithm and the test approach.</li>
  <li>Solving a problem with a known algorithm using TDD gives more readable code than I otherwise would expect.</li>
  <li>When I solved the problem with TDD, running the solution on real problems worked the very first time I tried it.</li>
  <li>The trick to making TDD work is to work from the outside in.</li>
  <li>When creating a Sudoku solver, don't think like a human! Think like a machine! The human algorithm is difficult to understand and likely to not work on all problems. This was the biggest problem with Norvig's code</li>
</ul>

<h3>The journey</h3>

I decided on the following approach:

<ol>
  <li>I had decided upon an initial design with a solver class and a board class. The solver should use a recursive depth first search. The solver asks the board what options exists per cell, but it has no knowledge of the rules of Sudoku (such as no duplicate numbers on the same row).</li>
  <li>The first step was to get the solver ("the outside") correct. For this step, I mocked out the board</li>
  <li>The second step was to implement the interface that the solver needed for the board. Mainly, this is a matter of specifying the rules for what numbers can occur in which cell on a Sudoku board.</li>
  <li>Finally, I wrote some code to read and write the Sudoku board. When trying the solver on real problems, it worked the first time, and solved <a href="http://magictour.free.fr/top95">95 hard problems</a> correct. It was somewhat slow, though.</li>
</ol>

After solving the problem the first time, I practices a few times and recorded a screen cast of the solution:

<embed src="http://blip.tv/play/AYHTrDcA" type="application/x-shockwave-flash" width="480" height="380" allowscriptaccess="always" allowfullscreen="true"></embed>

<h3>The solver</h3>

Testing the solver is a matter of creating a mock board and ensuring that the solver does the correct things. This is the most complex test case:

<pre lang="java">
@Test
public void shouldBacktrackWhenNoMoreOptions() throws Exception {
    SudokuSolver solver = new SudokuSolver();
    SudokuBoard board = mock(SudokuBoard.class);
    when(board.getOptionsForCell(anyInt(), anyInt()))
            .thenReturn(singleOption());

    when(board.getOptionsForCell(8, 7))
            .thenReturn(moreOptions(1, 2));
    when(board.getOptionsForCell(8, 8))
            .thenReturn(noOptions())
            .thenReturn(singleOption());

    assertThat(solver.findSolution(board)).isTrue();
    InOrder order = inOrder(board);
    order.verify(board).setValueInCell(1, 8,7);
    order.verify(board).setValueInCell(2, 8,7);
}
</pre>

It specifies that all cells, except (8,7) and (8,8) return exactly one option. (8,7) returns two options. (8,8) returns no options the first time it is called, and one option the second time. The test verifies that a solution is found, and the solver tries to set both options for (8,7).

This drives a rather simple algorithm. Here's basically the whole algorithm:

<pre lang="java">
public boolean findSolution(Board board, int cell) {
    if (cell == SIZE*SIZE) return true;

    boolean wasEmpty = board.isEmpty(row(cell), col(cell));
    for (Integer value : board.getCellOptions(row(cell), col(cell))) {
        board.setValueInCell(value, row(cell), col(cell));
        if (findSolution(board, cell+1)) return true;
    }
    if (wasEmpty) board.clearValueInCell(row(cell), col(cell));

    return false;
}
</pre>

The algorithm tries all available options for a cell in order. If no solution works for the rest of the board, the algorithm returns false (for "no solution").

The algorithm is not how a human would solve Sudoku. But then again, we're not writing a tutorial on how to solve Sudoku, we're writing a <em>program</em> that solves Sudoku.
The board

As I implemented the solver, the interface for the board started to emerge. At that point in time, I had to create tests for the Sudoku board itself. A typical test verifies that the board doesn't allow duplicate values in a row:

<pre lang="java">
@Test
public void shouldDisallowOptionsInSameRow() throws Exception {
    int row = 4;
    board.setValueInCell(1, row, 5);
    board.setValueInCell(2, row, 8);
    board.setValueInCell(3, row+1, 5);
    assertThat(board.getOptionsForCell(row, 0))
            .excludes(1,2).contains(3);
}
</pre>

The essence of SudokuBoard is finding out what values are legal in an open cell:

<pre lang="java">
public List getOptionsForCell(int row, int col) {
    if (!isEmpty(row,col)) return Arrays.asList(cells[row][col]);
    List result = allOptions();
    removeAllInRow(result, row);
    removeAllInCol(result, col);
    removeAllInBox(result, row, col);
    return result;
}
</pre>

<h3>TDD as a design guide</h3>

I invite you to compare <a href="http://norvig.com/sudoku.html">Peter Norvig's solution</a> to mine (you can find the full source code for my solution in <a href="http://github.com/jhannes/sudoku-kata">my github repository</a>).

It would probably have been possible for me to code the solution faster without tests, but it probably would not have worked the first time I tried it. I also would have much less confidence in the code. Finally, I think the design imposed by the tests made my code easier to understand.
]]></description>
			<content:encoded><![CDATA[<p>My colleague Thomas sent me a <a href="http://devgrind.com/2007/04/25/how-to-not-solve-a-sudoku/">very interesting link</a> about attempts to solve Sudoku using test-driven development. The article, somewhat unfairly, pits Ron Jeffries&#8217; explorations of Sudoku using test-driven development against Peter Norvig&#8217;s &#8220;design driven&#8221; approach.</p>
<p>I found both attempts lacking. However, while Ron Jeffries freely admitted that he didn&#8217;t even know the rules of Sudoku when he started, both Norvig himself and his readers fawn over his solution. I didn&#8217;t find it very understandable.</p>
<p>So I took it upon myself to examine the problem myself. I did some up-front thinking in the shower and on the subway, then attacked the problem with TDD. I ended up with a solution that works in <em>all</em> cases (unlike Norvig). My implementation has readable code, readable tests, and solves the problem reasonably fast.</p>
<h3>Observations and conjectures</h3>
<p>Here are a few things I learned from the exercise:</p>
<ul>
<li>When you&#8217;re using TDD to solve a tricky algorithm, you have to think about both the algorithm and the test approach.</li>
<li>Solving a problem with a known algorithm using TDD gives more readable code than I otherwise would expect.</li>
<li>When I solved the problem with TDD, running the solution on real problems worked the very first time I tried it.</li>
<li>The trick to making TDD work is to work from the outside in.</li>
<li>When creating a Sudoku solver, don&#8217;t think like a human! Think like a machine! The human algorithm is difficult to understand and likely to not work on all problems. This was the biggest problem with Norvig&#8217;s code</li>
</ul>
<h3>The journey</h3>
<p>I decided on the following approach:</p>
<ol>
<li>I had decided upon an initial design with a solver class and a board class. The solver should use a recursive depth first search. The solver asks the board what options exists per cell, but it has no knowledge of the rules of Sudoku (such as no duplicate numbers on the same row).</li>
<li>The first step was to get the solver (&#8220;the outside&#8221;) correct. For this step, I mocked out the board</li>
<li>The second step was to implement the interface that the solver needed for the board. Mainly, this is a matter of specifying the rules for what numbers can occur in which cell on a Sudoku board.</li>
<li>Finally, I wrote some code to read and write the Sudoku board. When trying the solver on real problems, it worked the first time, and solved <a href="http://magictour.free.fr/top95">95 hard problems</a> correct. It was somewhat slow, though.</li>
</ol>
<p>After solving the problem the first time, I practices a few times and recorded a screen cast of the solution:</p>
<p><embed src="http://blip.tv/play/AYHTrDcA" type="application/x-shockwave-flash" width="480" height="380" allowscriptaccess="always" allowfullscreen="true"></embed></p>
<h3>The solver</h3>
<p>Testing the solver is a matter of creating a mock board and ensuring that the solver does the correct things. This is the most complex test case:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Test
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> shouldBacktrackWhenNoMoreOptions<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span> <span style="color: #009900;">&#123;</span>
    SudokuSolver solver <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> SudokuSolver<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    SudokuBoard board <span style="color: #339933;">=</span> mock<span style="color: #009900;">&#40;</span>SudokuBoard.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    when<span style="color: #009900;">&#40;</span>board.<span style="color: #006633;">getOptionsForCell</span><span style="color: #009900;">&#40;</span>anyInt<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, anyInt<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
            .<span style="color: #006633;">thenReturn</span><span style="color: #009900;">&#40;</span>singleOption<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    when<span style="color: #009900;">&#40;</span>board.<span style="color: #006633;">getOptionsForCell</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">8</span>, <span style="color: #cc66cc;">7</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
            .<span style="color: #006633;">thenReturn</span><span style="color: #009900;">&#40;</span>moreOptions<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    when<span style="color: #009900;">&#40;</span>board.<span style="color: #006633;">getOptionsForCell</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">8</span>, <span style="color: #cc66cc;">8</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
            .<span style="color: #006633;">thenReturn</span><span style="color: #009900;">&#40;</span>noOptions<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
            .<span style="color: #006633;">thenReturn</span><span style="color: #009900;">&#40;</span>singleOption<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    assertThat<span style="color: #009900;">&#40;</span>solver.<span style="color: #006633;">findSolution</span><span style="color: #009900;">&#40;</span>board<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">isTrue</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    InOrder order <span style="color: #339933;">=</span> inOrder<span style="color: #009900;">&#40;</span>board<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    order.<span style="color: #006633;">verify</span><span style="color: #009900;">&#40;</span>board<span style="color: #009900;">&#41;</span>.<span style="color: #006633;">setValueInCell</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">8</span>,<span style="color: #cc66cc;">7</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    order.<span style="color: #006633;">verify</span><span style="color: #009900;">&#40;</span>board<span style="color: #009900;">&#41;</span>.<span style="color: #006633;">setValueInCell</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">8</span>,<span style="color: #cc66cc;">7</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>It specifies that all cells, except (8,7) and (8,8) return exactly one option. (8,7) returns two options. (8,8) returns no options the first time it is called, and one option the second time. The test verifies that a solution is found, and the solver tries to set both options for (8,7).</p>
<p>This drives a rather simple algorithm. Here&#8217;s basically the whole algorithm:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> findSolution<span style="color: #009900;">&#40;</span>Board board, <span style="color: #000066; font-weight: bold;">int</span> cell<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>cell <span style="color: #339933;">==</span> SIZE<span style="color: #339933;">*</span>SIZE<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">true</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000066; font-weight: bold;">boolean</span> wasEmpty <span style="color: #339933;">=</span> board.<span style="color: #006633;">isEmpty</span><span style="color: #009900;">&#40;</span>row<span style="color: #009900;">&#40;</span>cell<span style="color: #009900;">&#41;</span>, col<span style="color: #009900;">&#40;</span>cell<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Integer</span> value <span style="color: #339933;">:</span> board.<span style="color: #006633;">getCellOptions</span><span style="color: #009900;">&#40;</span>row<span style="color: #009900;">&#40;</span>cell<span style="color: #009900;">&#41;</span>, col<span style="color: #009900;">&#40;</span>cell<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        board.<span style="color: #006633;">setValueInCell</span><span style="color: #009900;">&#40;</span>value, row<span style="color: #009900;">&#40;</span>cell<span style="color: #009900;">&#41;</span>, col<span style="color: #009900;">&#40;</span>cell<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>findSolution<span style="color: #009900;">&#40;</span>board, cell<span style="color: #339933;">+</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">true</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>wasEmpty<span style="color: #009900;">&#41;</span> board.<span style="color: #006633;">clearValueInCell</span><span style="color: #009900;">&#40;</span>row<span style="color: #009900;">&#40;</span>cell<span style="color: #009900;">&#41;</span>, col<span style="color: #009900;">&#40;</span>cell<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The algorithm tries all available options for a cell in order. If no solution works for the rest of the board, the algorithm returns false (for &#8220;no solution&#8221;).</p>
<p>The algorithm is not how a human would solve Sudoku. But then again, we&#8217;re not writing a tutorial on how to solve Sudoku, we&#8217;re writing a <em>program</em> that solves Sudoku.<br />
The board</p>
<p>As I implemented the solver, the interface for the board started to emerge. At that point in time, I had to create tests for the Sudoku board itself. A typical test verifies that the board doesn&#8217;t allow duplicate values in a row:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Test
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> shouldDisallowOptionsInSameRow<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">int</span> row <span style="color: #339933;">=</span> <span style="color: #cc66cc;">4</span><span style="color: #339933;">;</span>
    board.<span style="color: #006633;">setValueInCell</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span>, row, <span style="color: #cc66cc;">5</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    board.<span style="color: #006633;">setValueInCell</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">2</span>, row, <span style="color: #cc66cc;">8</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    board.<span style="color: #006633;">setValueInCell</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">3</span>, row<span style="color: #339933;">+</span><span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">5</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    assertThat<span style="color: #009900;">&#40;</span>board.<span style="color: #006633;">getOptionsForCell</span><span style="color: #009900;">&#40;</span>row, <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
            .<span style="color: #006633;">excludes</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span>,<span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">contains</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">3</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The essence of SudokuBoard is finding out what values are legal in an open cell:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">List</span> getOptionsForCell<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> row, <span style="color: #000066; font-weight: bold;">int</span> col<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>isEmpty<span style="color: #009900;">&#40;</span>row,col<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #003399;">Arrays</span>.<span style="color: #006633;">asList</span><span style="color: #009900;">&#40;</span>cells<span style="color: #009900;">&#91;</span>row<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>col<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #003399;">List</span> result <span style="color: #339933;">=</span> allOptions<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    removeAllInRow<span style="color: #009900;">&#40;</span>result, row<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    removeAllInCol<span style="color: #009900;">&#40;</span>result, col<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    removeAllInBox<span style="color: #009900;">&#40;</span>result, row, col<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">return</span> result<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h3>TDD as a design guide</h3>
<p>I invite you to compare <a href="http://norvig.com/sudoku.html">Peter Norvig&#8217;s solution</a> to mine (you can find the full source code for my solution in <a href="http://github.com/jhannes/sudoku-kata">my github repository</a>).</p>
<p>It would probably have been possible for me to code the solution faster without tests, but it probably would not have worked the first time I tried it. I also would have much less confidence in the code. Finally, I think the design imposed by the tests made my code easier to understand.</p>
]]></content:encoded>
			<wfw:commentRss>http://johannesbrodwall.com/2010/04/06/why-tdd-makes-a-lot-of-sense-for-sudoko/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>My first katacast</title>
		<link>http://johannesbrodwall.com/2009/12/31/my-first-katacast/</link>
		<comments>http://johannesbrodwall.com/2009/12/31/my-first-katacast/#comments</comments>
		<pubDate>Thu, 31 Dec 2009 10:29:13 +0000</pubDate>
		<dc:creator>Johannes Brodwall</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Extreme Programming]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[video]]></category>

		<guid isPermaLink="false">http://johannesbrodwall.com/?p=500</guid>
		<description><![CDATA[After seeing some of the great examples of coders working on practiced problems on <a href="http://www.katacasts.com/">KataCasts</a>, I decided to try make my own. I am not happy with the pacing of the video. I'm about a minute too early relative to the music.

But I thought I'd post the video here, to see what you all think. Comments are welcome!

I hope the video will demonstrate how to use refactoring effectively to drive the design of a program.

I chose the FizzBuzz kata - that is, to generate a sequence of numbers where every number divisible by three is replaced by "fizz" and every number divisible by five is replaced by "five". The music changes to be more aggressive just as I induce a new requirement into the kata: The FizzBuzz generator should be programmable, so, in the kata, numbers divisible by two are replaced by "coconut" and numbers divisible by seven are replaced by "banana".

Thanks to Emily Bache for the inspiration for the kata.

Enjoy!

<object width="400" height="300"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=8459948&#38;server=vimeo.com&#38;show_title=1&#38;show_byline=1&#38;show_portrait=0&#38;color=&#38;fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id=8459948&#38;server=vimeo.com&#38;show_title=1&#38;show_byline=1&#38;show_portrait=0&#38;color=&#38;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="400" height="300"></embed></object><p><a href="http://vimeo.com/8459948">Fizz buzz code kata</a> from <a href="http://vimeo.com/user2873956">Johannes Brodwall</a> on <a href="http://vimeo.com">Vimeo</a>.</p>

The video was made with <a href="http://www.jetbrains.com/idea/free_java_ide.html">IntelliJ IDEA Community Edition</a> on Windows Vista (!) with <a href="http://www.bbsoftware.co.uk/BBFlashBack_FreePlayer.aspx?cc=true">BB FlashBack Express</a> (free screen recorder), converted to AVI with Windows Media 1 codec and uploaded to Vimeo.]]></description>
			<content:encoded><![CDATA[<p>After seeing some of the great examples of coders working on practiced problems on <a href="http://www.katacasts.com/">KataCasts</a>, I decided to try make my own. I am not happy with the pacing of the video. I&#8217;m about a minute too early relative to the music.</p>
<p>But I thought I&#8217;d post the video here, to see what you all think. Comments are welcome!</p>
<p>I hope the video will demonstrate how to use refactoring effectively to drive the design of a program.</p>
<p>I chose the FizzBuzz kata &#8211; that is, to generate a sequence of numbers where every number divisible by three is replaced by &#8220;fizz&#8221; and every number divisible by five is replaced by &#8220;five&#8221;. The music changes to be more aggressive just as I induce a new requirement into the kata: The FizzBuzz generator should be programmable, so, in the kata, numbers divisible by two are replaced by &#8220;coconut&#8221; and numbers divisible by seven are replaced by &#8220;banana&#8221;.</p>
<p>Thanks to Emily Bache for the inspiration for the kata.</p>
<p>Enjoy!</p>
<p><object width="400" height="300"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=8459948&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id=8459948&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="400" height="300"></embed></object>
<p><a href="http://vimeo.com/8459948">Fizz buzz code kata</a> from <a href="http://vimeo.com/user2873956">Johannes Brodwall</a> on <a href="http://vimeo.com">Vimeo</a>.</p>
<p>The video was made with <a href="http://www.jetbrains.com/idea/free_java_ide.html">IntelliJ IDEA Community Edition</a> on Windows Vista (!) with <a href="http://www.bbsoftware.co.uk/BBFlashBack_FreePlayer.aspx?cc=true">BB FlashBack Express</a> (free screen recorder), converted to AVI with Windows Media 1 codec and uploaded to Vimeo.</p>
]]></content:encoded>
			<wfw:commentRss>http://johannesbrodwall.com/2009/12/31/my-first-katacast/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
