<?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; Java</title>
	<atom:link href="http://johannesbrodwall.com/category/java/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>Why and how to use Jetty in mission-critical production</title>
		<link>http://johannesbrodwall.com/2010/03/08/why-and-how-to-use-jetty-in-mission-critical-production/</link>
		<comments>http://johannesbrodwall.com/2010/03/08/why-and-how-to-use-jetty-in-mission-critical-production/#comments</comments>
		<pubDate>Mon, 08 Mar 2010 22:48:22 +0000</pubDate>
		<dc:creator>Johannes Brodwall</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Meeting Summary]]></category>

		<guid isPermaLink="false">http://johannesbrodwall.com/?p=519</guid>
		<description><![CDATA[<blockquote>This article is a summary of a seminar I had on the topic. If it seems like it's a continuation of an existing discussion that's because, to some extent, it is. If you haven't been discussing exchanging your app server, this article probably isn't very interesting to you.</blockquote>

By putting the application server inside my application instead of the other way around, I was able to leap tall buildings in a single bound.]]></description>
			<content:encoded><![CDATA[<blockquote><p>This article is a summary of a seminar I had on the topic. If it seems like it&#8217;s a continuation of an existing discussion that&#8217;s because, to some extent, it is. If you haven&#8217;t been discussing exchanging your app server, this article probably isn&#8217;t very interesting to you.</p></blockquote>
<p>By putting the application server inside my application instead of the other way around, I was able to leap tall buildings in a single bound.</p>
<h3>The embedded application server</h3>
<p>This is how I build and deploy <a href="http://svn.brodwall.com/demo/embedded-container/">my sample application</a> to a new test environment (or to production):</p>
<ol>
<li><code>mvn install</code></li>
<li><code>scp <em>someapp</em>-server/target/<em>someapp</em>-1.0.onejar.jar appuser@appserver:/home/appuser/test-env1/</code></li>
<li><code>ssh appuser@appserver "cd /home/appuser/test-env1/ &#038;&#038; java -jar <em>someapp</em>-1.0.onejar.jar&amp;"</code></li>
</ol>
<p>This require no prior installed software on the appserver (with the exception of the JVM). It requires no prior configuration. Rolling back is a matter of replacing one jar-file with another. Clustering is a matter of deploying the same application several times.</p>
<p>In order to make this work in a real environment, there are a many details you as a developer need to take care of. As a matter of fact, you will have to take responsibility for your operational environment. The good news is that creating a good operational environment is not more time-consuming than trying to cope with the feed and care of a big-a Application Server.</p>
<p>In this scheme every application comes with its own application server in the form of jetty&#8217;s jar-files embedded in the deployed jar-file.</p>
<h3>The advantages</h3>
<p>Why would you want to do something like this?</p>
<ul>
<li><strong>Independent application</strong>: If you&#8217;ve ever been told that you can&#8217;t use Java 1.5 because that would require an upgrade of the application server. And if we upgrade the application server, that could affect someone else adversely. So we need to start a huge undertaking to find out who could possibly be affected.</li>
<li><strong>Developer managed libraries</strong>: Similar problems can occur with libraries. Especially those that come with the application server. For example: Oracle OC4J helpfully places a preview version of JPA 1.0 first in your classpath. If you want to use Hibernate with JPA 1.0-FINAL, it will mostly work. Until you try to use a annotation that was changed after the preview version (@Discriminator, for example). The general rule is: <em>If an API comes with your app server, you&#8217;re better served by staying away from it.</em> A rather bizarre state of affairs.</li>
<li><strong>Deployment, configuration and upgrades</strong>: Each version of the application, including all its dependencies is packaged into a single jar-file that can be deployed on several application server, or several times on the same application server (with different ports). The configuration is read from a properties-file in the current working directory. On the minus side, there&#8217;s no fancy web UI where you can step through a wizard to deploy the application or change the configuration. On the plus side, there is no fancy web UI &#8230;. If you&#8217;ve used one such web UI, you know what I mean.</li>
<li><strong>Continuous deployment</strong>: As your maven-repository will contain stand alone applications, creating a continuous deployment scheme is very easy. In my previous environment, a cron job running wget periodically was all that was needed to connect the dots. Having each server environment PULL the latest version gives a bit more flexibility if you want many test environments. (However, if you&#8217;re doing automated PUSH deployment, it&#8217;s probably just as practical for you).</li>
<li><strong>Same code in test and production</strong>: The fact that you can <a href="http://svn.brodwall.com/demo/embedded-container/embedded-container-web/src/test/java/no/steria/embeddedcontainer/web/HelloWebTest.java">start Jetty inside a plain old JUnit test</a> means that it is ideal for taking your automated tests one step further. However, if you test with Jetty and deploy on a different Application Server, the difference will occasionally trip you. It&#8217;s not a big deal. You have to test in the server environment anyway. But why not eliminate the extra source of pain if you can?</li>
<li><strong>Licenses</strong>: Sure, you can afford to pay a few million $ for an application server. You probably don&#8217;t have any better use for that money, anyway, right? However, if you have to pay licenses for each test-server in addition, it will probably mean that you will test less. We don&#8217;t want that.</li>
<li><strong>Operations</strong>: In my experience, operations people don&#8217;t like to mess around with the internals of an Application Server. An executable jar file plus a script that can be run with [start|status|stop] may be a much better match.</li>
</ul>
<h3>The missing bits</h3>
<p>Taking control of the application server takes away a lot of complex technology. This simplifies and makes a lot of stuff cheaper. It also puts you back in control of the environment. However, it forces you to think about some things that might&#8217;ve been solved for you before:</p>
<ul>
<li><strong>Monitoring</strong>: The first step of monitoring is simple: Just make sure you write to a log file that is being monitored by your operations department. The second step requires some work: Create a servlet (or a Jetty Handler) that a monitoring tool can ping to check that everything is okay. Taking control of this means that you can improve it: Check if your data sources can connect, if your file share is visible, if that service answers. Maybe add application-calibrated load reporting. Beyond that, Jetty has good JMX support, but I&#8217;ve never needed it myself.</li>
<li><strong>Load balancing</strong>: My setup supports no load balancing or failover out of the box. However, this is normally something that the web server or routers in front of the application server anyway. You might want to look into <a href="http://docs.codehaus.org/display/JETTY/Configuring+mod_proxy">Jetty&#8217;s options for session affinity</a>, if you need that.</li>
<li><strong>Security</strong>: Jetty supports JAAS, of course. Also: In all the environments I&#8217;ve been working with (CA SiteMinder, Sun OpenSSO, Oracle SSO), the SSO server sends the user name of the currently logged in user as an HTTP header. You can get far by just using that.</li>
<li><strong>Consistency</strong>: If you deploy more than one application as an embedded application server, the file structure used by an application (if any) should be standardized. As should the commands to start and stop the application. And the location of logs. Beyond that, reuse what you like, recreate what you don&#8217;t.</li>
</ul>
<h3>Taking control of your destiny</h3>
<p>Using an embedded application server means using the application server as a library instead of a framework. It means taking control of your &#8220;main&#8221; method. There&#8217;s a surprisingly small number of things you need to work out yourself. In exchange, you get the control to do many things that are impossible with a big-A Application Server.</p>
<p><em>Thanks to Dicksen, Eivind, Terje, Kristian and Kristian for a fun discussion on Jetty as a production app server</em></p>
]]></content:encoded>
			<wfw:commentRss>http://johannesbrodwall.com/2010/03/08/why-and-how-to-use-jetty-in-mission-critical-production/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Using Eclipse Better</title>
		<link>http://johannesbrodwall.com/2010/02/18/using-eclipse-better/</link>
		<comments>http://johannesbrodwall.com/2010/02/18/using-eclipse-better/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 19:16:05 +0000</pubDate>
		<dc:creator>Johannes Brodwall</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://johannesbrodwall.com/?p=509</guid>
		<description><![CDATA[I've pair programmed <a href="http://johannesbrodwall.com/2009/12/23/observations-from-katas/">the Java EE spike kata</a> in Eclipse with a number of people, I've found that a number of keyboard short cuts and preference settings recur as useful new information. I've compiled the most popular ones in this article. The article is subject to change, but I won't change the number of shortcuts.

<h3>Top five shortcuts</h3>

There are some keyboard short cuts that everyone who uses Eclipse should know:

<ul>
  <li><strong>ctrl-1 (quick fix):</strong> You hopefully use this shortcut to get quick fix support for compiler errors and warnings. Did you know that you can also use it to assign parameters to new fields, rename variables, and invert if-statements and equals-checks? Learn to think of <em>ctrl-1</em> as asking Eclipse "what can you do make the code better (or just different)?"</li>
  <li><strong>ctrl-space (complete):</strong> Again, you hopefully know that you can use ctrl-space to complete the name of variables and method names. But did you know that you can type "<code>equa&#60;ctrl-space></code>" in the class body and have Eclipse override the equals-method for you? Or that you can type "<code>getNam&#60;ctrl-space></code>" and have Eclipse create the whole implementation of a getter for name (if there's a name-field in the class). Or that you can type "<code>Test&#60;ctrl-space></code>" and have Eclipse fill in the Test code template. Think of <em>ctrl-space</em> as asking Eclipse "guess what I'm about to write"</li>
  <li><strong>ctrl-f6 (next editor):</strong> Use this to cycle between open files. It really should've been bound to <em>ctrl-tab</em>, but you can do this yourself.</li>
  <li><strong>f3 (go to definition):</strong> Place the cursor on a method call or variable usage and press <em>f3</em> to go to it's definition.</li>
  <li><strong>ctrl-shift-t (open type):</strong> A nifty dialog to go to any class in your project. Did you know that typing <code>PerCoT</code> will take you to <code>PersonControllerTest</code>?</li>
</ul>

<h3>Top ten runner ups</h3>

Here are some eye-openers that people enjoy learning:

<ul>
  <li><strong>alt-ctrl-down (copy current line):</strong> Creates a new copy of the line under the cursor on the next line. Without wiping the clipboard! Try it while selecting several lines, too</li>
  <li><strong>alt-down (move current line):</strong> Moves the line under the cursor down one line. Works with <em>alt-up</em>, too. And with a number of lines selected. A quick way to move code around with the keyboard.</li>
  <li><strong>alt-shift-left (extend selection):</strong> Progressively selects a larger syntactic element in the editor. Hard to explain. Try it out!</li>
  <li><strong>ctrl-shift-m (static import):</strong> Replace a call to <code>Assert.assertEquals</code> with a static import of the <code>org.junit.Assert.assertEquals</code> and a call to <code>assertEquals</code>.</li>
  <li><strong>ctrl-F11 (rerun latest command):</strong> To run for example the same test again, you can usually press <em>ctrl-f11</em>. Sadly, a few years back the Eclipse team tried to improve this and failed. Fix it under <em>Windows->Preferences, Run/Debug -> Launching</em>. Change "Launch operation" to "Always launch previous".</li>
  <li><strong>f12 (activate editor):</strong> When you perform an operation where some other pane got the focus, use <em>f12</em> to return to the editor again.</li>
  <li><strong>ctrl-N (new &#60;something>):</strong> Create a new class, XML file or whatever. Be sure to use the filter</li>
  <li><strong>alt-shift-l (extract local variable):</strong> My favorite refactoring. Select an expression and press <em>alt-shift-l</em> to assign it to a local variable and replace all uses of the expression with that variable.</li>
  <li><strong>alt-shift-m (extract method):</strong> Your bread and butter refactoring to split up complex logic in understandable units.</li>
  <li><strong>alt-shift-i (inline method/inline variable):</strong> The inverse of both <em>alt-shift-l</em> and <em>alt-shift-m</em>. Together, these three refactorings let you resculpt your code while being certain that the behavior is unaltered.</li>
</ul>

<h3>Top three properties to change</h3>

When I sit down with new programmers, I almost always help them make the following changes in the preferences. Find the preferences under Window->Preferences:

<ul>
  <li><strong>Use ctrl-tab (and ctrl-shift-tab) to switch between open editors:</strong> Go to <em>General->Keys</em>, type in "next editor" in the filter. Select "Copy command" and type "ctrl-tab" in the Binding field. Do the same for "previous editor" and ctrl-shift-tab.</li>
  <li><strong>Type filter:</strong> Do you wonder why Eclipse can't understand that when you say List, you mean <code>java.util.List</code>, not <code>org.hibernate.mapping.List</code> or (ye gods!) <code>java.awt.List</code>. Well, you can make Eclipse understand. Put classes and packages you don't like under <em>Java->Appearance->Type filters</em>. If your project is like mine, putting org.hibernate.mapping.*, antlr.*, java.awt.List, and com.sun.* in the list makes List unique to java.util.List. Then "organize imports" and completion works as you want.</li>
  <li><strong>Static import favorites:</strong> Do you find yourself using static imports with the same few classes again and again? The preference <em>Java->Editor->Content Assist->Favorites</em> lets you list up classes which will have their static methods checked when you press ctrl-space to complete a method call. <code>org.junit.Assert.*</code> is a good first candidate.</li>
</ul>

<h3>Learning your tool</h3>

All IDEs are rich and powerful tools. Spending some time to learn a few new tricks is well worth the effort.]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve pair programmed <a href="http://johannesbrodwall.com/2009/12/23/observations-from-katas/">the Java EE spike kata</a> in Eclipse with a number of people, I&#8217;ve found that a number of keyboard short cuts and preference settings recur as useful new information. I&#8217;ve compiled the most popular ones in this article. The article is subject to change, but I won&#8217;t change the number of shortcuts.</p>
<h3>Top five shortcuts</h3>
<p>There are some keyboard short cuts that everyone who uses Eclipse should know:</p>
<ul>
<li><strong>ctrl-1 (quick fix):</strong> You hopefully use this shortcut to get quick fix support for compiler errors and warnings. Did you know that you can also use it to assign parameters to new fields, rename variables, and invert if-statements and equals-checks? Learn to think of <em>ctrl-1</em> as asking Eclipse &#8220;what can you do make the code better (or just different)?&#8221;</li>
<li><strong>ctrl-space (complete):</strong> Again, you hopefully know that you can use ctrl-space to complete the name of variables and method names. But did you know that you can type &#8220;<code>equa&lt;ctrl-space></code>&#8221; in the class body and have Eclipse override the equals-method for you? Or that you can type &#8220;<code>getNam&lt;ctrl-space></code>&#8221; and have Eclipse create the whole implementation of a getter for name (if there&#8217;s a name-field in the class). Or that you can type &#8220;<code>Test&lt;ctrl-space></code>&#8221; and have Eclipse fill in the Test code template. Think of <em>ctrl-space</em> as asking Eclipse &#8220;guess what I&#8217;m about to write&#8221;</li>
<li><strong>ctrl-f6 (next editor):</strong> Use this to cycle between open files. It really should&#8217;ve been bound to <em>ctrl-tab</em>, but you can do this yourself.</li>
<li><strong>f3 (go to definition):</strong> Place the cursor on a method call or variable usage and press <em>f3</em> to go to it&#8217;s definition.</li>
<li><strong>ctrl-shift-t (open type):</strong> A nifty dialog to go to any class in your project. Did you know that typing <code>PerCoT</code> will take you to <code>PersonControllerTest</code>?</li>
</ul>
<h3>Top ten runner ups</h3>
<p>Here are some eye-openers that people enjoy learning:</p>
<ul>
<li><strong>alt-ctrl-down (copy current line):</strong> Creates a new copy of the line under the cursor on the next line. Without wiping the clipboard! Try it while selecting several lines, too</li>
<li><strong>alt-down (move current line):</strong> Moves the line under the cursor down one line. Works with <em>alt-up</em>, too. And with a number of lines selected. A quick way to move code around with the keyboard.</li>
<li><strong>alt-shift-left (extend selection):</strong> Progressively selects a larger syntactic element in the editor. Hard to explain. Try it out!</li>
<li><strong>ctrl-shift-m (static import):</strong> Replace a call to <code>Assert.assertEquals</code> with a static import of the <code>org.junit.Assert.assertEquals</code> and a call to <code>assertEquals</code>.</li>
<li><strong>ctrl-F11 (rerun latest command):</strong> To run for example the same test again, you can usually press <em>ctrl-f11</em>. Sadly, a few years back the Eclipse team tried to improve this and failed. Fix it under <em>Windows->Preferences, Run/Debug -> Launching</em>. Change &#8220;Launch operation&#8221; to &#8220;Always launch previous&#8221;.</li>
<li><strong>f12 (activate editor):</strong> When you perform an operation where some other pane got the focus, use <em>f12</em> to return to the editor again.</li>
<li><strong>ctrl-N (new &lt;something>):</strong> Create a new class, XML file or whatever. Be sure to use the filter</li>
<li><strong>alt-shift-l (extract local variable):</strong> My favorite refactoring. Select an expression and press <em>alt-shift-l</em> to assign it to a local variable and replace all uses of the expression with that variable.</li>
<li><strong>alt-shift-m (extract method):</strong> Your bread and butter refactoring to split up complex logic in understandable units.</li>
<li><strong>alt-shift-i (inline method/inline variable):</strong> The inverse of both <em>alt-shift-l</em> and <em>alt-shift-m</em>. Together, these three refactorings let you resculpt your code while being certain that the behavior is unaltered.</li>
</ul>
<h3>Top three properties to change</h3>
<p>When I sit down with new programmers, I almost always help them make the following changes in the preferences. Find the preferences under Window->Preferences:</p>
<ul>
<li><strong>Use ctrl-tab (and ctrl-shift-tab) to switch between open editors:</strong> Go to <em>General->Keys</em>, type in &#8220;next editor&#8221; in the filter. Select &#8220;Copy command&#8221; and type &#8220;ctrl-tab&#8221; in the Binding field. Do the same for &#8220;previous editor&#8221; and ctrl-shift-tab.</li>
<li><strong>Type filter:</strong> Do you wonder why Eclipse can&#8217;t understand that when you say List, you mean <code>java.util.List</code>, not <code>org.hibernate.mapping.List</code> or (ye gods!) <code>java.awt.List</code>. Well, you can make Eclipse understand. Put classes and packages you don&#8217;t like under <em>Java->Appearance->Type filters</em>. If your project is like mine, putting org.hibernate.mapping.*, antlr.*, java.awt.List, and com.sun.* in the list makes List unique to java.util.List. Then &#8220;organize imports&#8221; and completion works as you want.</li>
<li><strong>Static import favorites:</strong> Do you find yourself using static imports with the same few classes again and again? The preference <em>Java->Editor->Content Assist->Favorites</em> lets you list up classes which will have their static methods checked when you press ctrl-space to complete a method call. <code>org.junit.Assert.*</code> is a good first candidate.</li>
</ul>
<h3>Learning your tool</h3>
<p>All IDEs are rich and powerful tools. Spending some time to learn a few new tricks is well worth the effort.</p>
]]></content:encoded>
			<wfw:commentRss>http://johannesbrodwall.com/2010/02/18/using-eclipse-better/feed/</wfw:commentRss>
		<slash:comments>8</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>
		<item>
		<title>Observations from katas</title>
		<link>http://johannesbrodwall.com/2009/12/23/observations-from-katas/</link>
		<comments>http://johannesbrodwall.com/2009/12/23/observations-from-katas/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 11:56:50 +0000</pubDate>
		<dc:creator>Johannes Brodwall</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://johannesbrodwall.com/?p=497</guid>
		<description><![CDATA[Lately, I've been working on two code katas, that is, programming exercises that I repeat until the motions are secure in my muscle memory. The katas I've chosen are:

<ul>
  <li><strong>Java EE Spike</strong>: An application that stores People with names to a database and lets me search for them. I've repeated this pair programming with several different programmers.</li>
  <li><strong>Programmable Fizz Buzz</strong>: Create a sequence of numbers 1,2,fizz,4,buzz,fizz,... you know the one. And the twist: Make it programmable, so that for example numbers divisible by 7 should be replaced with "coconut".</li>
</ul>

I've learned a lot from repeating these exercises:

<ul>
  <li>Using test-driven development it takes me longer to get to something that "should work in principle", but shorter to get to something that works correctly.</li>
  <li>When refactoring to a new data structure, add the new structure while keeping the old one, make switching between them as simple as changing a single line. Delete the old when it works.</li>
  <li>There's always an automated refactoring you still want to help you out. Extract Parameter Object was my big one.</li>
  <li>Writing for example a method invocation and then using quickfix to have the IDE generate the method is the quickest way of writing code available to you.</li>
  <li>After 8 iterations, the Java EE Spike takes me 80 minutes solo. Pair programming with another programmer who had practiced: 65 minutes. I don't know why!</li>
  <li>Pair programming a moderately complex kata like the Java EE Spike is fun. It's also a good chance to discuss different roles of different tests.</li>
  <li>There is a huge difference between a test that takes 3 seconds to run and one that takes 0.5 seconds when you're test driving. More surprisingly, there's a big difference between a test that takes 0.5 seconds and one that takes 0.01 seconds</li>
  <li>If you think test-driven development is not for you or that it's bunk, you probably write really slow tests.</li>
</ul>

What are your latest coding observations?
]]></description>
			<content:encoded><![CDATA[<p>Lately, I&#8217;ve been working on two code katas, that is, programming exercises that I repeat until the motions are secure in my muscle memory. The katas I&#8217;ve chosen are:</p>
<ul>
<li><strong>Java EE Spike</strong>: An application that stores People with names to a database and lets me search for them. I&#8217;ve repeated this pair programming with several different programmers.</li>
<li><strong>Programmable Fizz Buzz</strong>: Create a sequence of numbers 1,2,fizz,4,buzz,fizz,&#8230; you know the one. And the twist: Make it programmable, so that for example numbers divisible by 7 should be replaced with &#8220;coconut&#8221;.</li>
</ul>
<p>I&#8217;ve learned a lot from repeating these exercises:</p>
<ul>
<li>Using test-driven development it takes me longer to get to something that &#8220;should work in principle&#8221;, but shorter to get to something that works correctly.</li>
<li>When refactoring to a new data structure, add the new structure while keeping the old one, make switching between them as simple as changing a single line. Delete the old when it works.</li>
<li>There&#8217;s always an automated refactoring you still want to help you out. Extract Parameter Object was my big one.</li>
<li>Writing for example a method invocation and then using quickfix to have the IDE generate the method is the quickest way of writing code available to you.</li>
<li>After 8 iterations, the Java EE Spike takes me 80 minutes solo. Pair programming with another programmer who had practiced: 65 minutes. I don&#8217;t know why!</li>
<li>Pair programming a moderately complex kata like the Java EE Spike is fun. It&#8217;s also a good chance to discuss different roles of different tests.</li>
<li>There is a huge difference between a test that takes 3 seconds to run and one that takes 0.5 seconds when you&#8217;re test driving. More surprisingly, there&#8217;s a big difference between a test that takes 0.5 seconds and one that takes 0.01 seconds</li>
<li>If you think test-driven development is not for you or that it&#8217;s bunk, you probably write really slow tests.</li>
</ul>
<p>What are your latest coding observations?</p>
]]></content:encoded>
			<wfw:commentRss>http://johannesbrodwall.com/2009/12/23/observations-from-katas/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Å trene på Java EE</title>
		<link>http://johannesbrodwall.com/2009/12/02/trene-pa-java-ee/</link>
		<comments>http://johannesbrodwall.com/2009/12/02/trene-pa-java-ee/#comments</comments>
		<pubDate>Wed, 02 Dec 2009 19:25:52 +0000</pubDate>
		<dc:creator>Johannes Brodwall</dc:creator>
				<category><![CDATA[Extreme Programming]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Norsk]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://johannesbrodwall.com/?p=489</guid>
		<description><![CDATA[For å bli bedre må man trene. For å bli bedre med avanserte ting, må man forstå de grunnleggende tingene bra. For å vite hvorfor man bruker avanserte verktøy, må man prøve å jobbe uten dem. Derfor har jeg de siste ukene trent mange ganger på å lage en veldig enkel webapplikasjon i Java. For hele applikasjonen har jeg startet med å skrive testene før koden som implementerer funksjonaliteten.

Dersom du vil prøve deg på samme øvelse, inneholder denne artikkelen litt informasjon for å komme i gang. Start med koden under og <em>følg feilmeldingene.</em> Send en kommentar dersom du ikke kommer videre fra en feilmelding, så får vi en FAQ.

<h3>Oppgaven</h3>

Løs et så enkelt som mulig problem som involverer websider og database med så enkel teknologi om mulig.

Oppgaven jeg har laget går ut på å <em>opprette personer med fullt navn og søke etter personer basert på navnet deres</em>. For å gjøre oppgaven så lite som mulig har jeg valgt å la personer kun ha ett informasjonsfelt: Fullt navn. Denne oppgaven tar cirka 2-3 timer uten øvelse og du kan få den ned i 60-90 minutter med trening.

Du kan naturligvis velge en annen oppgave, men uansett hva du velger: Det er mer lærerikt å gjenta den samme oppgaven flere ganger enn å utføre en avansert oppgave.

Når jeg utfører oppgaven er det viktigste jeg lærer meg å forstå feilmeldingene som guider meg gjennom utviklingen. Dersom du trenger hjelp til å komme til de første feilmeldingene kan du se resten av artikkelen.
]]></description>
			<content:encoded><![CDATA[<p>For å bli bedre må man trene. For å bli bedre med avanserte ting, må man forstå de grunnleggende tingene bra. For å vite hvorfor man bruker avanserte verktøy, må man prøve å jobbe uten dem. Derfor har jeg de siste ukene trent mange ganger på å lage en veldig enkel webapplikasjon i Java. For hele applikasjonen har jeg startet med å skrive testene før koden som implementerer funksjonaliteten.</p>
<p>Dersom du vil prøve deg på samme øvelse, inneholder denne artikkelen litt informasjon for å komme i gang. Start med koden under og <em>følg feilmeldingene.</em> Send en kommentar dersom du ikke kommer videre fra en feilmelding, så får vi en FAQ.</p>
<h3>Oppgaven</h3>
<p>Løs et så enkelt som mulig problem som involverer websider og database med så enkel teknologi om mulig.</p>
<p>Oppgaven jeg har laget går ut på å <em>opprette personer med fullt navn og søke etter personer basert på navnet deres</em>. For å gjøre oppgaven så lite som mulig har jeg valgt å la personer kun ha ett informasjonsfelt: Fullt navn. Denne oppgaven tar cirka 2-3 timer uten øvelse og du kan få den ned i 60-90 minutter med trening.</p>
<p>Du kan naturligvis velge en annen oppgave, men uansett hva du velger: Det er mer lærerikt å gjenta den samme oppgaven flere ganger enn å utføre en avansert oppgave.</p>
<p>Når jeg utfører oppgaven er det viktigste jeg lærer meg å forstå feilmeldingene som guider meg gjennom utviklingen. Dersom du trenger hjelp til å komme til de første feilmeldingene kan du se resten av artikkelen.</p>
<p><!-- more --></p>
<h3>Steg for steg: Startpunktet</h3>
<p>Selv om jeg valgte veldig enkel teknologi for implementasjonen, har jeg valgt et større sett med biblioteker for å skrive testene. Jeg bruker følgende når jeg skriver testene:</p>
<ul>
<li>JUnit 4.6</li>
<li>Jetty 6.1.22</li>
<li>HSqlDb 1.8.0.10</li>
<li>WebDriver-HtmlUnit 0.6.1039</li>
<li>Mockito 1.8.0</li>
<li>FEST-assert 1.2 (ikke påkrevd, men gjør testene søtere)</li>
</ul>
<p>Den eneste teknologien jeg har valgt for implementasjonen er Servlet-API 2.5 og Hibernate-Annotations 3.4.0.GA.</p>
<p>For at du skal slippe å plundre så mye med avhengigheter før du kommer i gang har jeg laget en <a href="http://svn.brodwall.com/demo/java-ee-spike-kata/pom.xml">pom.xml</a>-fil som du kan ta utgangspunkt i.</p>
<h3>Web-tester</h3>
<p>For å starte utviklingen, er det lurt med en test som starter på utsiden av applikasjonen. Noe slikt:</p>
<ol>
<li>Start opp miljøet</li>
<li>Legg inn en person</li>
<li>Søk etter personen</li>
</ol>
<p>Slik kommer du i gang med en test som går mot en web applikasjon:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">int</span> SERVER_PICKS_PORT <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
org.<span style="color: #006633;">mortbay</span>.<span style="color: #006633;">jetty</span>.<span style="color: #006633;">Server</span> server <span style="color: #339933;">=</span> 
       <span style="color: #000000; font-weight: bold;">new</span> org.<span style="color: #006633;">mortbay</span>.<span style="color: #006633;">jetty</span>.<span style="color: #006633;">Server</span><span style="color: #009900;">&#40;</span>SERVER_PICKS_PORT<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
server.<span style="color: #006633;">addHandler</span><span style="color: #009900;">&#40;</span>
       <span style="color: #000000; font-weight: bold;">new</span> org.<span style="color: #006633;">mortbay</span>.<span style="color: #006633;">jetty</span>.<span style="color: #006633;">webapp</span>.<span style="color: #006633;">WebAppContext</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;src/main/webapp&quot;</span>, <span style="color: #0000ff;">&quot;/&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
server.<span style="color: #006633;">start</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000066; font-weight: bold;">int</span> serverPort <span style="color: #339933;">=</span> server.<span style="color: #006633;">getConnectors</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span>.<span style="color: #006633;">getLocalPort</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
org.<span style="color: #006633;">openqa</span>.<span style="color: #006633;">selenium</span>.<span style="color: #006633;">WebDriver</span> browser <span style="color: #339933;">=</span>
       <span style="color: #000000; font-weight: bold;">new</span> org.<span style="color: #006633;">openqa</span>.<span style="color: #006633;">selenium</span>.<span style="color: #006633;">htmlunit</span>.<span style="color: #006633;">HtmlUnitDriver</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
browser.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;http://localhost:&quot;</span> <span style="color: #339933;">+</span> serverPort <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;/&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
browser.<span style="color: #006633;">findElement</span><span style="color: #009900;">&#40;</span>By.<span style="color: #006633;">linkText</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Create person&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Dette oppsettet forventer å finne <code>web.xml</code>-fila på <code>src/main/webapp/WEB-INF/web.xml</code>.</p>
<h3>Funksjonell test</h3>
<p>En funksjonell test definerer <em>kravene</em> i applikasjonen. Det er lurt å gjøre funksjonelle tester så raske som overhode mulig, samtidig som de går gjennom alle kravene. En funksjonell test trenger ikke være en ende-til-ende test, slik som eksempelet over. Dette er viktig, fordi ende-til-ende tester er ofte veldig trege. Her er noen eksempler på funksjonelle tester:</p>
<ul>
<li>Vis en siden for å opprette nye personer</li>
<li>Opprett en ny person</li>
<li>Verifiser at personens navn er oppgitt og ikke inneholder ulovlige tegn</li>
<li>Vis en side for å søke etter personer</li>
<li>Vis alle personer dersom søkestreng ikke er angitt</li>
<li>Søk etter angitt søkestreng</li>
</ul>
<p>En funksjonell test kan se slik ut:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">PersonServlet servlet <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> PersonServlet<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
HttpServletRequest req <span style="color: #339933;">=</span>
    org.<span style="color: #006633;">mockito</span>.<span style="color: #006633;">Mockito</span>.<span style="color: #006633;">mock</span><span style="color: #009900;">&#40;</span>HttpServletRequest.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
HttpServletResponse resp <span style="color: #339933;">=</span>
    org.<span style="color: #006633;">mockito</span>.<span style="color: #006633;">Mockito</span>.<span style="color: #006633;">mock</span><span style="color: #009900;">&#40;</span>HttpServletResponse.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
PersonDao personDao <span style="color: #339933;">=</span>
    org.<span style="color: #006633;">mockito</span>.<span style="color: #006633;">Mockito</span>.<span style="color: #006633;">mock</span><span style="color: #009900;">&#40;</span>PersonDao.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
servlet.<span style="color: #006633;">setPersonDao</span><span style="color: #009900;">&#40;</span>personDao<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
org.<span style="color: #006633;">mockito</span>.<span style="color: #006633;">Mockito</span>.<span style="color: #006633;">when</span><span style="color: #009900;">&#40;</span>req.<span style="color: #006633;">getMethod</span><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><span style="color: #0000ff;">&quot;POST&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
org.<span style="color: #006633;">mockito</span>.<span style="color: #006633;">Mockito</span>.<span style="color: #006633;">when</span><span style="color: #009900;">&#40;</span>req.<span style="color: #006633;">getPathInfo</span><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><span style="color: #0000ff;">&quot;/create.html&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
org.<span style="color: #006633;">mockito</span>.<span style="color: #006633;">Mockito</span>.<span style="color: #006633;">when</span><span style="color: #009900;">&#40;</span>req.<span style="color: #006633;">getParameter</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;full_name&quot;</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><span style="color: #0000ff;">&quot;Johannes Brodwall&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #003399;">StringWriter</span> pageSource <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">StringWriter</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
org.<span style="color: #006633;">mockito</span>.<span style="color: #006633;">Mockito</span>.<span style="color: #006633;">when</span><span style="color: #009900;">&#40;</span>resp.<span style="color: #006633;">getWriter</span><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><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">PrintWriter</span><span style="color: #009900;">&#40;</span>pageSource<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
servlet.<span style="color: #006633;">service</span><span style="color: #009900;">&#40;</span>req, resp<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
org.<span style="color: #006633;">mockito</span>.<span style="color: #006633;">Mockito</span>.<span style="color: #006633;">verify</span><span style="color: #009900;">&#40;</span>personDao<span style="color: #009900;">&#41;</span>
    .<span style="color: #006633;">create</span><span style="color: #009900;">&#40;</span>Person.<span style="color: #006633;">byName</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Johannes Brodwall&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
org.<span style="color: #006633;">fest</span>.<span style="color: #006633;">assertions</span>.<span style="color: #006633;">Assertions</span>.<span style="color: #006633;">assertThat</span><span style="color: #009900;">&#40;</span>pageSource.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    .<span style="color: #006633;">contains</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Personen er opprettet&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<h3>Data-aksess-test</h3>
<p>Hibernate forenkler databasebruken mye. Men Hibernate er selv komplekst og når man bruker det på mer avanserte måter fortjener det egne tester. En typisk test med Hibernate kan være:</p>
<ol>
<li>Legg i tre personer i database</li>
<li>Søk etter en del av navnet på en av dem</li>
<li>Sjekk at du får tilbake akkurat den du forventet</li>
</ol>
<p>Når jeg starter med Hibernate, lager jeg en test som dette, og følger feilmeldingene. Pass på å både følge feilmeldinger i loggen og stack tracer.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">AnnotationConfiguration conf <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> AnnotationConfiguration<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    .<span style="color: #006633;">setProperty</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">Environment</span>.<span style="color: #003399;">URL</span>, <span style="color: #0000ff;">&quot;jdbc:hsqldb:mem:persondaotest&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
PersonDao dao <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> HibernatePersonDao<span style="color: #009900;">&#40;</span>conf.<span style="color: #006633;">buildSessionFactory</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
dao.<span style="color: #006633;">create</span><span style="color: #009900;">&#40;</span>Person.<span style="color: #006633;">withName</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;foo&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
org.<span style="color: #006633;">fest</span>.<span style="color: #006633;">assertions</span>.<span style="color: #006633;">Assertions</span>.<span style="color: #006633;">assertThat</span><span style="color: #009900;">&#40;</span>dao.<span style="color: #006633;">find</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    .<span style="color: #006633;">containsExactly</span><span style="color: #009900;">&#40;</span>Person.<span style="color: #006633;">withName</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;foo&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Følg feilmeldingene herfra.</p>
<h3>Integrasjon</h3>
<p>En veldig vanlig måte for web serveren å overlevere spesielt ting som DataSources til applikasjonen er via JNDI. I Jetty kan du gjøre dette i Web-testen på følgende måte:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">org.<span style="color: #006633;">hsqldb</span>.<span style="color: #006633;">jdbc</span>.<span style="color: #006633;">jdbcDataSource</span> ds <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> org.<span style="color: #006633;">hsqldb</span>.<span style="color: #006633;">jdbc</span>.<span style="color: #006633;">jdbcDataSource</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
ds.<span style="color: #006633;">setDatabase</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;jdbc:hsqldb:mem:personwebtest&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
ds.<span style="color: #006633;">setUser</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;sa&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">new</span> org.<span style="color: #006633;">mortbay</span>.<span style="color: #006633;">jetty</span>.<span style="color: #006633;">plus</span>.<span style="color: #006633;">naming</span>.<span style="color: #006633;">Resource</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;jdbc/primaryDs&quot;</span>, ds<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Oppstart av Jetty som vist over</span></pre></div></div>

<h3>Konklusjon</h3>
<p>Å gjøre en liten øvelse som dette er en god måte å bli bevisst hvilke vaner du har og hvor lang tid det egentlig tar for deg å gjøre oppgavene dine. Du vil oppleve at det å skrive tester før koden føles som om det går saktere enn du tror du er vant til.</p>
<p>Men dersom du er som meg, vil du også oppleve noe annet: Når du tester ut applikasjonen første gang (du kan gjøre dette med Jetty, naturligvis) så er sjansene gode for at den vil være nokså feilfri og at debugging i stor grad er overflødig. Jeg vet ikke med deg, men debugging er en aktivitet jeg gjerne blir kvitt.</p>
]]></content:encoded>
			<wfw:commentRss>http://johannesbrodwall.com/2009/12/02/trene-pa-java-ee/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Effective Enterprise Java at Öredev</title>
		<link>http://johannesbrodwall.com/2009/11/03/effective-enterprise-java-at-oredev/</link>
		<comments>http://johannesbrodwall.com/2009/11/03/effective-enterprise-java-at-oredev/#comments</comments>
		<pubDate>Tue, 03 Nov 2009 17:31:11 +0000</pubDate>
		<dc:creator>Johannes Brodwall</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://johannesbrodwall.com/?p=474</guid>
		<description><![CDATA[Just three weeks ago, I was asked to step in for Ted Neward to give a tutorial at Öredev on <a href="http://www.oredev.org/Prod/Oredev/site.nsf/docsbycodename/session?opendocument&#038;sid=2DDB2738A9A84259C125765D006D06EA&#038;day=2&#038;track=E92AC6A14535633BC12575A5004943A0">Effective Enterprise Java</a>. As I did not have time to get the tutorial materials printed, I present them here on the web for the participants and others.

<h3>1. Effect Enterprise Java architecture in 2009</h3>

Since the Effective Enterprise Java book was written, many of the topics regarding transactions, concurrency and shared state have been resolved. Here are the basic guidelines of an enterprise application in Java as of 2009:

<ol>
  <li>All processing is triggered by an event, such as an http-request, a timer or an incoming message</li>
  <li>Each processing event is handled in an isolated scope, never touching the data of another processing event. All coordination of data happens through the data layer. This means that objects are either stateful and short-lived or stateless and immortal.</li>
  <li>Each processing event is either completed or aborted totally. Very few applications will benefit from trying to automatically recover from most problems.</li>
  <li>Inconsistent updates are resolved when transactions are committed, usually through optimistic locking.</li>
</ol>

Some things I told the attendants to consider: First, today most people consider EJBs to be more trouble than value (with the exception of Entity beans 3.0 which is JPA which is really mostly Hibernate, which really isn't very much EJB). Second, all triggers can be forged. We return to the second issue when we discuss security.

<h3>2. Web integration testing</h3>

I showed a <a href="http://svn.brodwall.com/presentations/public/2009-11-03%20Enterprise%20Java%20Kata%20-%20%C3%98redev/src/test/java/com/brodwall/kata/webcrud/PersonWebTest.java">practical demo using WebDriver and Jetty</a> to perform web integration tests as JUnit test. The remarkable things about this example is that it requires no installation of an app server (Jetty is installed as a Maven dependency), it requires no separate starting of an application server (Jetty can run embedded in the test) and it is very fast (Jetty starts up in about 200 milliseconds).

<h3>3. Hibernate integration testing</h3>

I showed a <a href="http://svn.brodwall.com/presentations/public/2009-11-03%20Enterprise%20Java%20Kata%20-%20%C3%98redev/src/test/java/com/brodwall/kata/webcrud/HibernatePersonDaoTest.java">practical example of how to test a DAO implemented with Hibernate</a>. The remarkable things about this demonstration was that, again, no installation or startup is required (I use H2 as an in-memory database).

Hibernate is a power tool. I use the following analogy: If you're building a tunnel and need to mine through a mountain, you want to use dynamite. If you want to remove a rock from you back yard, you may want to use dynamite. But if you don't know what you're doing, chances are you may blow your foot off.

Hibernate is like that dynamite. You need knowledge and safety measures to deal with it correctly, but when you do, it can save you a lot of effort. Creating JUnit tests for your Hibernate code is one such safety measure.

<h3>4. Security</h3>

Almost all the threats an application developer should be concerned with are in the same class, namely that of Injection attacks. An injection attack is when a client tricks another process into treating data as instructions. For example by using SQL meta-characters:

<img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" alt="Little Bobby Tables" width="400" />

An important source of injection vulnerabilities is HTML injection, also known as Cross-Site Scripting (XSS).

In both situations, and in all others, there's one important guideline: Data from the outside world should be considered "tainted". Never use tainted data in unsafe ways. When reading input parameters, validate against malicious characters (but please don't make poor "O'Reiley" unable to use your system). When writing HTML pages, always escape tainted data. When using tainted data during access to the database or with HSQL or JPAQL, always use PreparedStatement and send in data as parameters.

Another often overlooked exploit is request forgery, often used in combination with phishing attacks. To protect your users from request forgery, supply an authentication token as a hidden field with all forms. Or if you're lazy: Make sure all operations have confirmation dialogs.

<h3>5. Continuous Deployment</h3>

Continuous Deployment is the practice of rolling out a deployment to a server after every successful build on your Continuous Integration server. I described two ways of doing Continuous Deployment during the tutorial, but I will restrict this discussion to the more modern one.

Most teams doing continuous deployment use Maven or Ant to invoke the deployment tools of their respective application servers. Many application servers make this pretty hard, but the hardest part of the battle if finding out what command needs to be invoked. The Continuous Integration server can be configured to run this task.

After doing deployment, it is a good idea to run some sort of system level integration tests. Teams use replay of production data, load generators like JMeter and webcrawlers that validate HTML and CSS to do automated non-functional integration tests. If you keep your logs clean, you can actually gain quite a bit of confidence just by looking at the logs after applying simulated load to your system.

Some projects take this even further, by continuously deploying to production. Both IMVU and Flickr are known to practice this.

At any rate, the practice of doing continuous deployment should lead you to consider how to simplify your deployment and runtime configuration, which will result in an easier installation procedure into production, even if it's not automated.

<h3>Summary</h3>

Effective Enterprise Java development has progressed a lot since 2004. Much of the emphasis now is on how to improve testing in enterprise Java applications. The way applications usually process data has stabilized as well, with most application preferring each event to be processed in an isolated, transactional context with very little automated recovery.

In the end, Effective Enterprise Java is a lot simpler in 2009 than it was in 2004.

<h3>Material</h3>

<ul>
  <li><a href="http://svn.brodwall.com/presentations/public/2009-11-03%20Effective%20Enterprise%20Java%20-%20%C3%98redev.ppt">My slides</a>, including topics that we didn't discuss as well as code for all the examples</li>
  <li>The complete source code for one iteration of my <a href="http://svn.brodwall.com/presentations/public/2009-11-03%20Enterprise%20Java%20Kata%20-%20%C3%98redev">Enterprise Java Kata</a>, including a <a href="http://svn.brodwall.com/presentations/public/2009-11-03%20Enterprise%20Java%20Kata%20-%20%C3%98redev/pom.xml">pom.xml</a> file with all dependencies needed to get the tests running</li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>Just three weeks ago, I was asked to step in for Ted Neward to give a tutorial at Öredev on <a href="http://www.oredev.org/Prod/Oredev/site.nsf/docsbycodename/session?opendocument&#038;sid=2DDB2738A9A84259C125765D006D06EA&#038;day=2&#038;track=E92AC6A14535633BC12575A5004943A0">Effective Enterprise Java</a>. As I did not have time to get the tutorial materials printed, I present them here on the web for the participants and others.</p>
<h3>1. Effect Enterprise Java architecture in 2009</h3>
<p>Since the Effective Enterprise Java book was written, many of the topics regarding transactions, concurrency and shared state have been resolved. Here are the basic guidelines of an enterprise application in Java as of 2009:</p>
<ol>
<li>All processing is triggered by an event, such as an http-request, a timer or an incoming message</li>
<li>Each processing event is handled in an isolated scope, never touching the data of another processing event. All coordination of data happens through the data layer. This means that objects are either stateful and short-lived or stateless and immortal.</li>
<li>Each processing event is either completed or aborted totally. Very few applications will benefit from trying to automatically recover from most problems.</li>
<li>Inconsistent updates are resolved when transactions are committed, usually through optimistic locking.</li>
</ol>
<p>Some things I told the attendants to consider: First, today most people consider EJBs to be more trouble than value (with the exception of Entity beans 3.0 which is JPA which is really mostly Hibernate, which really isn&#8217;t very much EJB). Second, all triggers can be forged. We return to the second issue when we discuss security.</p>
<h3>2. Web integration testing</h3>
<p>I showed a <a href="http://svn.brodwall.com/presentations/public/2009-11-03%20Enterprise%20Java%20Kata%20-%20%C3%98redev/src/test/java/com/brodwall/kata/webcrud/PersonWebTest.java">practical demo using WebDriver and Jetty</a> to perform web integration tests as JUnit test. The remarkable things about this example is that it requires no installation of an app server (Jetty is installed as a Maven dependency), it requires no separate starting of an application server (Jetty can run embedded in the test) and it is very fast (Jetty starts up in about 200 milliseconds).</p>
<h3>3. Hibernate integration testing</h3>
<p>I showed a <a href="http://svn.brodwall.com/presentations/public/2009-11-03%20Enterprise%20Java%20Kata%20-%20%C3%98redev/src/test/java/com/brodwall/kata/webcrud/HibernatePersonDaoTest.java">practical example of how to test a DAO implemented with Hibernate</a>. The remarkable things about this demonstration was that, again, no installation or startup is required (I use H2 as an in-memory database).</p>
<p>Hibernate is a power tool. I use the following analogy: If you&#8217;re building a tunnel and need to mine through a mountain, you want to use dynamite. If you want to remove a rock from you back yard, you may want to use dynamite. But if you don&#8217;t know what you&#8217;re doing, chances are you may blow your foot off.</p>
<p>Hibernate is like that dynamite. You need knowledge and safety measures to deal with it correctly, but when you do, it can save you a lot of effort. Creating JUnit tests for your Hibernate code is one such safety measure.</p>
<h3>4. Security</h3>
<p>Almost all the threats an application developer should be concerned with are in the same class, namely that of Injection attacks. An injection attack is when a client tricks another process into treating data as instructions. For example by using SQL meta-characters:</p>
<p><img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" alt="Little Bobby Tables" width="400" /></p>
<p>An important source of injection vulnerabilities is HTML injection, also known as Cross-Site Scripting (XSS).</p>
<p>In both situations, and in all others, there&#8217;s one important guideline: Data from the outside world should be considered &#8220;tainted&#8221;. Never use tainted data in unsafe ways. When reading input parameters, validate against malicious characters (but please don&#8217;t make poor &#8220;O&#8217;Reiley&#8221; unable to use your system). When writing HTML pages, always escape tainted data. When using tainted data during access to the database or with HSQL or JPAQL, always use PreparedStatement and send in data as parameters.</p>
<p>Another often overlooked exploit is request forgery, often used in combination with phishing attacks. To protect your users from request forgery, supply an authentication token as a hidden field with all forms. Or if you&#8217;re lazy: Make sure all operations have confirmation dialogs.</p>
<h3>5. Continuous Deployment</h3>
<p>Continuous Deployment is the practice of rolling out a deployment to a server after every successful build on your Continuous Integration server. I described two ways of doing Continuous Deployment during the tutorial, but I will restrict this discussion to the more modern one.</p>
<p>Most teams doing continuous deployment use Maven or Ant to invoke the deployment tools of their respective application servers. Many application servers make this pretty hard, but the hardest part of the battle if finding out what command needs to be invoked. The Continuous Integration server can be configured to run this task.</p>
<p>After doing deployment, it is a good idea to run some sort of system level integration tests. Teams use replay of production data, load generators like JMeter and webcrawlers that validate HTML and CSS to do automated non-functional integration tests. If you keep your logs clean, you can actually gain quite a bit of confidence just by looking at the logs after applying simulated load to your system.</p>
<p>Some projects take this even further, by continuously deploying to production. Both IMVU and Flickr are known to practice this.</p>
<p>At any rate, the practice of doing continuous deployment should lead you to consider how to simplify your deployment and runtime configuration, which will result in an easier installation procedure into production, even if it&#8217;s not automated.</p>
<h3>Summary</h3>
<p>Effective Enterprise Java development has progressed a lot since 2004. Much of the emphasis now is on how to improve testing in enterprise Java applications. The way applications usually process data has stabilized as well, with most application preferring each event to be processed in an isolated, transactional context with very little automated recovery.</p>
<p>In the end, Effective Enterprise Java is a lot simpler in 2009 than it was in 2004.</p>
<h3>Material</h3>
<ul>
<li><a href="http://svn.brodwall.com/presentations/public/2009-11-03%20Effective%20Enterprise%20Java%20-%20%C3%98redev.ppt">My slides</a>, including topics that we didn&#8217;t discuss as well as code for all the examples</li>
<li>The complete source code for one iteration of my <a href="http://svn.brodwall.com/presentations/public/2009-11-03%20Enterprise%20Java%20Kata%20-%20%C3%98redev">Enterprise Java Kata</a>, including a <a href="http://svn.brodwall.com/presentations/public/2009-11-03%20Enterprise%20Java%20Kata%20-%20%C3%98redev/pom.xml">pom.xml</a> file with all dependencies needed to get the tests running</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://johannesbrodwall.com/2009/11/03/effective-enterprise-java-at-oredev/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Testing Servlets with Mockito</title>
		<link>http://johannesbrodwall.com/2009/10/24/testing-servlets-with-mockito/</link>
		<comments>http://johannesbrodwall.com/2009/10/24/testing-servlets-with-mockito/#comments</comments>
		<pubDate>Sat, 24 Oct 2009 16:54:51 +0000</pubDate>
		<dc:creator>Johannes Brodwall</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://johannesbrodwall.com/?p=466</guid>
		<description><![CDATA[When I write Java-projects that produce web pages, I test on several levels. First, I use Jetty and WebDriver to test the result via http. (WebDriver even lets me test JavaScript!)

But for speed and agility, unit-level tests beat even the fastest integration level tests. Unit tests run much much faster, and lets me pinpoint problems much more accurately. As a general rule: If you introduce a bug, you want a unit test to be the one that sees it first.

For web applications in Java, I've found the following pattern useful when testing classes that deal with <code>HttpServletRequest</code> and <code>HttpServletResponse</code>:

<pre lang="java">
@Test
public void shouldDecodeSearchParameters() throws IOException {
    HttpServletRequest req = mock(HttpServletRequest.class);
    HttpServletResponse resp = mock(HttpServletResponse.class);
    Repository repository = mock(Repository.class);

    PersonController personController =
            new PersonController(req, resp, repository);

    given(req.getParameter("firstName")).willReturn("johannes");
    given(req.getParameter("lastName")).willReturn("brodwall");
    given(req.getParameter("includePaidMembers"))
            .willReturn("true");
    given(req.getParameter("includeUnpaidMembers"))
            .willReturn("false");
    when(resp.getWriter())
            .thenReturn(new PrintWriter(new StringWriter()));

    personController.find();

    ArgumentCaptor< PersonSpecification> specificationCapture = 
            ArgumentCaptor.forClass(PersonSpecification.class);
    verify(repository).find(specificationCapture.capture());

    PersonSpecification personSpec =
            specificationCapture.getValue();
    assertThat(personSpec.getFirstName()).isEqualTo("johannes");
    assertThat(personSpec.getLastName()).isEqualTo("brodwall");
    assertThat(personSpec.isIncludingPaidMembers())
         .isEqualTo(true);
    assertThat(personSpec.isIncludingUnpaidMembers())
         .isEqualTo(false);
}
</pre>

1: This example uses Mockito to specify what calls to <code>HttpServletRequest</code> should return. A really nice thing about Mockito is that you only have to specify what you care about. If, for example, <code>PersonController</code> ends up calling <code>req.getParameter("nonexistant")</code>, Mockito will simply return null. If <code>PersonContoller</code> asks for "lastName" several times, Mockito will keep returning "brodwall".

2: Mockito doesn't verify that a set of methods were called unless you explicitly ask it to. <code>PersonController</code> happens to call several methods on <code>HttpServletResponse</code> that we don't even mention in the test.

3: Mockito lets you look at what arguments were used to call a mocked-out method <strong>after the method was called</strong> by using an <code>ArgumentCaptor</code>.

One caveat, though: In the case of <code>HttpServletRequest</code>, the production code can decide to read the request parameters in several different ways: <code>getParameter</code>, <code>getParameterValues</code> or <code>getParameterMap</code>. Mockito will naturally not have any idea of the relationship between these methods, so your test will be sensitive to this sort of implementation change.

After working with EasyMock and JMock for a while, I seriously lost faith in mocking. Mockito has restored my faith again!

Happy testing!]]></description>
			<content:encoded><![CDATA[<p>When I write Java-projects that produce web pages, I test on several levels. First, I use Jetty and WebDriver to test the result via http. (WebDriver even lets me test JavaScript!)</p>
<p>But for speed and agility, unit-level tests beat even the fastest integration level tests. Unit tests run much much faster, and lets me pinpoint problems much more accurately. As a general rule: If you introduce a bug, you want a unit test to be the one that sees it first.</p>
<p>For web applications in Java, I&#8217;ve found the following pattern useful when testing classes that deal with <code>HttpServletRequest</code> and <code>HttpServletResponse</code>:</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> shouldDecodeSearchParameters<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;">IOException</span> <span style="color: #009900;">&#123;</span>
    HttpServletRequest req <span style="color: #339933;">=</span> mock<span style="color: #009900;">&#40;</span>HttpServletRequest.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    HttpServletResponse resp <span style="color: #339933;">=</span> mock<span style="color: #009900;">&#40;</span>HttpServletResponse.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #003399;">Repository</span> repository <span style="color: #339933;">=</span> mock<span style="color: #009900;">&#40;</span><span style="color: #003399;">Repository</span>.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    PersonController personController <span style="color: #339933;">=</span>
            <span style="color: #000000; font-weight: bold;">new</span> PersonController<span style="color: #009900;">&#40;</span>req, resp, repository<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    given<span style="color: #009900;">&#40;</span>req.<span style="color: #006633;">getParameter</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;firstName&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">willReturn</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;johannes&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    given<span style="color: #009900;">&#40;</span>req.<span style="color: #006633;">getParameter</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;lastName&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">willReturn</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;brodwall&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    given<span style="color: #009900;">&#40;</span>req.<span style="color: #006633;">getParameter</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;includePaidMembers&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
            .<span style="color: #006633;">willReturn</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;true&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    given<span style="color: #009900;">&#40;</span>req.<span style="color: #006633;">getParameter</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;includeUnpaidMembers&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
            .<span style="color: #006633;">willReturn</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;false&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    when<span style="color: #009900;">&#40;</span>resp.<span style="color: #006633;">getWriter</span><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><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">PrintWriter</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">StringWriter</span><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: #339933;">;</span>
&nbsp;
    personController.<span style="color: #006633;">find</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    ArgumentCaptor<span style="color: #339933;">&lt;</span> PersonSpecification<span style="color: #339933;">&gt;</span> specificationCapture <span style="color: #339933;">=</span> 
            ArgumentCaptor.<span style="color: #006633;">forClass</span><span style="color: #009900;">&#40;</span>PersonSpecification.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    verify<span style="color: #009900;">&#40;</span>repository<span style="color: #009900;">&#41;</span>.<span style="color: #006633;">find</span><span style="color: #009900;">&#40;</span>specificationCapture.<span style="color: #006633;">capture</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    PersonSpecification personSpec <span style="color: #339933;">=</span>
            specificationCapture.<span style="color: #006633;">getValue</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    assertThat<span style="color: #009900;">&#40;</span>personSpec.<span style="color: #006633;">getFirstName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">isEqualTo</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;johannes&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    assertThat<span style="color: #009900;">&#40;</span>personSpec.<span style="color: #006633;">getLastName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">isEqualTo</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;brodwall&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    assertThat<span style="color: #009900;">&#40;</span>personSpec.<span style="color: #006633;">isIncludingPaidMembers</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
         .<span style="color: #006633;">isEqualTo</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    assertThat<span style="color: #009900;">&#40;</span>personSpec.<span style="color: #006633;">isIncludingUnpaidMembers</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
         .<span style="color: #006633;">isEqualTo</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>1: This example uses Mockito to specify what calls to <code>HttpServletRequest</code> should return. A really nice thing about Mockito is that you only have to specify what you care about. If, for example, <code>PersonController</code> ends up calling <code>req.getParameter("nonexistant")</code>, Mockito will simply return null. If <code>PersonContoller</code> asks for &#8220;lastName&#8221; several times, Mockito will keep returning &#8220;brodwall&#8221;.</p>
<p>2: Mockito doesn&#8217;t verify that a set of methods were called unless you explicitly ask it to. <code>PersonController</code> happens to call several methods on <code>HttpServletResponse</code> that we don&#8217;t even mention in the test.</p>
<p>3: Mockito lets you look at what arguments were used to call a mocked-out method <strong>after the method was called</strong> by using an <code>ArgumentCaptor</code>.</p>
<p>One caveat, though: In the case of <code>HttpServletRequest</code>, the production code can decide to read the request parameters in several different ways: <code>getParameter</code>, <code>getParameterValues</code> or <code>getParameterMap</code>. Mockito will naturally not have any idea of the relationship between these methods, so your test will be sensitive to this sort of implementation change.</p>
<p>After working with EasyMock and JMock for a while, I seriously lost faith in mocking. Mockito has restored my faith again!</p>
<p>Happy testing!</p>
]]></content:encoded>
			<wfw:commentRss>http://johannesbrodwall.com/2009/10/24/testing-servlets-with-mockito/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Extreme Integration: The future of software development?</title>
		<link>http://johannesbrodwall.com/2009/08/11/extreme-integration-the-future-of-software-development/</link>
		<comments>http://johannesbrodwall.com/2009/08/11/extreme-integration-the-future-of-software-development/#comments</comments>
		<pubDate>Tue, 11 Aug 2009 14:20:25 +0000</pubDate>
		<dc:creator>Johannes Brodwall</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Extreme Programming]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://johannesbrodwall.com/?p=421</guid>
		<description><![CDATA[What will the daily experience of software development look like, say, five years from now? Have our current processes reached their peak, or will the world continue to change? Alan Kay said "the easiest way to predict the future is to invent it." Here are some ideas of the future I want to invent: I hope it will be dramatically better than what we currently do.

[caption id="" align="alignright" width="240" caption="Steel pipes (by monkeyc.net)"]<img alt="Steel pipes (by monkeyc.net)" src="http://farm1.static.flickr.com/33/101354216_6dbd65bd87_m.jpg" title="Steel pipes" width="240" height="160" />[/caption]

The term "Continuous Integration" was first discussed when Extreme Programming was starting to garner interest in the late 90s. From then, it has gone from being a manual process that top-notch team used, to being an automated, nearly ubiquitous process. The tools have gone from being home made through demanding tools like <a href="http://cruisecontrol.sourceforge.net/">CruiseControl</a> to user friendly tools like <a href="https://hudson.dev.java.net/">Hudson</a>. After Hudson, is there still any radical change in store for us?

Somewhat independent of the evolution of Continuous Integration tools, there have been four trends that have developed in the last few years:
<ul>
  <li>Continuous testing: Tools like <a href="http://www.zenspider.com/ZSS/Products/ZenTest/">autotest</a> for Ruby and Kent Beck's <a href="http://junitmax.com/junitmax/">JUnit Max</a> for Java execute your tests after every change you make to the source code. Autotest is widely used within the Rails community, and even though JUnit Max did not get the takeoff Kent was hoping for, I think there's still great potential in this sphere. I've used both tools, and they transform the way I work for the better.</li>
  <li>Distributed source control greatly increases our flexibility in terms of multiple sources and stages of source code. Especially <a href="http://git-scm.com/">Git</a> has seen growing interest in the last two years. <a href="http://github.com/">Github</a> is quickly becoming one of the large project hosting providers.</li>
  <li>Continuous deployment: Organizations have started pushing the result of their continuous integration process further towards production. In the last three years, I've worked on two large projects, both of which deploy every build to a test server. The company IMVU, with it's large customer base, <a href="http://timothyfitz.wordpress.com/2009/02/10/continuous-deployment-at-imvu-doing-the-impossible-fifty-times-a-day/">deploys automatically into production roughly 50 times per day</a>.</li>
  <li>Smaller checkins: In the last issue of <a href="http://agiletoolkit.libsyn.com/index.php?post_id=506912">The Agile Toolkit</a> George (no last name given in podcast or notes) suggest checking in every time your build is green. I've never worked on a project like that, but I've experienced a gradual increase in how frequently we check in.</li>
</ul>

[caption id="" align="alignleft" width="240" caption="Complexity (by nerovivo)"]<img alt="Complexity (by nerovivo)" src="http://farm1.static.flickr.com/182/384027019_5e64727276_m.jpg" title="Complexity" width="240" height="180" />[/caption]

If we extrapolate from these trends, where do they lead? Here is what I think will be the development experience of advanced teams in the future:

<ol>
  <li>Whenever I save a file, my (fast running) tests are run in the background.</li>
  <li>When all the tests run successfully, my changes are pushed up to my personal clone of the repository.
A first stage continuous integration server listens to changes from all the developers repositories. When it verifies the tests, it pushes the changes to the integrated repository.</li>
  <li>Every few minutes, my workspace is updated to reflect new changes from other developers in the integrated repository.</li>
  <li>After the integrated repository, similar build processes propagate code changes through slower, and possibly even manual tests. The verified result is stored in the staged repository.</li>
  <li>At the push of a button, I can roll the code from the staged repository into any test or production environment.</li>
</ol>

Sounds far fetched? Vincent Massol wrote about <a href="http://blogs.codehaus.org/people/vmassol/archives/000937_unbreakable_builds.html">unbreakable builds</a> five years ago. Distributed version control is being adopted quickly and will greatly simplify the implementation of such processes. Despite Kent Beck's <a href="http://www.threeriversinstitute.org/blog/?p=291">regretful decision</a> to stop active development of JUnit Max, I believe the time for continuous testing is near. The process I outline can include as enough verification steps to make the organization comfortable. As the trend of improving test quality continues, this process will be gradually more automated.

The strange thing is that we've almost made a complete circle: Before the widespread use of revision control, many developers would edit the code directly in their production environment. Extreme Integration will feel almost like this, but with enough non-intrusive verification to make even the most paranoid test manager happy.

<em>Thanks to Martin Eggen for digging up the information on IMVU's Continuous Deployment. Thanks to Sarah Brodwall, Trond Pedersen and Finn-Robert Kristensen for helpful comments.</em>
]]></description>
			<content:encoded><![CDATA[<p>What will the daily experience of software development look like, say, five years from now? Have our current processes reached their peak, or will the world continue to change? Alan Kay said &#8220;the easiest way to predict the future is to invent it.&#8221; Here are some ideas of the future I want to invent: I hope it will be dramatically better than what we currently do.</p>
<div class="wp-caption alignright" style="width: 250px"><img alt="Steel pipes (by monkeyc.net)" src="http://farm1.static.flickr.com/33/101354216_6dbd65bd87_m.jpg" title="Steel pipes" width="240" height="160" /><p class="wp-caption-text">Steel pipes (by monkeyc.net)</p></div>
<p>The term &#8220;Continuous Integration&#8221; was first discussed when Extreme Programming was starting to garner interest in the late 90s. From then, it has gone from being a manual process that top-notch team used, to being an automated, nearly ubiquitous process. The tools have gone from being home made through demanding tools like <a href="http://cruisecontrol.sourceforge.net/">CruiseControl</a> to user friendly tools like <a href="https://hudson.dev.java.net/">Hudson</a>. After Hudson, is there still any radical change in store for us?</p>
<p>Somewhat independent of the evolution of Continuous Integration tools, there have been four trends that have developed in the last few years:</p>
<ul>
<li>Continuous testing: Tools like <a href="http://www.zenspider.com/ZSS/Products/ZenTest/">autotest</a> for Ruby and Kent Beck&#8217;s <a href="http://junitmax.com/junitmax/">JUnit Max</a> for Java execute your tests after every change you make to the source code. Autotest is widely used within the Rails community, and even though JUnit Max did not get the takeoff Kent was hoping for, I think there&#8217;s still great potential in this sphere. I&#8217;ve used both tools, and they transform the way I work for the better.</li>
<li>Distributed source control greatly increases our flexibility in terms of multiple sources and stages of source code. Especially <a href="http://git-scm.com/">Git</a> has seen growing interest in the last two years. <a href="http://github.com/">Github</a> is quickly becoming one of the large project hosting providers.</li>
<li>Continuous deployment: Organizations have started pushing the result of their continuous integration process further towards production. In the last three years, I&#8217;ve worked on two large projects, both of which deploy every build to a test server. The company IMVU, with it&#8217;s large customer base, <a href="http://timothyfitz.wordpress.com/2009/02/10/continuous-deployment-at-imvu-doing-the-impossible-fifty-times-a-day/">deploys automatically into production roughly 50 times per day</a>.</li>
<li>Smaller checkins: In the last issue of <a href="http://agiletoolkit.libsyn.com/index.php?post_id=506912">The Agile Toolkit</a> George (no last name given in podcast or notes) suggest checking in every time your build is green. I&#8217;ve never worked on a project like that, but I&#8217;ve experienced a gradual increase in how frequently we check in.</li>
</ul>
<div class="wp-caption alignleft" style="width: 250px"><img alt="Complexity (by nerovivo)" src="http://farm1.static.flickr.com/182/384027019_5e64727276_m.jpg" title="Complexity" width="240" height="180" /><p class="wp-caption-text">Complexity (by nerovivo)</p></div>
<p>If we extrapolate from these trends, where do they lead? Here is what I think will be the development experience of advanced teams in the future:</p>
<ol>
<li>Whenever I save a file, my (fast running) tests are run in the background.</li>
<li>When all the tests run successfully, my changes are pushed up to my personal clone of the repository.<br />
A first stage continuous integration server listens to changes from all the developers repositories. When it verifies the tests, it pushes the changes to the integrated repository.</li>
<li>Every few minutes, my workspace is updated to reflect new changes from other developers in the integrated repository.</li>
<li>After the integrated repository, similar build processes propagate code changes through slower, and possibly even manual tests. The verified result is stored in the staged repository.</li>
<li>At the push of a button, I can roll the code from the staged repository into any test or production environment.</li>
</ol>
<p>Sounds far fetched? Vincent Massol wrote about <a href="http://blogs.codehaus.org/people/vmassol/archives/000937_unbreakable_builds.html">unbreakable builds</a> five years ago. Distributed version control is being adopted quickly and will greatly simplify the implementation of such processes. Despite Kent Beck&#8217;s <a href="http://www.threeriversinstitute.org/blog/?p=291">regretful decision</a> to stop active development of JUnit Max, I believe the time for continuous testing is near. The process I outline can include as enough verification steps to make the organization comfortable. As the trend of improving test quality continues, this process will be gradually more automated.</p>
<p>The strange thing is that we&#8217;ve almost made a complete circle: Before the widespread use of revision control, many developers would edit the code directly in their production environment. Extreme Integration will feel almost like this, but with enough non-intrusive verification to make even the most paranoid test manager happy.</p>
<p><em>Thanks to Martin Eggen for digging up the information on IMVU&#8217;s Continuous Deployment. Thanks to Sarah Brodwall, Trond Pedersen and Finn-Robert Kristensen for helpful comments.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://johannesbrodwall.com/2009/08/11/extreme-integration-the-future-of-software-development/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>
