<?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/"
	>

<channel>
	<title>Bugfree.dk - Ronnie Holm&#039;s blog &#187; Programming</title>
	<atom:link href="http://www.bugfree.dk/blog/tag/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bugfree.dk/blog</link>
	<description>Not anti-anything, just pro-quality</description>
	<lastBuildDate>Mon, 28 Nov 2011 07:32:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Printing iframe content using JavaScript</title>
		<link>http://www.bugfree.dk/blog/2009/12/17/printing-iframe-content-using-javascript/</link>
		<comments>http://www.bugfree.dk/blog/2009/12/17/printing-iframe-content-using-javascript/#comments</comments>
		<pubDate>Thu, 17 Dec 2009 21:50:41 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Html]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/?p=1005</guid>
		<description><![CDATA[JavaScript is on top of the list of things I’d like to become better at. So I was quite happy when assigned a JavaScript-related defect in an application at work. Apparently, there was a bug in the JavaScript routine used for printing only the content of an iframe on a page. Rather than printing only [...]]]></description>
			<content:encoded><![CDATA[<p>JavaScript is on top of the list of things I’d like to become better at. So I was quite happy when assigned a JavaScript-related defect in an application at work. Apparently, there was a bug in the JavaScript routine used for printing only the content of an iframe on a page. Rather than printing only the iframe’s content, it printed the page hosting the iframe, cropping parts of the iframe’s content.</p>
<p>I started out confident that printing would be easy to fix. But after Googling and playing around with JavaScript for a while, frustration, fueled by the number of non-working hits I’d stumbled on, started to grow on me. Suppose you start out with an HTML document hosting an iframe and a few lines of JavaScript.</p>
<pre class="prettyprint lang-html">  &lt;html&gt;
    &lt;head&gt;
      &lt;title&gt;IFrame printing example&lt;/title&gt;
      &lt;script type=&quot;text/javascript&quot;&gt;
        function myPrint() {
          var browser = navigator.appName;
          if (browser == &quot;Microsoft Internet Explorer&quot;) {
            window.frames[&quot;frame&quot;].focus();
            window.frames.print();
          }
          else if (browser == &quot;Netscape&quot;)
            alert(&quot;Printing not supported in Firefox&quot;);
        }
      &lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
      &lt;iframe id=&quot;frame&quot; name=&quot;frame&quot; width=&quot;100&quot;
              height=&quot;100&quot; src=&quot;http://google.com&quot;&gt;
      &lt;/iframe&gt;
      &lt;a href=&quot;#&quot; onclick=&quot;javascript:myPrint();&quot;&gt;Print&lt;/a&gt;
    &lt;/body&gt;
  &lt;/html&gt;</pre>
<p>A number of issues arise when printing the iframe. First you need to consider if you’re always hosting the main document on the same domain as the iframe’s source. If so, printing only the iframe with Internet Explorer works like a charm. If, on the other hand, the main document and the iframe’s source reside on different domains, it triggers Internet Explorer to displays a bar across the top of the window.</p>
<p><img src="http://www.bugfree.dk/blog/wp-content/uploads/2009/12/allow-blocked-content-browser-bar.png" /></p>
<p>Now, to print the iframe’s content, you must allow blocked content. Only then can JavaScript access the iframe’s object model. But at the same time, you make yourself vulnerable to <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">cross-site scripting attacks</a>.</p>
<p>As far as Firefox support goes, you can issue the same API calls as for Internet Explorer. But Firefox will always print the main page, including only the visible parts of the iframe. To my knowledge there’s no way to make Firefox print the iframe’s content as seamlessly as Internet Explorer. One workaround, though, would be to open a new window, grab a reference to the iframe element, and move its contents to the new window before printing it. For cross-domain content, however, Firefox responds with a “permission denied” error when accessing the iframe element. And there’s no option to allow blocked content. Another workaround may therefore be to use Ajax to retrieve the source of the iframe for any domain and insert it into the new window. That, however, wouldn’t work in my case since the iframe may contain a form that the user may have started filling out before hitting print.</p>
<p>As a last resort, I considered writing a proxy to retrieve cross-domain hosted content. This would make Internet Explorer never display the bar and allow Firefox to always open a new window with the iframe’s content loaded, even if the user started filling out a form first. But this approach sort of defies the purpose of the browser bar and the permission denied error. Unless you absolutely trust your iframe’s source, you’re exposing your users without their consent.</p>
<p>In the end I went with the simplest and most secure solution of not supporting printing at all.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2009%2F12%2F17%2Fprinting-iframe-content-using-javascript%2F&amp;title=Printing%20iframe%20content%20using%20JavaScript" id="wpa2a_2"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2009/12/17/printing-iframe-content-using-javascript/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Parallel page processing with Asp.Net</title>
		<link>http://www.bugfree.dk/blog/2009/11/26/parallel-page-processing-with-asp-net/</link>
		<comments>http://www.bugfree.dk/blog/2009/11/26/parallel-page-processing-with-asp-net/#comments</comments>
		<pubDate>Thu, 26 Nov 2009 09:02:00 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[Presentation]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/?p=993</guid>
		<description><![CDATA[(This post grew out of a presentation I did on the subject. Turn to the slides for more details, including code.) With Asp.Net, by default a page is rendered synchronously, one control at a time. The thread rendering the page comes from the thread pool within the world wide web worker process (w3wp.exe) and is [...]]]></description>
			<content:encoded><![CDATA[<p>(This post grew out of a presentation I did on the subject. Turn to the <a href="http://www.bugfree.dk/blog/wp-content/uploads/2009/11/Parallel page processing with Asp.Net.pdf">slides</a> for more details, including code.)</p>
<p>With Asp.Net, by default a page is rendered synchronously, one control at a time. The thread rendering the page comes from the thread pool within the world wide web worker process (w3wp.exe) and is assigned to the request when it comes in on the web server. Only when the page has fully rendered can the thread go back in the pool waiting for the next request.</p>
<p>Processing a complex page using only one thread, however, may cause the page to render slowly. The page may hold controls that require calls to web services, databases, or other external resources for it to render. Whenever the worker thread encounters such a control, it goes idle waiting for data to come back from the external resource. Only when data is received can the worker thread resume processing.</p>
<p>One way to speed up page processing would be for the page or control to explicitly make use of threads. Depending on the situation, this may be a cumbersome task that requires a significant amount of boiler-plate code. A simpler approach might be to turn to the Asp.Net 2.0 feature for asynchronous page processing. At its core is an extension to the page or control lifecycle.</p>
<p style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px">
<img src="http://www.bugfree.dk/blog/wp-content/uploads/2009/11/Comparable-page-lifecycles.gif" /><br/></p>
<p>Except for the <a href="http://msdn.microsoft.com/en-us/library/system.web.begineventhandler.aspx">Begin</a> and <a href="http://msdn.microsoft.com/en-us/library/system.web.endeventhandler.aspx">End</a> events, the flow is the same in both models. But while the synchronous model executes all code on a single thread, the asynchronous model makes implicit use of multiple worker threads to speed up page processing. With multiple threads, some threads still go idle waiting for input, but at least the main worker thread continues to work its way through the controls.</p>
<p>In the asynchronous model, we hook into the Begin and End handlers in one of the events preceding the call to Begin. Following PreRender, Asp.Net will then execute our Begin handler, where we call out to some method that carries out the long-running task. When that method exists the End handler is called and processing carries on as in the synchronous model.</p>
<p>To illustrate the flow and timing of the asynchronous model (turn to the slides for the complete code sample), suppose we add five controls to a page. Each control takes five seconds to render so using the synchronous model the page would take 25 seconds to render. Using the asynchronous model, and writing out trace information about which thread each method executes on, here&#8217;s what happens:</p>
<pre>1: Page_Load: 10            9: DoWork: 8
2: Page_Load: 10           10: DoWork: 11
3: Page_Load: 10           11: Render: 11 15:16:13 15:16:18
4: Page_Load: 10           12: Render: 11 15:16:13 15:16:18
5: Page_Load: 10           13: Render: 11 15:16:13 15:16:18
6: DoWork: 4               14: Render: 11 15:16:13 15:16:18
7: DoWork: 10              15: Render: 11 15:16:13 15:16:19
8: DoWork: 9</pre>
<p>The user control&#8217;s Page_Load and the code making up the Begin handler executes on the main worker thread. But the method carrying out the long-running task, and the code for the End handler, executes in parallel on different worker threads. Finally, after End is called, another worker thread takes over and executes the remaining parts of the control. Now page rendering has decreased from 25 to about five seconds.</p>
<p>All in all, little effort is required to make more efficient, and implicit, use of the thread pool, thereby decreasing the time required processing a page. Asynchronous page processing should be used judiciously, though. Optimizing away a bottleneck in the processing of a page may well lead to bottlenecks appearing elsewhere, e.g., the number of simultaneous calls made to a web service may be too much for it to handle.</p>
<p>For more details and examples, turn to <a href="http://www.wintellect.com/cs/blogs/jprosise/default.aspx">Jeff Prosise</a>&#8216;s article on <a href="http://msdn.microsoft.com/en-us/magazine/cc163725.aspx">Asynchronous Pages in Asp.Net 2.0</a>.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2009%2F11%2F26%2Fparallel-page-processing-with-asp-net%2F&amp;title=Parallel%20page%20processing%20with%20Asp.Net" id="wpa2a_4"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2009/11/26/parallel-page-processing-with-asp-net/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Why not to comment code</title>
		<link>http://www.bugfree.dk/blog/2009/08/15/why-not-to-comment-code/</link>
		<comments>http://www.bugfree.dk/blog/2009/08/15/why-not-to-comment-code/#comments</comments>
		<pubDate>Sat, 15 Aug 2009 19:55:24 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Quality]]></category>
		<category><![CDATA[Refactoring]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/?p=535</guid>
		<description><![CDATA[Update, Aug 18, 2009: I&#8217;m amazed at how much attention this post has received. More than 200 comments on Reddit. I was just listening to the Why comments are evil episode of Deep Fried Bytes. The views put forward by the guest, Corey Haines, deeply resonate with me because I believe they&#8217;re what every developer [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Update, Aug 18, 2009</strong>: I&#8217;m amazed at how much <a href="http://www.reddit.com/r/programming/comments/9b4ct/why_not_to_comment_code">attention</a> this post has received. More than 200 comments on Reddit.
</p>
<p>I was just listening to the <a href="http://deepfriedbytes.com/podcast/episode-35-why-comments-are-evil-and-pair-programming-with-corey-haines">Why comments are evil</a> episode of <a href="http://deepfriedbytes.com">Deep Fried Bytes</a>. The views put forward by the guest, <a href="http://www.coreyhaines.com/">Corey Haines</a>, deeply resonate with me because I believe they&#8217;re what every developer should strive for. I&#8217;m not advocating that code should be entirely free of comments, but rather that most comments do more harm than good.
</p>
<p>Below I&#8217;ve listed the main points of view.
</p>
<ul>
<li>It&#8217;s important to differentiate between code comments and API documentation. For API documentation, don&#8217;t auto-generate. Especially don&#8217;t go with tools like <a href="http://submain.com/products/ghostdoc.aspx">GhostDoc</a>. Take the time to document properly. Otherwise, you&#8217;re more likely to confuse the developer trying to make sense of your code.
</li>
<li>Stop focusing on having the computer understand you and start focusing on the person that comes after you, e.g., while there&#8217;s some overhead to method calls, unless the profiler tells you otherwise, don&#8217;t hesitate to break down a method into as many smaller methods as it takes to make it more approachable.
</li>
<li>Every time you&#8217;re tempted to comment, take the time to think if you can make the code tell its own story, e.g., instead of some branching condition, extract the condition into a method to emphasize the story of why over how.
</li>
<li>Developers comment to explain a confusing part of their code rather than take the time to <a href="http://en.wikipedia.org/wiki/Refactoring">refactor</a> it by extracting a method or naming a variable properly. Inevitably the code gets modified and the comment rots.
</li>
<li>Parts of a method may be complicated so a comment is added. Saying part of a method is complicated is in itself a sign that it&#8217;s doing too much.
</li>
<li>The prevailing culture among developers is to focus on what it takes to get code working. It&#8217;s a battle of short-term vs. long-term maintainability and short-term almost always comes out as the winner. Writing code, ask yourself if you&#8217;re able to immediately understand the code a month from now.
</li>
</ul>
<p>The opinions put forward in the episode aren&#8217;t new. Still, I find them well worth iterating because as developers we tend to not pay enough attention to them. We tend to focus too little on good <a href="http://manifesto.softwarecraftsmanship.org/">software craftsmanship</a>.  </p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2009%2F08%2F15%2Fwhy-not-to-comment-code%2F&amp;title=Why%20not%20to%20comment%20code" id="wpa2a_6"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2009/08/15/why-not-to-comment-code/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Basic logging guidelines</title>
		<link>http://www.bugfree.dk/blog/2009/07/22/basic-logging-guidelines/</link>
		<comments>http://www.bugfree.dk/blog/2009/07/22/basic-logging-guidelines/#comments</comments>
		<pubDate>Wed, 22 Jul 2009 11:28:22 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Logging]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Quality]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/?p=188</guid>
		<description><![CDATA[Next to unit testing I believe in logging to improve the quality of an application. Instrumenting code with logging (or tracing for that matter) should be an integral part of writing production code. Yet, I&#8217;ve often found it not to be the case or that what got logged only made sense to the developer who [...]]]></description>
			<content:encoded><![CDATA[<p>Next to <a href="http://www.bugfree.dk/blog/2009/06/19/basic-unit-testing-guidelines/">unit testing</a> I believe in logging to improve the quality of an application. Instrumenting code with <a href="http://en.wikipedia.org/wiki/Data_logging">logging</a> (or <a href="http://en.wikipedia.org/wiki/Tracing_(software)">tracing</a> for that matter) should be an integral part of writing production code. Yet, I&#8217;ve often found it not to be the case or that what got logged only made sense to the developer who wrote the entry.
</p>
<p>Not logging implies that debugging the application outside the development environment is largely based on guesswork. That’s interesting given that most applications spend the majority of their life running outside the development environment.
</p>
<h4>Life in the sandbox<br />
</h4>
<p>I suspect the absence or low quality of log statements can be, at least partially, explained by developers not finding them useful during development. The debugger available there is generally inferior to the print-lining approach of logging. That said, I&#8217;d argue that many developers don&#8217;t concern themselves enough with how their code behaves in a production environment. Rather than investing a small amount of time in adding log statements up-front, their focus is solely on satisfying functional customer requirements.
</p>
<p>A related case could be made for exception handling. For instance, rather than asserting the validity of an argument up-front and throwing an appropriate exception, the code may later fail with a NullReferenceException. Not throwing the exception up-front, close to where the actual error occurred, one will have a hard time tracking down the issue. Especially since a stack trace with symbols and line numbers is rarely available in a production environment.
</p>
<p>For someone having to resolve the issue, almost any clue as to the cause would be most welcomed. Without a clue that someone would walk around in the dark in the hope of stumbling into a solution.</p>
<h4>End users aren&#8217;t the only users<br />
</h4>
<p>As software developers we have to acknowledge that end users aren&#8217;t the only users of our software. System administrators, developers, and the like should also be factored in during development. Especially since the cost of instrumenting code at key places, early on, doesn&#8217;t add significantly to the overall development cost. Focusing on what can go wrong and communicating it well saves time, money, and frustration down the line. And as a bonus you might create better self-documenting code.
</p>
<p>That said it&#8217;s important to strike a balance between logging too little and too much information. A log should be detailed enough to reveal patterns of use. Ideally, the log should read like a story with short sentences detailing what&#8217;s about to happen, what did or didn&#8217;t happen, and possibly why.
</p>
<p>I&#8217;m not suggesting that we turn logging into a runtime version of <a href="http://en.wikipedia.org/wiki/Literate_programming">literate programming</a>. But simply that sufficient contextual information be provided, i.e., instead of logging &#8220;URL = &#8216;bugfree.dk&#8217;&#8221;, consider the more elaborate &#8220;Retrieving URL for indexing: &#8216;http://bugfree.dk&#8217;&#8221;.
</p>
<h4>Keep your statements clean<br />
</h4>
<p>On the other hand, log statements shouldn&#8217;t be immune to the <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY principle</a>. So make sure to have the logging framework automatically capture common bits of contextual information, such as the date and time of the entry and the class and method within which the log statement originated. On a similar note, don&#8217;t explicitly log when a method is entered or existed. Instead, treat such a case as a cross-cutting concern and take an <a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming">Aspect Oriented</a> approach to logging it.
</p>
<p>Lastly, not every method requires (extensive) logging. Figuring out when and what to log is key. Debugging the application, fixing bugs, and experience should provide guidance into what&#8217;s useful to log.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2009%2F07%2F22%2Fbasic-logging-guidelines%2F&amp;title=Basic%20logging%20guidelines" id="wpa2a_8"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2009/07/22/basic-logging-guidelines/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Basic unit testing guidelines</title>
		<link>http://www.bugfree.dk/blog/2009/06/19/basic-unit-testing-guidelines/</link>
		<comments>http://www.bugfree.dk/blog/2009/06/19/basic-unit-testing-guidelines/#comments</comments>
		<pubDate>Fri, 19 Jun 2009 21:02:39 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Mocking]]></category>
		<category><![CDATA[Presentation]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Quality]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/?p=111</guid>
		<description><![CDATA[Update, Nov 25, 2010: Rather than mimicking the directory structure of the assembly under test in a separate test assembly, I’m now more inclined to keep code under test and test code in the same assembly. Update, Aug 5, 2009: This post grew out of a couple of presentations that I did on the subject [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Update, Nov 25, 2010:</strong> Rather than mimicking the directory structure of the assembly under test in a separate test assembly, I’m now more inclined to <a href="http://weblogs.asp.net/bsimser/archive/2008/04/09/unit-test-projects-or-not.aspx">keep code under test and test code in the same assembly</a>. </p>
<p><b>Update, Aug 5, 2009</b>: This post grew out of a couple of presentations that I did on the subject back in May and June. Here are my slides from <a href="http://www.bugfree.dk/blog/wp-content/uploads/2009/08/Unit-testing-and-mocking.pdf">The Unit testing and mocking presentation</a>. Among other things, they contain a few C# samples elaborating on some of the points below.</p>
<p>This post is born of the need to formalize a set of guidelines on how to write and organize tests. In the past I couldn’t help feeling that with the lack of guidelines I had to start over explaining my views on every new project. With no guidelines the tests written quickly grew unmaintainable, giving unit testing a bad name.</p>
<h4>Why unit test</h4>
<p>Unit testing done right helps build confidence in the code base and drives forward development. Both in terms of forcing one to reflect on the requirements by authoring tests, but also by providing a foundation for developing more modular and testable code.</p>
<p>Given the <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity">cyclomatic complexity</a> of even simple methods, however, not every path through a method is worth exercising with a test. Instead, focus on writing representative unit tests for good and bad scenarios.</p>
<h4>Unit test != integration test</h4>
<p>For object-oriented code a unit test is one that exercises a class in isolation, without the code under test relying on other classes to carry out its operation. Similarly, a unit test shouldn&#8217;t rely on the presence of a database or a key/value pair in a configuration file for it to run. If it did, it would be an integration test. Not that there&#8217;s anything wrong with integration tests. They just take on more dependencies and hence tend to be more brittle. And so they cause more false positives because some dependent part isn&#8217;t properly configured. The key point, though, is not to confuse unit testing with integration testing.</p>
<p>Typically, an object delegates part of its operation to other objects. Writing modular and testable code therefore involves the application of design patterns, such as <a href="http://www.martinfowler.com/articles/injection.html#SignificantRevisions">Inversion of Control (IoC)</a>. With IoC a test can inject (fake) components into the object under test. The fake components share their interfaces with the real ones, but the test controls how they interact with the object under test and hence how the object under test behaves.</p>
<h4>Keep up quality</h4>
<p>As tests are written it&#8217;s vital for the understandability and maintainability of the test suite to keep them small and focused. As a rule of thumb a test should amount to no more than 10-15 lines of code. Longer tests are indicative of too much functionality being tested at once or that code common to multiple tests should be refactored into helper methods.</p>
<p>In terms of quality, the code comprising the tests should be of production code quality, i.e., the code must be kept clean and refactored as the need arises. Otherwise, tests will start to emit the <a href="http://martinfowler.com/bliki/CodeSmell.html">classic code smells</a>. In the longer run code smells lead to tests that are not maintainable and for the time that went into writing them to be wasted.</p>
<h4>Organizing test code</h4>
<p>Assuming the use of Visual Studio (VS), for each VS project with code that one wants to test, create matching projects that host the various kinds of tests, i.e., for the Acme.Intranet.Search project, create the following test related projects:</p>
<pre>    Acme.Intranet.Search.Common
    Acme.Intranet.Search.UnitTest
    Acme.Intranet.Search.IntegrationTest</pre>
<p>The Acme.Intranet.Common project is optional and may include code that is shared between test projects, such as custom assertions. As for the Acme.Intranet.Search.UnitTest project it should be fairly self-contained. One should be able to move the common assembly, the test assembly, and the business code assembly to another machine and have the tests execute there without further setup. Should a test rely on, say, a data file with test data, then include the file as an embedded resource within the test assembly.</p>
<p>Finally, within each test project, a class should be created for each class under test. In addition, the directory structure should match the namespace structure of the class under test, e.g., suppose the fully qualified name of a class is Acme.Intranet.Search.Business.Crawler, then create the following directory structure within the test assembly:</p>
<pre>    Acme.Intranet.Search.UnitTest
        Acme
            Intranet
                Search
                    Buesiness
                        CrawlerTest.cs</pre>
<p>While it’s important to write tests, it’s even more important to know where to put and find tests for a given functional area.</p>
<h4>Naming tests</h4>
<p>As far as naming and structure goes, a test should look something along these lines:</p>
<pre class="prettyprint lang-cs">    [TestClass]
    public class SomeClassTest {
        [TestMethod]
        public void SomeMethod_should_set_error_message_when_no_                    connection_string_is_configured() {
            // arrange
            // act
            // assert
        }
    }</pre>
<p>The test should generally start with the name of the method or property being tested, followed by the word &quot;should&quot; followed by the successful outcome in a descriptive form. Because names of tests tend to be longer than those of regular methods, underscores are used for ease of readability. In addition, the body of most tests should be composed of three parts: (1) the arrange part that sets up the object under test and possibly injects fake dependencies into it. (2) The act part then exercises the method under test, and finally (3) the assert part that verifies that expected state and/or behavioral changes did indeed take place.</p>
<h4>Gathering metrics</h4>
<p>Whenever a build is kicked of (on a build server) it should exercise all tests. Should a test fail, it should cause the entire build to fail, stressing the importance of keeping tests green at all times. Furthermore, a build report should include basic metrics such as code coverage, number of tests run, time spend running the tests, and so forth.</p>
<p>Keep in mind, though, that a high degree of code coverage isn&#8217;t a goal in itself. Instead, focus on writing solid, focused, and representative tests that eventually drive up code coverage.</p>
<h4>Tooling</h4>
<p>As far as .Net and tooling goes, <a href="http://en.wikipedia.org/wiki/MSTest">MSTest</a> or <a href="http://nunit.org">NUnit</a> should be used in concert with <a href="http://www.bugfree.dk/blog/2009/02/11/an-example-of-unit-testing-using-typemock">TypeMock</a> or <a href="http://ayende.com/projects/rhino-mocks.aspx">Rhino Mocks</a>. The use of TypeMock may be preferred over Rhino Mocks because of its unique approach to mocking. TypeMock doesn&#8217;t create fake objects by emitting MSIL and dynamically loading a runtime-generated assembly into the test runner. Instead, TypeMock hooks into the CLR APIs and intercepts calls as the unit test executes. From a coding point of view the TypeMock approach may not change much, but from a functionality point of view it enables the testing of legacy code or new code not written with IoC in mind.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2009%2F06%2F19%2Fbasic-unit-testing-guidelines%2F&amp;title=Basic%20unit%20testing%20guidelines" id="wpa2a_10"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2009/06/19/basic-unit-testing-guidelines/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Jumping through loops with XSL</title>
		<link>http://www.bugfree.dk/blog/2009/06/13/jumping-through-loops-with-xsl/</link>
		<comments>http://www.bugfree.dk/blog/2009/06/13/jumping-through-loops-with-xsl/#comments</comments>
		<pubDate>Sat, 13 Jun 2009 21:25:46 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Xsl]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/2009/06/13/jumping-through-loops-with-xsl/</guid>
		<description><![CDATA[I was recently faced with the need to express a loop in XSL. Not the build-in for-each that iterates over nodes matching an XPath, but one with a counter. In C# this kind of loop is easily expressed as for (int i = 0; i &#60; 5; i++) // do something No such for-construct exists [...]]]></description>
			<content:encoded><![CDATA[<p>I was recently faced with the need to express a loop in <a href="http://en.wikipedia.org/wiki/Xsl">XSL</a>. Not the build-in <a href="http://www.w3schools.com/XSL/el_for-each.asp">for-each</a> that iterates over nodes matching an <a href="http://en.wikipedia.org/wiki/XPath">XPath</a>, but one with a counter. In C# this kind of loop is easily expressed as
</p>
<pre class="prettyprint lang-cs">
    for (int i = 0; i &lt; 5; i++)
        // do something
</pre>
<p>No such for-construct exists in XSL. In fact there&#8217;re no looping constructs of any kind in XSL, except for the one used to iterate nodes. However, since XSL and C# are both <a href="http://en.wikipedia.org/wiki/Turing_complete">Turing complete</a> languages, and since anything that can be expressed in one Turing complete language can be expressed in another, it follows that it must be possible to express a loop with a counter in XSL.</p>
<p>But as <a href="http://en.wikipedia.org/wiki/Alan_Perlis">Alan Parlis</a> puts it in <a href="http://www-pu.informatik.uni-tuebingen.de/users/klaeren/epigrams.html">Epigrams on Programming</a>:
</p>
<blockquote><p>Beware of the <a href="http://en.wikipedia.org/wiki/Turing_tar_pit">Turing tar-pit</a> in which everything is possible but nothing of interest is easy.</p></blockquote>
<p>Although XSL and C# are both Turing complete languages, XSL is a <a href="http://en.wikipedia.org/wiki/Functional_programming">functional programming language</a> and therefore belongs to a strain of languages that forgo build-in looping constructs. Instead, looping is accomplished through recursion.</p>
<p>We can turn the iterative C# loop into a recursive one like so:</p>
<pre class="prettyprint lang-cs">
    void Loop(int i) {
        if (i &gt; 0) {
            // do something
            Loop(i - 1);
        }
    }
</pre>
<p>and transform the recursive solution into an XSL template:
</p>
<pre class="prettyprint lang-xsl">
    &lt;xsl:template name="Loop"&gt;
        &lt;xsl:param name="i" select="5"/&gt;
        &lt;xsl:if test="$i &gt; 0"&gt;
            &lt;!-- do something --&gt;
            &lt;xsl:call-template name="Loop"&gt;
                &lt;xsl:with-param name="i" select="$i - 1"/&gt;
            &lt;/xsl:call-template&gt;
        &lt;/xsl:if&gt;
    &lt;/xsl:template&gt;
</pre>
<p>Okay, but what about nested loops then:</p>
<pre class="prettyprint lang-cs">
    for (int i = 0; i &lt; 5; i++)
        for (int j = 0; j &lt; 5; j++)
            // do something
</pre>
<p>Giving it some thought, the nested loops (of any nesting level) can be expressed using recursion following a pattern of nested if-statements:
</p>
<pre class="prettyprint lang-cs">
    void NestedLoops(int i, int j, int k) {
        if (i &gt; 0) {
            // do something
            if (j == 1)
                NestedLoops(i - 1, k, k);
            else
                NestedLoops(i, j - 1, k);
        }
    }
</pre>
<p>Again, performing a one-to-one transformation to XSL:
</p>
<pre class="prettyprint lang-xsl">
    &lt;xsl:template name="NestedLoops"&gt;
        &lt;xsl:param name="i"/&gt;
        &lt;xsl:param name="j"/&gt;
        &lt;xsl:param name="k"/&gt;
        &lt;xsl:if test="$i &gt; 0"&gt;
            &lt;!-- do something --&gt;
            &lt;xsl:choose&gt;
                &lt;xsl:when test="$j = 1"&gt;
                    &lt;xsl:call-template name="NestedLoops"&gt;
                        &lt;xsl:with-param name="i" select="$i - 1"/&gt;
                        &lt;xsl:with-param name="j" select="$k"/&gt;
                        &lt;xsl:with-param name="k" select="$k"/&gt;
                    &lt;/xsl:call-template&gt;
                &lt;/xsl:when&gt;
                &lt;xsl:otherwise&gt;
                    &lt;xsl:call-template name="NestedLoops"&gt;
                        &lt;xsl:with-param name="i" select="$i"/&gt;
                        &lt;xsl:with-param name="j" select="$j - 1"/&gt;
                        &lt;xsl:with-param name="k" select="$k"/&gt;
                    &lt;/xsl:call-template&gt;
                &lt;/xsl:otherwise&gt;
            &lt;/xsl:choose&gt;
        &lt;/xsl:if&gt;
    &lt;/xsl:template&gt;
</pre>
<p>Wordy, but seeing through the angle brackets I find solution quite elegant.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2009%2F06%2F13%2Fjumping-through-loops-with-xsl%2F&amp;title=Jumping%20through%20loops%20with%20XSL" id="wpa2a_12"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2009/06/13/jumping-through-loops-with-xsl/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
	</channel>
</rss>

