<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="http://feeds.feedburner.com/~d/styles/rss2full.xsl" type="text/xsl" media="screen"?><?xml-stylesheet href="http://feeds.feedburner.com/~d/styles/itemcontent.css" type="text/css" media="screen"?><rss 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:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Chris Hedgate</title>
	
	<link>http://www.hedgate.net</link>
	<description>Self implied</description>
	<pubDate>Thu, 30 Oct 2008 14:35:12 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.6</generator>
	<language>en</language>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/ChrisHedgate" type="application/rss+xml" /><item>
		<title>From good developer to great developer</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/436969788/</link>
		<comments>http://www.hedgate.net/articles/2008/10/30/from-good-developer-to-great-developer/#comments</comments>
		<pubDate>Thu, 30 Oct 2008 14:33:51 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.hedgate.net/?p=92</guid>
		<description><![CDATA[During this autumn we at Blueplane have started a series of breakfast seminars. Next time, on Tuesday 11 november, it is my turn. My presentation is called &#8220;From good to great developer&#8221; (or as it is presented in Swedish, &#8220;Från duktig till fantastisk utvecklare&#8221;. I will talk about how I characterize great developers, and show [...]]]></description>
			<content:encoded><![CDATA[<p>During this autumn we at <a href="http://www.blueplane.se/">Blueplane</a> have started a series of <a href="http://www.blueplane.se/seminars/">breakfast seminars</a>. Next time, on Tuesday 11 november, it is my turn. My presentation is called &#8220;From good to great developer&#8221; (or as it is presented in Swedish, &#8220;Från duktig till fantastisk utvecklare&#8221;. I will talk about how I characterize great developers, and show an example of how a great developer implements a new feature while at the same time improving existing code, following an attitude I describe as Simplify, Improve, Modify. I will also discuss ways to motivate and support good developers to take that attitude and become great developers.</p>
<p>As I have been preparing the presentation, I have tried to identify the people will attend it. Next, to make sure that my material is relevant to these people, I have written down their reasons for being there, in a user story format. This way I can quite easily decide if an idea I want to talk about is actually relevant for the audience, or just a <a href="http://everything2.com/e2node/Kill%2520your%2520darlings">darling</a>.</p>
<p>Here are the stories I came up with:</p>
<blockquote><p>In order to deliver high-quality software with predictability, as a manager I want to support good developers to become great</p></blockquote>
<blockquote><p>In order to have more enjoyable challenges, work less with frustrating bugs and more with interesting problems, and advance my own skills, as a great developer I want to advance my colleagues into peers</p></blockquote>
<blockquote><p>In order to have more stimulating work and earn the respect of my colleagues, as a good developer I want to have some hands-on advice on what I can do to improve as a developer</p></blockquote>
<p>If you want to attend the seminar on Tuesday 11 november and have a free breakfast (breakfast is served at 07.30), send an email to <a href="mailto:seminarier@blueplane.se">seminarier@blueplane.se</a>. The place is St Gertrud Konferens, Östergatan 7b, in Malmö, Sweden. <a href="http://www.blueplane.se/seminars/great-developers-info.pdf">See this pdf (in Swedish) for more info</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2008/10/30/from-good-developer-to-great-developer/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2008/10/30/from-good-developer-to-great-developer/</feedburner:origLink></item>
		<item>
		<title>AgileØresund 2008</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/375267018/</link>
		<comments>http://www.hedgate.net/articles/2008/08/26/agile%c3%b8resund-2008/#comments</comments>
		<pubDate>Tue, 26 Aug 2008 14:17:17 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.hedgate.net/?p=82</guid>
		<description><![CDATA[As one of the driving forces of AgileØresund, I am involved in organizing a conference in Malmö next month. We are planning the conference to be a participant driven conference, meaning that the content is driven by the participants through lightning talks and open space discussions. It will be a full day free of charge, [...]]]></description>
			<content:encoded><![CDATA[<p>As one of the driving forces of <a href="http://www.agileoresund.org/">AgileØresund</a>, I am involved in organizing a conference in Malmö next month. We are planning the conference to be a participant driven conference, meaning that the content is driven by the participants through lightning talks and open space discussions. It will be a full day free of charge, so I hope a lot of agilistas from the Öresund region show up.</p>
<p>Go check out the <a href="http://www.agileoresund.org/2008/">web site</a> (only in Swedish) and sign up for the conference, and I will see you there!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2008/08/26/agile%c3%b8resund-2008/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2008/08/26/agile%c3%b8resund-2008/</feedburner:origLink></item>
		<item>
		<title>The elevator pitch introduction session</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/327390220/</link>
		<comments>http://www.hedgate.net/articles/2008/07/02/the-elevator-pitch-introduction-session/#comments</comments>
		<pubDate>Tue, 01 Jul 2008 22:45:46 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.hedgate.net/?p=79</guid>
		<description><![CDATA[Start a conference with a big introduction session where every speaker has to present a 45 second version of his or her session. This would make it easier for the attendees to decide which sessions to go to, and also increase the quality of the sessions.

	
	Photo from bogenfreund&#8217;s Flickr photostream

I was recently at the Agila [...]]]></description>
			<content:encoded><![CDATA[<p>Start a conference with a big introduction session where every speaker has to present a 45 second version of his or her session. This would make it easier for the attendees to decide which sessions to go to, and also increase the quality of the sessions.</p>
<p align="center">
	<img src="http://www.hedgate.net/wp-content/uploads/elevator.jpg" border="1" /><br />
	<em>Photo from <a href="http://www.flickr.com/photos/bogenfreund/" title="Flickr: bogenfreund's Photostream">bogenfreund&#8217;s Flickr photostream</a></em>
</p>
<p>I was recently at the <a href="http://agilasverige.se/2008/" title="Agila Sverige 2008">Agila Sverige 2008 conference</a> (which I guess some would call an <a href="http://en.wikipedia.org/wiki/Unconference" title="Unconference - Wikipedia, the free encyclopedia">unconference</a> since it was made up of <a href="http://en.wikipedia.org/wiki/Lightning_Talk" title="Lightning Talk - Wikipedia, the free encyclopedia">lightning talks</a> and <a href="http://en.wikipedia.org/wiki/Open_Space_Technology" title="Open Space Technology - Wikipedia, the free encyclopedia">open space sessions</a>, instead of normal 45-90 minute breakout sessions and keynotes). I presented a lightning talk version of <a href="http://www.hedgate.net/articles/2008/04/15/real-retrospectives-not-just-talking/" title="Real Retrospectives - Not Just Talk">Real Retrospectives - Not Just Talk</a> (<a href="http://www.blueplane.se/seminars/realretrospectives-lightningedition.pdf" title="">download pdf</a>).</p>
<p>I really liked the constraint of presenting the same ideas as before, only this time I only had 10 minutes. In fact, since I am a big fan of the <a href="http://en.wikipedia.org/wiki/Elevator_pitch" title="Elevator pitch - Wikipedia, the free encyclopedia">elevator pitch</a>, I started by presenting my content in 45 seconds. After this I told the audience that I had now delivered my core message to them. If they thought the ideas where not that interesting or they already knew the topic, or just did not like me for any reason, they could switch to a parallel session. If not, I would spend the rest of my 10 minutes to build upon that core message and hopefully give them some more value for their time.</p>
<p>This got me thinking, it would be an interesting idea to have a conference start with a general session, where every speaker had to present their session in 45 seconds. This would force speakers to really think through their content and boil it down to the key ideas they want to convey, which in turn I think is a good recipe for improving the quality and consistency of the content. It would also be a lot of help to attendees who are trying to decide which sessions to attend with multiple concurrent tracks. For one thing it would of course be helpful to see what the key ideas are, but also just to see and hear the speakers in action would make the decision easier in some cases.</p>
<p align="center">
	<img src="http://www.hedgate.net/wp-content/uploads/stop.jpg" border="1" /><br />
	<em>Photo from <a href="http://www.flickr.com/photos/mag3737/" title="Flickr: mag3737's Photostream">mag3737&#8217;s Flickr photostream</a></em>
</p>
<p>To take this idea even further, a variation could have the attendees voting for the sessions they think should be included in the schedule after getting the elevator pitches. Attendees could have an Emergency Stop button (for stopping the elevator, giving the speaker more time) to indicate that they liked the idea and would like to hear more about it by attending a full session (however long that is). This would not work for every conference of course, but it would be an interesting idea to try&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2008/07/02/the-elevator-pitch-introduction-session/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2008/07/02/the-elevator-pitch-introduction-session/</feedburner:origLink></item>
		<item>
		<title>Documentation (photos) from Agila Sverige open space session about retrospectives</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/320010597/</link>
		<comments>http://www.hedgate.net/articles/2008/06/25/documentation-photos-from-agila-sverige-open-space-session-about-retrospectives/#comments</comments>
		<pubDate>Wed, 25 Jun 2008 09:30:05 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<guid isPermaLink="false">http://www.hedgate.net/articles/2008/06/25/documentation-photos-from-agila-sverige-open-space-session-about-retrospectives/</guid>
		<description><![CDATA[This is just a very short post linking to a couple of photos that we took to document an open space session about retrospectives and effective meetings, which we hosted at the Agila Sverige 2008 conference. Since some people asked to have them, the photos can be found at the Blueplane Flickr photostream (descriptions and [...]]]></description>
			<content:encoded><![CDATA[<p>This is just a very short post linking to a couple of photos that we took to document an open space session about retrospectives and effective meetings, which we hosted at the <a href="http://agilasverige.se/2008/" title="Agila Sverige 2008">Agila Sverige 2008</a> conference. Since some people asked to have them, the photos can be found at the <a href="http://www.flickr.com/photos/blueplane/sets/72157605508459633/" title="Open Space om retrospektiv och effektivare möten - a set on Flickr">Blueplane Flickr photostream</a> (descriptions and photographed writing in Swedish only).</p>
<p>The really short summary for non-Swedish speaking is that the session started out discussing why meetings are sometimes not very effective, and moved towards defining areas to focus on to improve them. Unfortunately we did not have time to get down to how to improve in these areas, but the session concluded that the most important area to focus on (of those brought up) is to work on creating an environment that encourages involvement.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2008/06/25/documentation-photos-from-agila-sverige-open-space-session-about-retrospectives/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2008/06/25/documentation-photos-from-agila-sverige-open-space-session-about-retrospectives/</feedburner:origLink></item>
		<item>
		<title>Facilitator tip: Break contact when you are the centre of attention</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/319972281/</link>
		<comments>http://www.hedgate.net/articles/2008/06/25/facilitator-tip-break-contact-when-you-are-the-centre-of-attention/#comments</comments>
		<pubDate>Wed, 25 Jun 2008 08:24:47 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<guid isPermaLink="false">http://www.hedgate.net/articles/2008/06/25/facilitator-tip-break-contact-when-you-are-the-centre-of-attention/</guid>
		<description><![CDATA[As a facilitator, your role is normally a neutral one with regards to whatever is discussed. Your job is to help and encourage other people to engage and discuss in an efficient collaborative way. A common problem that occurs is when a facilitator is not seen as a neutral person by some or all of [...]]]></description>
			<content:encoded><![CDATA[<p>As a facilitator, your role is normally a neutral one with regards to whatever is discussed. Your job is to help and encourage other people to engage and discuss in an efficient collaborative way. A common problem that occurs is when a facilitator is not seen as a neutral person by some or all of the group being facilitated, and instead is seen as a leader. In the presence of a leader some people will turn into a passive mode, expecting to be told what to do instead of figuring it out for themselves.</p>
<p>I have experienced this in many different team meeting situations, such as retrospectives or daily standup meetings. For instance, a common failure mode of daily standups is when team members address the Scrummaster (or whatever you call your role as a coach) instead of the rest of the team when they inform about their progress. While one person is interacting with the Scrummaster the rest of the team zones out just waiting for their turn.</p>
<p align="center">
	<img src="http://www.hedgate.net/wp-content/uploads/lookaway.jpg" width="400" height="300" border="1" /><br />
	<br />
	<em>Photo by <a href="http://www.sxc.hu/profile/bombom" title="stock.xchng - bombom's sxc home">bombom</a></em>
</p>
<p>I use a very simple technique when this happens. I simply look away, or perhaps step behind someone else, to break direct contact with the team member addressing me. As simple as this is, I find it very effective. Even if I only look down for a second, when I look up again the person talking has usually gotten contact with someone else in the group and is now addressing the group as a whole.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2008/06/25/facilitator-tip-break-contact-when-you-are-the-centre-of-attention/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2008/06/25/facilitator-tip-break-contact-when-you-are-the-centre-of-attention/</feedburner:origLink></item>
		<item>
		<title>Great Developers</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/313715139/</link>
		<comments>http://www.hedgate.net/articles/2008/06/17/great-developers/#comments</comments>
		<pubDate>Tue, 17 Jun 2008 07:04:27 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<guid isPermaLink="false">http://www.hedgate.net/articles/2008/06/17/great-developers/</guid>
		<description><![CDATA[Great developers know that writing code is a much smaller and easier task than understanding and modifying code is. Therefore, they make sure that the code they write is easy to understand, and possible to extend by writing new code rather than rewriting old code.
Furthermore, when a great developer encounters code that is difficult to [...]]]></description>
			<content:encoded><![CDATA[<p>Great developers know that writing code is a much smaller and easier task than understanding and modifying code is. Therefore, they make sure that the code they write is easy to understand, and possible to extend by writing new code rather than rewriting old code.</p>
<p>Furthermore, when a great developer encounters code that is difficult to understand or that makes it difficult to add the new functionality they are working on they do not work around it, or add to the mess by adding more code to an existing <a href="http://www.laputan.org/mud/" title="Big Ball of Mud">big ball of mud</a>. Instead, they follow the mantra of first simplifying the existing code to make it easier to understand, then improving it to make it easier to change, and finally they make the changes necessary to add the new functionality.</p>
<p>Finally, a great developer never leave code in worse shape than what they found it in, but they do not always strive for perfection. They achieve a balance between improving existing code and adding new functionality (in Swedish we call this <a href="http://en.wikipedia.org/wiki/Lagom" title="Lagom - Wikipedia, the free encyclopedia">&#8220;lagom&#8221;</a>).</p>
<p align="center">
	<img src="http://www.hedgate.net/wp-content/uploads/greatdevelopers.jpg" width="333" height="222" border="1" />
</p>
<p>This was the message of a presentation entitled Great Developers, Principles and Patterns for writing good code, that I gave at the <a href="http://www.swenug.com/">Swenug Code Camp</a> in Gothenburg last week (pictures available on the <a href="http://www.flickr.com/photos/blueplane/sets/72157605590581989/" title="Swenug Code Camp - a set on Flickr">Blueplane Flickr photostream</a>, link to slides and code at the bottom of this post).</p>
<p>The presentation had two major parts, each accompanied by a demo with code. In the first part I talked about how developers differ in how much they care about the code they work with, using the story of <a href="http://www.agileadvice.com/2008/05/13/miscellaneous/stonecutters-paycheck-earners-or-cathedral-builders/" title="Stonecutters, Paycheck Earners, or Cathedral Builders?">stonecutters and cathedral builders</a>. I often hear people complaining about how their team members do not care about code the way they do. They then go on to talk about how they have tried teaching them design patterns, Open-Closed Principle, low coupling and separation of concerns etc. I think that although this is important knowledge, the first step towards becoming a cathedral builder is not to learn about such things but to understand and get into the mindset. To do this we need to teach simple work patterns, how a cathedral builder thinks when he encounters code that is not easy to work with. If we can influence someone to think about improving code using something as simple as <a href="http://www.hedgate.net/articles/2008/04/24/motivation-for-one-line-methods/">extracting short code fragments into named methods</a> they will be well on their way towards thinking like a cathedral builder.</p>
<p>In my first demo I played the role of a developer with the task of adding some new functionality to a system that already has some very similar functionality implemented. The existing code was implemented in the PictureListController class, shown below:</p>
<pre name="code" class="c-sharp">
	public class PictureListController
	{
		private PictureListView view;

		public PictureListController(PictureListView view)
		{
			this.view = view;
		}

		public void ShowTopPictures(int age)
		{
			// Is visitor allowed to see pictures?
			if (age < LoadsaPicsConfig.MinimumAge)
			{
				Logger logger = Logger.Instance;
				logger.Log("Under age violation!");
				throw new NotOldEnoughException();
			}

			PictureRepository repository = new PictureRepository();
			List<Picture> allPictures = repository.GetAllPictures();
			allPictures.Sort(
			    delegate(Picture first, Picture second)
			    {
				    return second.Views.CompareTo(first.Views);
				});

			view.SetPicturesToShow(allPictures);
		}

		public void ShowPicturesByRank(int age)
		{
			if (LoadsaPicsConfig.MinimumAge - age > 0)
			{
				Logger.Instance.Log("Under age violation!");
				throw new NotOldEnoughException();
			}

			PictureRepository repository = new PictureRepository();
			List<Picture> allPictures = repository.GetAllPictures();
			allPictures.Sort(
			    delegate(Picture first, Picture second)
			    {
				    return second.AverageVote.CompareTo(first.AverageVote);
				});

			view.SetPicturesToShow(allPictures);
		}
	}
</pre>
<p>My task was to implement a new way of listing pictures, this time ordered by most downloads. Instead of simply creating a new public method ShowPicturesByDownloads and copy-pasting code from the other methods, I instead decided to improve the existing code to make it easier to add the new functionality. I first simplified the two methods a bit and found out that they really did the same thing in the first part, so I could extract that into a common method. I noted that I should probably move that method somewhere else sometime, but right now I was OK with leaving it there (lagom). With that code extracted, I noted that the two methods was exactly the same except for the delegate used to sort the pictures. Since the client code that calls this code was also part of the same system I had the option to change the public methods of PictureListController and update any callers accordingly. The final result is shown below:</p>
<pre name="code" class="c-sharp">
	public class PictureListController
		{
			private PictureListView view;
			private IComparer<Picture> sortAlgorithm;

			public PictureListController(PictureListView view,
			            IComparer<Picture> sortAlgorithm)
			{
				this.view = view;
				this.sortAlgorithm = sortAlgorithm;
			}

			public void ShowPicturesSorted(int ageOfVisitor)
			{
				VerifyOldEnough(ageOfVisitor);
				List<Picture> allPictures = GetPictures();
				SortPictures(allPictures);

				view.SetPicturesToShow(allPictures);
			}

			private static void VerifyOldEnough(int age)
			{
				if (age < LoadsaPicsConfig.MinimumAge)
				{
					Logger logger = Logger.Instance;
					logger.Log("Under age violation!");
					throw new NotOldEnoughException();
				}
			}

			private static List<Picture> GetPictures()
			{
				PictureRepository repository = new PictureRepository();
				return repository.GetAllPictures();
			}

			private void SortPictures(List<Picture> pictures)
			{
				pictures.Sort(sortAlgorithm);
			}
		}
</pre>
<p>Now I can extend the functionality with infinite sorting orders, simply by instantiating the controller with different IComparers. This led me in to the second part of my talk, where I discussed principles such as Single Responsibility Principle (SRP) and Open-Closed Principle (OCP). I ended with a demo where I showed how a piece of code could be refactored from an implementation that did not follow SRP or OCP, into one that was very open for extension and had clearly separated responsibilities.</p>
<p>My slides and all of the demo code is available on <a href="http://www.blueplane.se/seminars/" title="Blueplane - Seminarier">Blueplane&#8217;s web site</a> (or <a href="http://www.blueplane.se/seminars/greatdevelopers.zip" title="Zip file with slides and code">download zip file directly</a>).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2008/06/17/great-developers/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2008/06/17/great-developers/</feedburner:origLink></item>
		<item>
		<title>Motivation for one-line methods</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/276928126/</link>
		<comments>http://www.hedgate.net/articles/2008/04/24/motivation-for-one-line-methods/#comments</comments>
		<pubDate>Thu, 24 Apr 2008 07:03:04 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<guid isPermaLink="false">http://www.hedgate.net/articles/2008/04/24/motivation-for-one-line-methods/</guid>
		<description><![CDATA[A simple thing that I often do to clean up and improve code as I am trying to understand it is to extract short fragments of a method into a new, smaller method. Quite often I will move just a single line of code into a new method. The reason for doing this is of [...]]]></description>
			<content:encoded><![CDATA[<p>A simple thing that I often do to clean up and improve code as I am trying to understand it is to extract short fragments of a method into a new, smaller method. Quite often I will move just a single line of code into a new method. The reason for doing this is of course to document why the line exists by naming the method accordingly. However, even though more and more people are now realizing that comments are a code smell, I am sometimes challenged to provide a motivation for extracting it into a method instead of simply writing a comment for that one line of code.</p>
<p>Take a look at the code fragment below:</p>
<pre name="code" class="c-sharp">
	public void readSomeData(int x, int y) {
		int position = x / y - this.z;

		startReadingFromPosition(position);
	}
</pre>
<p>That first line of code calculates a value according to some rules that are not quite clear from just seeing it. Lets say that this specific calculation is called the UltraMegaAlgorithm. Naturally we need to document this to help readers know that we use this algorithm. But why not simply write a comment? What is the difference between the two alternatives below?</p>
<pre name="code" class="c-sharp">
	public void readSomeData(int x, int y) {

		// Use UltraMegaAlgorithm to calculate starting position
		int position = x / y - this.z;

		startReadingFromPosition(position);

	}

	/* -------------------- */

	public void readSomeData(int x, int y) {

		int position =
			calculateStartingPositionUsingUltraMegaAlgorithm(x, y);

		startReadingFromPosition(position);

	}

	private int calculateStartingPositionUsingUltraMegaAlgorithm(
		int x, int y) {

		return x / y - this.z;

	}
</pre>
<p>Some will argue that it is much easier to read the comment than the camelCased method name. And I agree, it is really unfortunate that method names are often written this way (I think Ruby&#8217;s calculate_starting_position_using_ultra_mega_algorithm is at least better, but it is difficult to get Java and .Net programmers to change their old policies). But I would still argue that the second alternative is better. I could argue that we might want to do more than simply extracting into a new method. Perhaps we want to Move Method into another class. Perhaps this might become a strategy implementation. But I think there is a much simpler reason.</p>
<p>My main motivation for extracting into a method lies in considering what is important to us when we read the code to try and understand it. We want to see that readSomeData uses the UltraMegaAlgorithm to calculate a starting position, and then starts (doing whatever it does) from that position. We are completely oblivious to how the UltraMegaAlgorithm is implemented! The information in the comment is what is interesting to us here, not the implementation following it. In fact, that line makes it harder to understand what readSomeData does, since we will stop to consider the implementation even if we do not want to.</p>
<p>My rule of thumb is that the steps of a non-private method should be easy to understand by simply glancing at it. The way to achieve this is to make it read like normal language, which means that unclear one-liners with comments should be replaced with a method call that hides the implementation that the comment describes the reason for. If I trust the implementation of calculateStartingPositionUsingUltraMegaAlgorithm to be correct I can decide for myself if I just need to know that the code does this, of if I want to drill down and learn about the implementation as well.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2008/04/24/motivation-for-one-line-methods/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2008/04/24/motivation-for-one-line-methods/</feedburner:origLink></item>
		<item>
		<title>Real Retrospectives - Not Just Talking</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/320320636/</link>
		<comments>http://www.hedgate.net/articles/2008/04/15/real-retrospectives-not-just-talking/#comments</comments>
		<pubDate>Tue, 15 Apr 2008 06:51:29 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<guid isPermaLink="false">http://www.hedgate.net/articles/2008/04/15/real-retrospectives-not-just-talking/</guid>
		<description><![CDATA[Last Thursday, me and my colleague Andr&#233;s Taylor ran a session at Cornerstone&#8217;s Developer Summit 2008 in Stockholm. The title was Real Retrospectives - Not Just Talking. Our main point was that retrospectives are a great way of helping the team define (and refine) their own process, one that they agree on and will commit [...]]]></description>
			<content:encoded><![CDATA[<p>Last Thursday, me and my colleague <a href="http://www.taylor.se/blog/">Andr&eacute;s Taylor</a> ran a session at <a href="http://www.cornerstone.se/" title="Cornerstone.se">Cornerstone&#8217;s</a> <a href="http://www.expertzone.se/dev08/" title="ExpertZone: Developer Summt 2008">Developer Summit 2008</a> in Stockholm. The title was Real Retrospectives - Not Just Talking. Our main point was that retrospectives are a great way of helping the team define (and refine) their own process, one that they agree on and will commit to working with. However, it is not as easy as sitting down around a table for a quick chat (more on this in a later post). To have an effective group discussion you need a structure that supports it.
</p>
<p>In fact, with inspiration from <a href="http://randomfoo.net/oscon/2002/lessig/" title="free_culture">Lawrence Lessig</a>, we tried to condense our entire presentation into a short &#8220;refrain&#8221; (if our presentation would have been a song):</p>
<blockquote><p>
	We have to constantly adapt our method to our current reality.<br />
	To adapt our method effectively, we have to think together.<br />
	Thinking together is hard, and requires focused effort.
</p></blockquote>
<p>We showed these lines several times throughout the presentation, sometimes reading them out loud, sometimes just flashing through them. And as we ended the presentation by showing the refrain a final time we also read it together which produced a few laughs. I think this worked very well and hopefully will help the audience to remember our message. All credits to Andr&eacute;s for suggesting this and convincing me that it would work.</p>
<p>Our slides and also some pointers to further reading material are available at <a href="http://www.blueplane.se/seminars/" title="Blueplane - Seminarier">Blueplane&#8217;s web site</a>. The site is in Swedish, but just look for Real Retrospectives and the links in that section. However, I do not think that the slides will be of much value if you did not attend the presentation, so I will try and cover some of what we said in future blog posts (and I am sure Andr&eacute;s will do the same).</p>
<p>Regarding the conference, I was very happy to see a track called People Matters Too! at a very much developer oriented conference. I was even more happy to see so many people turn up for our session as well as the other sessions in this track. I am sure this will continue next year with at least a full day track like this one. See you there!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2008/04/15/real-retrospectives-not-just-talking/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2008/04/15/real-retrospectives-not-just-talking/</feedburner:origLink></item>
		<item>
		<title>Sharing</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/154437746/</link>
		<comments>http://www.hedgate.net/articles/2007/08/24/sharing/#comments</comments>
		<pubDate>Fri, 24 Aug 2007 15:17:47 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false" />
		<description><![CDATA[Late friday evening, after some wine, whisky and beer and a movie, I could not think of anything better to do than to catch up a bit on my blog reading (it&#8217;s not just my posting that is more or less dead right now, parental leave has left a lot of unread items in Google [...]]]></description>
			<content:encoded><![CDATA[<p>Late friday evening, after some wine, whisky and beer and a movie, I could not think of anything better to do than to catch up a bit on my blog reading (it&#8217;s not just my posting that is more or less dead right now, parental leave has left a lot of unread items in Google Reader). After reading a couple of hundred posts, in the end it was two that really stuck in my head. Maybe it was just the short and simple format of them that made it easier to read them, but they really spoke to me.</p>
<p>I used to have the latin phrase <em><a href="http://www.m-w.com/dictionary/docendo+discimus">Docendo discimus</a></em> (We learn by teaching) as my personal motto, but I think Jason Yip really nails it with:</p>
<blockquote><p><a href="http://jchyip.blogspot.com/2007/08/always-explain-why.html">There&#8217;s no substitute for sharing knowledge</a></p></blockquote>
<p>Jason says you should always explain why, especially to children and others who really have no idea why something happens the way it does. Never just say it&#8217;s magic or so. I couldn&#8217;t agree more.</p>
<p>On a somewhat similar note, Paul Duvall discuss why you should &#8220;<a href="http://www.testearly.com/2007/08/17/fire-your-best-peoplereward-the-lazy-ones/">fire your best people &#8230; reward the lazy ones</a>&#8220;. Now, the title is of course a bit misleading although there is some truth to it, but the message of the post for me can be boiled down to the following quote from the post:</p>
<blockquote><p>If the knowledge is locked in your head, you are a less valuable, not more valuable, resource.</p></blockquote>
<p>To me, these posts say that it is always important to take the time to share the knowledge instead of just &#8220;making it so&#8221;, whether it is something we implement in software or just something we say to someone.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2007/08/24/sharing/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2007/08/24/sharing/</feedburner:origLink></item>
		<item>
		<title>Programming with your nose</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/154437747/</link>
		<comments>http://www.hedgate.net/articles/2007/07/04/programming-with-your-nose/#comments</comments>
		<pubDate>Wed, 04 Jul 2007 14:45:08 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<guid isPermaLink="false" />
		<description><![CDATA[While flipping through an old MSDN magazine* today, I was inspired to this thought: Programming is done with the nose! One way of describing programming as using your nose would be to refer to the analogy of &#8220;code smells&#8221;:http://en.wikipedia.org/wiki/Code_smell. While I have always liked that analogy, that was however not what I had in mind [...]]]></description>
			<content:encoded><![CDATA[<p>While flipping through an old MSDN magazine* today, I was inspired to this thought: Programming is done with the nose! One way of describing programming as using your nose would be to refer to the analogy of &#8220;code smells&#8221;:http://en.wikipedia.org/wiki/Code_smell. While I have always liked that analogy, that was however not what I had in mind here.</p>
<p>The article that inspired my thought was Stan Lippman&#8217;s column entitled &#8220;Is Programming an Art?&#8221;:http://msdn.microsoft.com/msdnmag/issues/06/10/EndBracket/, where he compares software development to art. I like calling software development an art, in the same way as the process of &#8220;creating a Scotch Blended Whisky&#8221;:http://www.scotchmaltwhisky.co.uk/made-blended.htm is often called an art (as opposed to creating malt whisky which is called a science, since it is mostly about following a protocol). When creating a blended whisky, the Master Blender will use nothing but his nose to select the combination of malt and grain whisky to include in the blend. Sometimes a blend will include up to 50 different sorts of whisky. And every batch of blended whisky that is produced must consistently taste and smell the same way. Anyone interested in Single Malts knows that whisky from different batches, even different barrels in the same batch, will have different characteristics, so being a &#8220;Noser&#8221; (which is a much cooler title than Master Blender) is truly a difficult job with no easy way of simply following a protocol.</p>
<p>This art of &#8220;nosing&#8221; in many ways remind me of creating software. Although many would like it to be, software development is not about following a simple process of pressing a couple of buttons and drawing some lines. Producing software requires coding, and no project is ever the same as another one.</p>
<hr/>
<p>Here&#8217;s another thought: Maybe this means we can finally retire the term Architect? Lets start using Noser instead, at least for &#8220;architects doing real work&#8221;:http://codebetter.com/blogs/scott.bellware/archive/2006/09/10/149127.aspx. :D</p>
<p><small>*Ironically, this was right after I had listened to &#8220;Don Box and Chris Sells on .NET Rocks!&#8221;:http://www.dotnetrocks.com/default.aspx?showNum=249, talking about how no one actually reads magazines anymore and they could not remember when the last time they saw a copy of MSDN magazine was. I think that was the main reason I picked it up and browsed through it. :)</small></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2007/07/04/programming-with-your-nose/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2007/07/04/programming-with-your-nose/</feedburner:origLink></item>
		<item>
		<title>Will it be C#?</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/154437748/</link>
		<comments>http://www.hedgate.net/articles/2007/06/19/will-it-be-c/#comments</comments>
		<pubDate>Tue, 19 Jun 2007 14:34:54 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<guid isPermaLink="false" />
		<description><![CDATA[In &#8220;More Ruby-Influenced BDD in .NET&#8221;:http://codebetter.com/blogs/scott.bellware/archive/2007/06/19/164380.aspx, &#8220;Scott Bellware&#8221;:http://codebetter.com/blogs/scott.bellware/ writes:
bq. I&#8217;m not sure that C# will ultimately the language that will let BDD really shine on the CLR.  Without some kind of DSL ability like what can be had from Ruby and Boo, it&#8217;s kinda hard to conceive of specification syntaxes that won&#8217;t be fraught [...]]]></description>
			<content:encoded><![CDATA[<p>In &#8220;More Ruby-Influenced BDD in .NET&#8221;:http://codebetter.com/blogs/scott.bellware/archive/2007/06/19/164380.aspx, &#8220;Scott Bellware&#8221;:http://codebetter.com/blogs/scott.bellware/ writes:</p>
<p>bq. I&#8217;m not sure that C# will ultimately the language that will let BDD really shine on the CLR.  Without some kind of DSL ability like what can be had from Ruby and Boo, it&#8217;s kinda hard to conceive of specification syntaxes that won&#8217;t be fraught with C# line noise.</p>
<p>Here is a thought I had while reading this: _Is C# ultimately the language we will use on the CLR, period?_ (VB guys, substitute C# for VB.NET if you want)</p>
<p>Or, to put it in another way, which has the longest lifetime, C# or the CLR platform? For instance, on the Java side of things, here are two slides from &#8220;Polyglot Programming&#8221;:http://www.sda-india.com/conferences/jax-india/sessions/Neal_Ford/Neal_Ford-Polyglot_Programming-slides.pdf, a presentation by &#8220;Neal Ford&#8221;:http://memeagora.blogspot.com:</p>
<p>bq. Another language will supplant Java as the primary way people code the Java Platform</p>
<p>bq. Start treating Java as the assembly language of the Java Platform</p>
<p>In the future, will C# be the primary way of programming the .NET platform?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2007/06/19/will-it-be-c/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2007/06/19/will-it-be-c/</feedburner:origLink></item>
		<item>
		<title>Don’t blame Paula!</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/154437749/</link>
		<comments>http://www.hedgate.net/articles/2007/06/13/dont-blame-paula/#comments</comments>
		<pubDate>Wed, 13 Jun 2007 06:07:16 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<guid isPermaLink="false" />
		<description><![CDATA[
I used to subscribe to the blog &#8220;Worse Than Failure&#8221;:http://worsethanfailure.com/ (formerly The Daily WTF), but it got removed when I was trimming the number of blogs in my reader. If you have not seen it, they post examples of code that is really badly written or designed. Most often there is also a funny story [...]]]></description>
			<content:encoded><![CDATA[<p><a href='http://www.hedgate.net/wp-content/uploads/pointing_girl.jpg' title='Do not point fingers'><img src='http://www.hedgate.net/wp-content/uploads/pointing_girl.jpg' alt='Do not point fingers' align='right' /></a><br />
I used to subscribe to the blog &#8220;Worse Than Failure&#8221;:http://worsethanfailure.com/ (formerly The Daily WTF), but it got removed when I was trimming the number of blogs in my reader. If you have not seen it, they post examples of code that is really badly written or designed. Most often there is also a funny story to go with the code. One of the most absurd posts that I remember was one called &#8220;The Brillant Paula Bean&#8221;:http://worsethanfailure.com/Articles/The_Brillant_Paula_Bean.aspx.</p>
<p>It is a very short post, so go read it if you want. For the even shorter summary, it tells the story of a company that brought in a contractor, Paula, to help with a Java project. She was apparently handed some work to do, and for a few months she reported good progress during the weekly status meetings. However when the deadline came closer she asked for some help to finish it in time, and then it became clear that all she had produced was a couple lines of code that could do nothing more than return a misspelled string.</p>
<p>I guess all posts at WTF has to be taken with a grain of salt, but for now let us consider this one to actually be true. Like I said, it is really absurd, but what is it actually that is most absurd here? While there is no question that Paula was not a very good programmer, can we really blame her for this mess? If the story is true, this is clearly an example of a &#8220;process problem&#8221;:http://silkandspinach.net/2006/04/02/people-problems-vs-process-problems/. Why did no one notice there were no commits from her? Why did no one review her code? How did she ever get hired? There are so many ways this mess could have been avoided. For instance if Paula would have been pair-programming, her lack of skills would have been noticed at day one. With smaller tasks it would have been clear that she where having problems much earlier.</p>
<p>Unfortunately, even if the story turns out to be untrue, I do not think it is that uncommon. Change a few of the extremes of the story (the ridiculously low amount of code produced, the quite long time period, the insanely large task she must have been working on to be given so much time) into more realistic ones and I think most of us will recognise situations that we have been in. Maybe not situations that ended up the same way, but definitely situations that had the potential to do so. Things such as not testing the code and application enough, not having code reviews, and working on too large tasks with individual responsibility for the programmer that is given them all have the potential to end up in disasters such as The Brillant Paula Bean. When they do, instead of just pointing fingers at the person who screwed up, ask how it happened. Find out what is the root cause and eliminate it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2007/06/13/dont-blame-paula/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2007/06/13/dont-blame-paula/</feedburner:origLink></item>
		<item>
		<title>Ruby-style iterations in C# 3.0</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/154437750/</link>
		<comments>http://www.hedgate.net/articles/2007/05/10/ruby-style-iterations-in-c-3-0/#comments</comments>
		<pubDate>Thu, 10 May 2007 15:05:37 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<guid isPermaLink="false" />
		<description><![CDATA[While Ruby does have a for-loop, it is not commonly used in idiomatic Ruby code. Instead, to loop a number of times and do something in each run you would write code like this:

5.times do &#124;i&#124;
  print i
end

# equivalent for loop over a range
for int i in 0...5
  print i
end

I do not know [...]]]></description>
			<content:encoded><![CDATA[<p>While Ruby does have a for-loop, it is not commonly used in idiomatic Ruby code. Instead, to loop a number of times and do something in each run you would write code like this:</p>
<pre name="code" class="ruby">
5.times do |i|
  print i
end

# equivalent for loop over a range
for int i in 0...5
  print i
end
</pre>
<p>I do not know about you, but I definitely like the 5.times way better. With the new C# 3.0 (as part of Linq) feature extension methods it is a trivial thing to make it possible to write very similar code in C#:</p>
<pre name="code" class="c-sharp">
// using a lambda function, also a C# 3.0 feature
5.Times( i => Console.WriteLine(i) );

// or using a "simple" C# 2.0 delegate
5.Times(delegate (int i)
{
  Console.WriteLine(i);
});
</pre>
<p>So how does this work? By creating an extension method for int and bringing that into scope (with a using statement) all ints will now be extended with the method Times. Actually, int has of course not really been modified &#8220;on the fly&#8221; to include a new method, it is really only syntactic sugar for a method call such as @IntExtensions.Times(5, i => Console.WriteLine(i));@. Here is the simple extension method:</p>
<pre name="code" class="c-sharp">
public static class IntExtensions
{
  public static void Times(this int count, Action<int> block)
  {
    for (int i = 0; i < count; i++)
    {
      block.Invoke(i);
    }
  }
}
</pre>
<p>So what do you think? Am I crazy for even thinking about writing my C# (3.0) code in this way? Would you get confused and angry by looking at the code?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2007/05/10/ruby-style-iterations-in-c-3-0/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2007/05/10/ruby-style-iterations-in-c-3-0/</feedburner:origLink></item>
		<item>
		<title>Freedom fosters responsibility</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/154437751/</link>
		<comments>http://www.hedgate.net/articles/2007/05/04/freedom-fosters-responsibility/#comments</comments>
		<pubDate>Fri, 04 May 2007 14:57:56 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<guid isPermaLink="false" />
		<description><![CDATA[
Take a look at the photo to the right. Notice anything specific about it? Here is a hint: think about enforcing rules. See it now? That is right, there are no lanes, road signs, pedestrian crossings or similar. Other than the give-way markings on the ground, the intersection is completely clear of anything that rules [...]]]></description>
			<content:encoded><![CDATA[<p><a href='http://www.hedgate.net/wp-content/uploads/intersection.jpg' title='Intersection in Drachten, Holland'><img src='http://www.hedgate.net/wp-content/uploads/intersection.jpg' alt='Intersection in Drachten, Holland' align='right' /></a></p>
<p>Take a look at the photo to the right. Notice anything specific about it? Here is a hint: think about enforcing rules. See it now? That is right, there are no lanes, road signs, pedestrian crossings or similar. Other than the give-way markings on the ground, the intersection is completely clear of anything that rules how you should act here.</p>
<p>The photo shows a &#8220;traffic calmed&#8221; roundabout in the city of Drachten, Holland. Most of the city centre is actually completely free of the traffic ruling items mentioned above. But does this not lead to a lot of incidents? Surely there is some meaning behind this idea, but how can this possibly work? The simple answer is that the lack of road signs and such leads people to such a crazy thing as to actually take eye contact with each other. Instead of taking an &#8220;I have the right to do this&#8221;-attitude, &#8220;people actually take responsibility and work together to avoid incidents&#8221;:http://www.smallingerland.nl/index.cfm?sid=175. How many accidents involving cars and pedestrians are not the result the pedestrian simply walking straight out onto a pedestrian crossing expecting any cars to stop. The fact that there is a sign that says it is a pedestrian crossing combined with a law that says cars should stop for pedestrians does not mean that every car will automatically stop! The only thing that this really means is that cars have a responsibility to stop for pedestrians, but pedestrians do not have a right to walk right out into the street.</p>
<p>Although I know analogies can be dangerous, the reason I mention this is that I came to think about it after having a discussion over lunch regarding programming languages and how the code turns out in different ones. The discussion started with &#8220;Martin&#8221;:http://blog.upplopp.se/ talking about how he writes better code in C++ than he does when using C#. And I can vouch for his abilities in both languages, so it is not as simple as that. The reason, he said, was that C++ was more complex than C# and it is easier to get things wrong, so therefore he paid more attention to what he does when coding in C++. Instead of relying on the (sometimes dubiously) safe environment to help you, taking a step back to actually think for a second or two and make sure that what you just wrote not only solves whatever it should but is also meaningful to someone reading it later makes a huge difference.</p>
<p>The fears and skepticism people have about the lack of road signs in the Drachten intersections can be noted when developers skeptic to dynamic languages describe how they feel about them. &#8220;Does not the lack of structure make people do all sorts of crazy things? If someone can just open up a class at any time and modify a method (or add new ones), how can it possibly work out in a collaborative environment such as a typical software development project?&#8221; For the same reasons as the Drachten intersections lead to fewer accidents. By removing the &#8220;secure&#8221; environment of compile-time checking, people are actually forced to think and talk to eachother. Developers use better names for classes and methods, and also use tests to specify their intentions, both to the test runner and to other developers.</p>
<p>I want to use one last example. One practice common in agile development (and elsewhere of course) is continuous integration (CI). The idea is simple, integrate whenever any changes to the system are saved. Unfortunately it is also quite common to see this interpreted as &#8220;set up some CI server software, then we are done&#8221;. While a CI server can definitely be of use, people forget that &#8220;CI is really just an attitude&#8221;:http://www.jamesshore.com/Blog/Continuous-Integration-is-an-Attitude.html and &#8220;has nothing to do with having a CI server&#8221;:http://www.jamesshore.com/Blog/Continuous-Integration-on-a-Dollar-a-Day.html. The CI server becomes the road signs of the intersection. Instead of thinking in terms of what your responsibilities are when checking in, you trust the CI server to solve all problems for you.</p>
<p>To summarize: Be sure to not allow yourself or your team to get a false sense of security from processes and rules. Instead focus on the social parts of software development. Individuals and interactions over processes and tools is what it is all about.</p>
<p>&#8211;</p>
<p>Photo downloaded from &#8220;sociate&#8217;s flickr account&#8221;:http://www.flickr.com/photos/sociate/, used under a &#8220;Creative Commons Attribution-ShareAlike 2.0&#8243;:http://creativecommons.org/licenses/by-sa/2.0/ license.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2007/05/04/freedom-fosters-responsibility/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2007/05/04/freedom-fosters-responsibility/</feedburner:origLink></item>
		<item>
		<title>Testing events with unit tests</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/154437752/</link>
		<comments>http://www.hedgate.net/articles/2007/03/13/testing-events-with-unit-tests/#comments</comments>
		<pubDate>Tue, 13 Mar 2007 16:23:00 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<guid isPermaLink="false" />
		<description><![CDATA[How to test events seem to be a question that sometimes comes up regarding unit testing. There are three different things that we want to test when using events.
  * Verify that an event subscriber really wires up a listener to an event
  * Verify that an event subscriber does what it should [...]]]></description>
			<content:encoded><![CDATA[<p>How to test events seem to be a question that sometimes comes up regarding unit testing. There are three different things that we want to test when using events.</p>
<p>  * Verify that an event subscriber really wires up a listener to an event<br />
  * Verify that an event subscriber does what it should when that event is fired<br />
  * Verify that an event publisher fires an event when it should</p>
<p>The first two are basically the same. If we can verify that some action that should be taken when an event is fired really does happen then we have of course also verified that the subscriber does listen to the event. But I prefer to start simple with my tests and therefore often end up with a small test like the following one for testing the wiring only:</p>
<pre name="code" class="c-sharp">
using System;
using NUnit.Framework;

namespace TestingEvents
{
  [TestFixtureAttribute]
  public class EventsFiringTests
  {
    [Test]
    public void SubscriberWiresListenerToListenToMeEvent()
    {
      FakePublisher publisher = new FakePublisher();

      new SubscriberUnderTest(publisher);

      Assert.AreEqual(1, publisher.ListenToMeSubscriberCount);
    }
  }

  public interface Publisher
  {
    event EventHandler ListenToMe;
  }

  public class FakePublisher : Publisher
  {
    public event EventHandler ListenToMe;

    public int ListenToMeSubscriberCount
    {
      get { return ListenToMe.GetInvocationList().Length; }
    }

    public void FireListenToMe()
    {
      ListenToMe.Invoke(this, EventArgs.Empty);
    }
  }

  public class SubscriberUnderTest
  {
    private string message;

    public SubscriberUnderTest(Publisher publisher)
    {
      message = null;

      publisher.ListenToMe += IAmListening;
    }

    private void IAmListening(object sender, EventArgs args)
    {
      message = "I heard that!";
    }

    public string Message
    {
      get { return message; }
    }
  }
}
</pre>
<p>This test only tests that the subscriber actually does wire up a listener to the ListenToMe event of the publisher it is instantiated with. The next step is to verify what it does when the event is fired from the publisher. The next test takes care of that.</p>
<pre name="code" class="c-sharp">
  [Test]
  public void MessageIsSetWhenListenToMeIsFired()
  {
    FakePublisher publisher = new FakePublisher();
    SubscriberUnderTest subscriber = new SubscriberUnderTest(publisher);

    publisher.FireListenToMe();

    Assert.AreEqual("I heard that!", subscriber.Message);
  }
</pre>
<p>That takes care of testing that a subscriber does what we expect it to when the event it subscribes to is fired. The final thing that needs to be tested is that a publisher actually fires an event when we expect it to. Lets add a new class, @PublisherUnderTest@, and another test.</p>
<pre name="code" class="c-sharp">
  [Test]
  public void PublisherFiresListenToMeWhenAngry()
  {
    PublisherUnderTest publisher = new PublisherUnderTest();

    bool listenToMeWasCalled = false;
    publisher.ListenToMe += delegate { listenToMeWasCalled = true; };

    Assert.AreEqual(true, listenToMeWasCalled);
  }

  public class PublisherUnderTest : Publisher
  {
    public event EventHandler ListenToMe;

    public void GetAngry()
    {
      if (ListenToMe != null)
      {
        ListenToMe.Invoke(this, EventArgs.Empty);
      }
    }
  }
</pre>
<p>The test simply assigns an anonymous method to listen to the event from the publisher. In the anonymous method a boolean value is set to true to indicate that the event was fired.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2007/03/13/testing-events-with-unit-tests/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2007/03/13/testing-events-with-unit-tests/</feedburner:origLink></item>
		<item>
		<title>Back from SQL Server Open World 2007</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/154437753/</link>
		<comments>http://www.hedgate.net/articles/2007/03/11/back-from-sql-server-open-world-2007/#comments</comments>
		<pubDate>Sun, 11 Mar 2007 15:26:28 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<guid isPermaLink="false" />
		<description><![CDATA[From thursday evening until saturday afternoon I was at the SQL Server Open World in Denmark. SSOW turned out to be an excellent conference. There where about 140 attendees and speakers and there was a lot of interaction between people. Networking is always important and of course happens at all conferences, but I do believe [...]]]></description>
			<content:encoded><![CDATA[<p>From thursday evening until saturday afternoon I was at the SQL Server Open World in Denmark. SSOW turned out to be an excellent conference. There where about 140 attendees and speakers and there was a lot of interaction between people. Networking is always important and of course happens at all conferences, but I do believe that SSOW had a couple of things helping make networking very easy. How about these examples?</p>
<p>* During the first evening after the opening introduction and &#8220;technical&#8221; presentation they moved everyone into &#8220;the party house&#8221;. This was where the unfortunate latest employees of Miracle (the conference organizers) happened to live. Note that everyone means about a hundred people, in one small house meant for 4-8 people.<br />
* The party house had free beer, brewed by Miracle themselves (or rather their sister company that is in the beer brewing business).<br />
* Friday night was beach party. The conference was held at Lallandia, a vacation resort in Denmark with a big indoors waterland. Networking is just so much easier in a jacuzzi with a beer in your hand.<br />
* Most conferences try for a 80/20 mixture of serious stuff (sessions) and fun stuff. At SSOW they go for a 50/50 mix. That does not mean there is less serious stuff, just a lot less time to sleep. :)</p>
<p>I gave two presentations. The first one was a completely new one called <a href='http://www.hedgate.net/wp-content/uploads/agiledb-ssow.zip' title='Working with SQL Server in an agile development environment'>Working with SQL Server in an agile development environment</a> (though I think I will change that to Agile Data Practices if I give it again). Even though there where only a few attendees I still had a good time, since it was easier to get a good discussion going.</p>
<p>The other presentation was <a href='http://www.hedgate.net/wp-content/uploads/sqlclr-ssow.zip' title='Understanding CLR Integration'>Understanding CLR Integration</a> which I did for the fourth time. I think it went very well, with a lot of good interaction from the audience. I think it was the atmosphere at the conference that encouraged this, I know I saw it in other presentations as well. Two specific things where mentioned in the talk, which I promised to address here:</p>
<p>* Regarding user-defined aggregates (UDAggs) that can be created as CLR objects, we discussed the problem of the 8000 bytes limitation for &#8220;MaxByteSize&#8221;:http://msdn2.microsoft.com/en-us/library/microsoft.sqlserver.server.sqluserdefinedaggregateattribute.maxbytesize.aspx. As I said, this limitation really makes it impossible to use UDAggs for a lot of cases where they would otherwise be an option, for instance the often used examples of calculating a median or concatening strings. However, the really interesting bit is that I posted a &#8220;feedback item regarding this&#8221;:http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=124559 to Microsoft Connect during the SQL Server 2005 beta testing period. What I said was that the maximum needs to be higher, possibly even indefinite. As the feedback item shows the response from Microsoft was that this was a reasonable request but since it was a non-trivial change it would not make it into SQL Server 2005 (RTM). Wednesday evening however this feedback item was closed and marked as fixed! Unfortunately it does not say how it was fixed or in which version (future service pack of SQL Server 2005, or Katmai the next version of SQL Server?) it is fixed. I am hoping that this gets clarified in the feedback item and also discussed it with Mark Souza from Microsoft who was there (with Lubor Kollar) as speakers and Microsoft representatives.<br />
* The other thing was a question regarding the fact that not all system assemblies can be loaded in SQLCLR. The question was if the list of approved assemblies is available somewhere. I found &#8220;this blog post&#8221;:http://www.sqlskills.com/blogs/bobb/2006/05/28/NewSQLCLRapprovedAssemblyInSP1.aspx by &#8220;Bob Beauchemin&#8221;:http://www.sqlskills.com/blogs/bobb/ to be a good answer.</p>
<p>*Download the presentations* (as PDFs):</p>
<p>* <a href='http://www.hedgate.net/wp-content/uploads/agiledb-ssow.zip' title='Working with SQL Server in an agile development environment'>Working with SQL Server in an agile development environment</a> (with demo code)<br />
* <a href='http://www.hedgate.net/wp-content/uploads/sqlclr-ssow.zip' title='Understanding CLR Integration'>Understanding CLR Integration</a></p>
<p>All in all I had a great time. If you are a SQL Server speaker I would definitely recommend putting in an abstract for a session next year.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2007/03/11/back-from-sql-server-open-world-2007/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2007/03/11/back-from-sql-server-open-world-2007/</feedburner:origLink></item>
		<item>
		<title>Public fields vs properties and a bit of YAGNI</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/154437754/</link>
		<comments>http://www.hedgate.net/articles/2007/02/24/public-fields-vs-properties-and-a-bit-of-yagni/#comments</comments>
		<pubDate>Sat, 24 Feb 2007 09:55:11 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<guid isPermaLink="false" />
		<description><![CDATA[A month ago or so a friend of mine IM:d me and said they were having a discussion regarding properties, if they should always be used to access fields or if you could sometimes just make the fields public. My response was instant (it was IM after all): *Always use properties*
Actually, even though I really [...]]]></description>
			<content:encoded><![CDATA[<p>A month ago or so a friend of mine IM:d me and said they were having a discussion regarding properties, if they should always be used to access fields or if you could sometimes just make the fields public. My response was instant (it was IM after all): *Always use properties*</p>
<p>Actually, even though I really think that &#8220;public fields should not even be allowed by the language&#8221;:http://gbracha.blogspot.com/2007/01/representation-independent-code.html, I confessed that I do sometimes use them in &#8220;test doubles&#8221;:http://xunitpatterns.com/Mocks,%20Fakes,%20Stubs%20and%20Dummies.html that I create for my unit tests (for instance for setting a value that I want some method to return when it is called in a test). But this is the only time I use public fields and I am trying to get away from it.</p>
<p>My friend did not agree with me and pointed me to &#8220;a post by Jeff Atwood&#8221;:http://www.codinghorror.com/blog/archives/000654.html. We did discuss this further that evening over a couple of beers, but I am not sure if I managed to persuade him. Probably not. :)</p>
<p>Some &#8220;other&#8221;:http://jimmynilsson.com/blog/posts/PropertiesVsFields.htm &#8220;smart&#8221;:http://blogs.msdn.com/ericgu/archive/2007/02/01/properties-vs-public-fields-redux.aspx &#8220;people&#8221;:http://blogs.msdn.com/jaybaz_ms/archive/2007/02/08/properties-vs-fields-again.aspx at least seem to agree with Jeff and my friend, but I do not buy into the arguments. It seems there are three main arguments given by proponents of public fields:</p>
<p>  * *Performance*: Rico Mariani, performance guru at Microsoft, discusses performance differences between public fields and properties (as a part of a larger performance quiz on using value types for performance) in &#8220;two&#8221;:http://blogs.msdn.com/ricom/archive/2006/08/31/performance-quiz-11-ten-questions-on-value-based-programming.aspx &#8220;posts&#8221;:http://blogs.msdn.com/ricom/archive/2006/09/07/performance-quiz-11-ten-questions-on-value-based-programming-solution.aspx. This is the only reason that I can actually sometimes accept. It is of course impossible to argument against it since the numbers are pretty clear, but in general most applications do not see any real difference from these issues. And if the language, and VM of course, did not even allow public fields I think more work could be done there to avoid problems.</p>
<p>  * *Trivial properties are just meaningless wrapper code*:  I really do not understand this argument. I guess these are the same people who name a variable of type Window to wnd instead of window, or a method that inserts a new value into some container to InsVal. Sure, silly examples, but my point is that typing is not really an issue with modern IDEs. Type prop and hit tab and you have got a property backed by a private field. More lines to read with properties? Sure, but seriously, how is that an issue? Personally I think the code is more readable and understandable with consistent use of properties for accessing an objects internals. And again, if the language did not allow public fields and instead had some syntactic sugar for easily creating properties backed by private fields, like @public property string Name;@, this would not even be an issue. C# 3.0 by the way seems to have something similar, as you can use @public string Name { get; set; }@ to accomplish this, although I think the previous one would be better.</p>
<p>  * *Creating a trivial property is a premature decision because they will most often stay trivial forever*: I do not like this. Even if you think trivial properties makes it more difficult to understand the code, calling &#8220;YAGNI&#8221;:http://en.wikipedia.com/wiki/YAGNI on the decision to create one instead of using a public field to me is a misinterpretation or misuse of YAGNI. What it says that &#8220;you should defer making a decision until the *latest responsible moment*&#8221;, not simply &#8220;defer it until the latest possible moment&#8221;. What happens if you create a public field and then later change it into a property when it is used by clients? That is a &#8220;breaking change and clients will need to recompile from source&#8221;:http://blogs.msdn.com/abhinaba/archive/2006/04/11/572694.aspx. Not a very responsible thing to do.</p>
<p>Even if I would agree with the above arguments, there are enough quirks and problems that you might get into from using public fields that I still recommend avoiding them. These include problems with parts of the .NET framework (databinding and reflection for instance), naming convention questions, and of course most importantly how changing from a public field to a property can break code in several ways, requiring recompiling from source. See the comments to Jeff Atwood&#8217;s post above (also summarized by himself in the updated part of the post), and the comments Eric Gunnerson&#8217;s post (summarized in a &#8220;follow-up post&#8221;:http://blogs.msdn.com/ericgu/archive/2007/02/02/more-on-properties-vs-fields.aspx) for more info.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2007/02/24/public-fields-vs-properties-and-a-bit-of-yagni/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2007/02/24/public-fields-vs-properties-and-a-bit-of-yagni/</feedburner:origLink></item>
		<item>
		<title>Databinding a WPF control to something else than a static property</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/154437755/</link>
		<comments>http://www.hedgate.net/articles/2007/02/21/dynamically-databinding-a-wpf-control-to-items-in-a-list/#comments</comments>
		<pubDate>Wed, 21 Feb 2007 14:41:31 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<guid isPermaLink="false" />
		<description><![CDATA[A couple of days ago I was trying to solve a problem with databinding in WPF. What I was trying to do was to create columns for a ListView (with a GridView set for it&#8217;s view). Creating columns was no problem, neither was binding the columns to some property of the objects in the list [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of days ago I was trying to solve a problem with databinding in WPF. What I was trying to do was to create columns for a ListView (with a GridView set for it&#8217;s view). Creating columns was no problem, neither was binding the columns to some property of the objects in the list that was set as the ItemsSource of the ListView. The problem was however that the &#8220;properties&#8221; that I wanted to bind the columns to was not really properties (in the C#/.NET vocabulary).</p>
<p>To create a binding on a normal statically declared property, code like the below would work:</p>
<pre name="code" class="c-sharp">
Binding binding = new Binding();
binding.Path = new PropertyPath("SomeProperty");
binding.Mode = BindingMode.OneWay;

FrameworkElementFactory textElement = new FrameworkElementFactory(typeof(TextBlock));
textElement.SetBinding(TextBlock.TextProperty, binding);

DataTemplate template = new DataTemplate();
template.VisualTree = textElement;

GridViewColumn column = new GridViewColumn();
column.CellTemplate = template;
</pre>
<p>With this code in place I now have a column containing a single textblock. The Text property of that textblock will contain the value of the property SomeProperty for each object in the collection that is set as the ItemsSource of the listview. However, as I mentioned above, the problem was that my object (or rather, the object&#8217;s type) did not have a static property called SomeProperty. Instead it has a property called Properties, which is a Dictionary containing a &#8220;dynamic&#8221; set of objects each representing some property (in the general meaning of the word, not in the C#/.NET vocabulary) of the object I am showing on the current row of the listview.</p>
<pre name="code" class="c-sharp">
public class ShownInList {
  ...

  public Dictionary<string, PropertyObject> Properties {
    ...
  }
}

public class PropertyObject {
  ...

  public string Name {
    ...
  }

  public object Value {
    ...
  }
}
</pre>
<p>As seen above, each property has a name and a value. What I now want to do is to create a column and bind it to a property with a specific name, so that it will show the value of that property. The intuitive thing to try was to create the binding with a PropertyPath initialized with a string such as &#8220;Properties['SomeProperty']&#8220;. This did not work however, and neither did the different ways I tested to write the property path string.</p>
<p>Some Googling later I found the solution. Instead of binding to a property using a PropertyPath I could skip setting up the path at all and instead use a custom converter. Here is what I did:</p>
<pre name="code" class="c-sharp">
Binding binding = new Binding();
binding.Converter = new PropertyObjectConverter();
binding.ConverterParameter = "SomeProperty";
binding.Mode = BindingMode.OneWay;

...

public class PropertyObjectConverter : IValueConverter {
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
      ShownInList obj = (ShownInList)value;

      string key = (string)parameter;
      return obj.Properties.ContainsKey(key) ?
        obj.Properties[key].Value :
        null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
      throw new NotImplementedException();
    }
}
</pre>
<p>The binding is set up to call a converter to get a value to show. The converter is called with the object, of type ShownInList, that is the source for the current row, and a parameter describing which property in the dictionary I want to bind to. If the dictionary contains a propertyobject with the name as key then it returns the Value property of that object, otherwise it returns null.</p>
<p>If anyone has a better solution than mine then please add a comment about it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2007/02/21/dynamically-databinding-a-wpf-control-to-items-in-a-list/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2007/02/21/dynamically-databinding-a-wpf-control-to-items-in-a-list/</feedburner:origLink></item>
		<item>
		<title>Strange card games and methodology discussions</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/327390221/</link>
		<comments>http://www.hedgate.net/articles/2007/02/09/strange-card-games-and-methodology-discussions/#comments</comments>
		<pubDate>Fri, 09 Feb 2007 11:34:05 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<guid isPermaLink="false" />
		<description><![CDATA[One of the most demoralizing and improductive things that can happen to a project and team are endless discussions about methodology.
Do not get me wrong here, how we work should definitely not be a once-and-for-all decision that we can never change. Quite the contrary, we must reflect regularly on the process and how we work, [...]]]></description>
			<content:encoded><![CDATA[<p>One of the most demoralizing and improductive things that can happen to a project and team are endless discussions about methodology.</p>
<p>Do not get me wrong here, how we work should definitely not be a once-and-for-all decision that we can never change. Quite the contrary, we must reflect regularly on the process and how we work, make changes as necessary and then follow up on those changes. But the point here is that we make these changes from some known base and we make them based on experiencing that something does not work for us. Most importantly changes are introduced at regular points in time (after an iteration), and we try them for some period of time long enough to be able to measure and decide whether they help us or not. What I am referring to with endless discussions about methodology is when a team starts out without having a process that they collectively agree upon and understand.</p>
<hr />
<p>*Executive summary*: Before the start of a project, gather all the team members and collectively discuss and decide upon the process that the team will follow.</p>
<hr />
<p>This reminds me of a card game we played in school at a class in Organizational/Group Theory (or something similar). The teacher started by telling us that starting now, *we were not allowed to talk to each other*. No oral communication whatsoever was allowed.</p>
<p>We were then divided into groups, I think there were five groups of five people each (but it&#8217;s not important). Each group were placed at a table that had a sheet of paper and a deck of cards. On the paper she had written down the rules for the card game we were going to play. Silently the paper was passed around between the five people at the table so that everyone knew the rules. I do not remember the rules exactly, but it was a very basic kind of &#8220;trick-taking game&#8221;:http://en.wikipedia.org/wiki/Trick-taking_game. The person who took the highest number of tricks was the winner.</p>
<p>When everyone at the table had read the rules she collected all the papers and told us to start playing. There were no &#8220;official&#8221; scoring (we had nothing to write on) so it was mostly for fun, but as always the winning instinct in people set in and we had a good time playing. Sometimes you would win a trick and throw your hands in the air in triumph, but noone was allowed to say anything or make any noise. After playing for a while we were stopped and *one person from each table were instructed to move counter-clockwise to the next table*.</p>
<p>Play then commenced again and everyone was happy. Until it happened for the first time that this new person and someone else reached for the trick to collect it at the same time. Confusion arose, the two &#8220;winners&#8221; looked at each other in anger (maybe not that much anger), and everyone wondered what was going one. Was this new guy trying to cheat? No talking was allowed, so after a while of looking and gesturing someone more or less just grabbed the trick and play continued. This problem was intensified when another person from each table was moved to a new one, this time clockwise. Now it was suddenly a very chaotic game of trick-taking with a lot of silent arguing going on. I think we switched one more time before we finished and discussed what had happened.</p>
<p>What did happen was of course that *each table started out with slightly different variations of the same rules*. When we were not allowed to discuss them then everyone, especially the &#8220;stronger&#8221; ones, just did things their way. Some &#8220;weaker&#8221; individuals just did not care and gave up their wins, even though they knew they had won, when someone else reached for the cards. I seem to remember that there were even someone who after figuring it out just started faking a win by reaching for the cards, bullying the others away from them.</p>
<p>The reason we did this exercise was to understand and experience the dynamics of team membership and disagreement. The strong natural leaders often came out winners while others did not win anything. But the reason I compare this with methodology discussions is the fact that we had different sets of base processes (rules) that we tried to follow. Sure, if we would have been allowed to talk about it I think we would eventually have decided upon some common rules that we could all follow. But the person that had to give up a trick that he thought he had won would not be happy, and the discussions would most likely be lengthy and tiresome. *What we should have done was of course to make sure that before we started the game everyone agreed upon the same rules*.</p>
<p>This is how it needs to be done in our projects as well. Before starting a new project a team should sit down and decide how they want to work, and make sure everyone commits to following the process decided upon. This might be as simple as saying &#8220;we will follow XP by the book&#8221; or you can go the Crystal way of deciding which practices to use. The important thing is that it is perfectly clear what is decided upon and that everyone commits to following it. Even if someone does not agree that a certain practice is a good one they should commit to following it if the team collectively decides to include it. After a couple of iterations the practice can be evaluated and changed if it did not work out. And this process of pinning down the methodology needs to be done *before the project starts*. Just like in the card game, having these discussions when everyone is busy doing Real Work^(TM)^ unfortunately guarantees that they will be lengthy and tiresome, and some people will get run over and feel bad about it.</p>
<p>*To sum up*: Before starting a project, make sure that everyone in the team understands and commits to the process the team is going to follow. But do not forget to reflect regularly and change the process as the team sees necessary.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2007/02/09/strange-card-games-and-methodology-discussions/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2007/02/09/strange-card-games-and-methodology-discussions/</feedburner:origLink></item>
		<item>
		<title>Article about CLR integration posted</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/327390222/</link>
		<comments>http://www.hedgate.net/articles/2007/02/02/article-about-clr-integration-posted/#comments</comments>
		<pubDate>Fri, 02 Feb 2007 23:05:59 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<guid isPermaLink="false" />
		<description><![CDATA[About a year ago I wrote an article for the &#8220;SQL Server Standard&#8221;:http://www.sqlserverstandard.com/ magazine called &#8220;Understanding CLR integration in SQL Server 2005&#8243;:/writings/understanding-clr-integration. This article is now also available here at my site, in the &#8220;Articles&#8221;:/writings section. It is an overview of how the CLR and SQL Server work together and tries to show how this [...]]]></description>
			<content:encoded><![CDATA[<p>About a year ago I wrote an article for the &#8220;SQL Server Standard&#8221;:http://www.sqlserverstandard.com/ magazine called &#8220;Understanding CLR integration in SQL Server 2005&#8243;:/writings/understanding-clr-integration. This article is now also available here at my site, in the &#8220;Articles&#8221;:/writings section. It is an overview of how the CLR and SQL Server work together and tries to show how this is a much safer and better way to extend SQL Server than using extended stored procedures.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2007/02/02/article-about-clr-integration-posted/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2007/02/02/article-about-clr-integration-posted/</feedburner:origLink></item>
		<item>
		<title>Instantiating a WPF control from an NUnit test</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/327390223/</link>
		<comments>http://www.hedgate.net/articles/2007/01/08/instantiating-a-wpf-control-from-an-nunit-test/#comments</comments>
		<pubDate>Mon, 08 Jan 2007 13:46:46 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false" />
		<description><![CDATA[If you try to run a test like the following from NUnit, you will find that it does not work. You get an InvalidOperationException telling you that &#8220;The calling thread must be STA, because many UI components require this&#8221;.

[Test]
public void CanCreateAndShowWpfWindow()
{
  Console.WriteLine(Thread.CurrentThread.GetApartmentState());

  System.Windows.Window window = new System.Windows.Window();
  window.Show();
}

NUnit (both the GUI and [...]]]></description>
			<content:encoded><![CDATA[<p>If you try to run a test like the following from NUnit, you will find that it does not work. You get an <code>InvalidOperationException</code> telling you that &#8220;The calling thread must be STA, because many UI components require this&#8221;.</p>
<pre name="code" class="c-sharp">
[Test]
public void CanCreateAndShowWpfWindow()
{
  Console.WriteLine(Thread.CurrentThread.GetApartmentState());

  System.Windows.Window window = new System.Windows.Window();
  window.Show();
}
</pre>
<p>NUnit (both the GUI and console version) by default runs it&#8217;s threads in a multithreaded apartment (MTA), which can be verified by looking at the Console.Out tab. As the message says, instantiating a WPF Window requires that the calling thread is running in a single-threaded apartment (STA).</p>
<p>The simplest way to make this work is to configure NUnit to run tests in an STA thread. Create a config file for NUnit to use (<a href="http://nunit.org/index.php?p=configFiles">see the docs for info on how to name it</a>) and add the following XML configuration (or just add to your existing one):</p>
<pre name="code" class="xml">
<configuration>
  <configsections>
    <sectiongroup name="NUnit">
      <section name="TestRunner" type="System.Configuration.NameValueSectionHandler">
      </section>
    </sectiongroup>
  </configsections>
</configuration>

<nunit>
  <testrunner>
    <add key="ApartmentState" value="STA"></add>
  </testrunner>
</nunit>
</pre>
<p>This tells NUnit to run all tests in STA threads. However, if you just want a single test (or some but not all) to run in STA (or MTA, if you have used the above configuration to set the default to STA) you have to resort to code. You need to start a new thread and set the apartment state you want, and then run your unit test in that thread. I used <a href="http://www.peterprovost.org/archive/2004/11/03/2051.aspx">CrossThreadTestRunner</a> (from <a href="http://www.peterprovost.org/">Peter Provost</a>) and just added support to choose which apartment state to create and run a thread in. The following code example shows how to use it:</p>
<pre name="code" class="c-sharp">
[Test]
public void CanCreateAndShowWpfWindow()
{
  CrossThreadTestRunner runner = new CrossThreadTestRunner();
  runner.RunInSTA(
    delegate
    {
      Console.WriteLine(Thread.CurrentThread.GetApartmentState());

      System.Windows.Window window = new System.Windows.Window();
      window.Show();
    });
}
</pre>
<p>My modified CrossThreadTestRunner class looks like this:</p>
<pre name="code" class="c-sharp">
using System;
using System.Reflection;
using System.Security.Permissions;
using System.Threading;

namespace UnitTestThreadApartmentState
{
  public class CrossThreadTestRunner
  {
    private Exception lastException;

    public void RunInMTA(ThreadStart userDelegate)
    {
      Run(userDelegate, ApartmentState.MTA);
    }

    public void RunInSTA(ThreadStart userDelegate)
    {
      Run(userDelegate, ApartmentState.STA);
    }

    private void Run(ThreadStart userDelegate, ApartmentState apartmentState)
    {
      lastException = null;

      Thread thread = new Thread(
        delegate()
        {
          try
          {
            userDelegate.Invoke();
          }
          catch (Exception e)
          {
            lastException = e;
          }
        });
      thread.SetApartmentState(apartmentState);

      thread.Start();
      thread.Join();

      if (ExceptionWasThrown())
        ThrowExceptionPreservingStack(lastException);
    }

    private bool ExceptionWasThrown()
    {
      return lastException != null;
    }

    [ReflectionPermission(SecurityAction.Demand)]
    private static void ThrowExceptionPreservingStack(Exception exception)
    {
      FieldInfo remoteStackTraceString = typeof(Exception).GetField(
        "_remoteStackTraceString",
        BindingFlags.Instance | BindingFlags.NonPublic);
      remoteStackTraceString.SetValue(exception, exception.StackTrace + Environment.NewLine);
      throw exception;
    }
  }
}
</pre>
<p><strong>A final note</strong>: As opposed to NUnit, both TestDriven.Net and Resharper&#8217;s Unit Test Runner run tests in STA threads. I got bitten by this recently when all the tests where green on my machine, but when I committed the build server went red on me. I was using Resharper to run the tests, while NUnit-Console was used on the server. Hope this might help someone else in the same situation.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2007/01/08/instantiating-a-wpf-control-from-an-nunit-test/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2007/01/08/instantiating-a-wpf-control-from-an-nunit-test/</feedburner:origLink></item>
		<item>
		<title>User stories and customer</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/327390224/</link>
		<comments>http://www.hedgate.net/articles/2007/01/04/user-stories-and-customer/#comments</comments>
		<pubDate>Thu, 04 Jan 2007 22:54:42 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<guid isPermaLink="false" />
		<description><![CDATA[On the XP mailing list, Adam Sroka posted &#8220;this great reply&#8221;:http://tech.groups.yahoo.com/group/extremeprogramming/message/124598 to a question regarding how to write a story when there is no user involved. The entire thread is very interesting, but this message contains probably the most well written description that I have seen of the customer in XP (and other agile methodologies.
]]></description>
			<content:encoded><![CDATA[<p>On the XP mailing list, Adam Sroka posted &#8220;this great reply&#8221;:http://tech.groups.yahoo.com/group/extremeprogramming/message/124598 to a question regarding how to write a story when there is no user involved. The entire thread is very interesting, but this message contains probably the most well written description that I have seen of the customer in XP (and other agile methodologies.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2007/01/04/user-stories-and-customer/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2007/01/04/user-stories-and-customer/</feedburner:origLink></item>
		<item>
		<title>Plus one on Ayende’s OSS post</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/327390225/</link>
		<comments>http://www.hedgate.net/articles/2006/12/11/plus-one-on-ayendes-oss-post/#comments</comments>
		<pubDate>Mon, 11 Dec 2006 00:12:30 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false" />
		<description><![CDATA[Ayende Rahien recently wrote a very well thought through post discussing The Problem of Open Source in the Microsoft World. This is a must-read for any .NET developer who has reached the stage of looking for tools outside of Microsoft. As Ayende describes, a big part of the problem is that there is one major [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ayende.com/">Ayende Rahien</a> recently wrote a very well thought through post discussing <a href="http://www.ayende.com/Blog/2006/12/09/TheProblemOfOpenSourceInTheMicrosoftWorld.aspx">The Problem of Open Source in the Microsoft World</a>. This is a must-read for any .NET developer who has reached the stage of looking for tools outside of Microsoft. As Ayende describes, a big part of the problem is that there is one major vendor, Microsoft, who not only gives us the basic framework we use to create applications on but also the tools we use to do so with. This means that we can never expect to see built-in support for creating and running NUnit tests. Microsoft has the strength to respond to a need of .NET developers (unit testing their code in this case) by creating their own framework (MS Test) and promoting that, instead of  using (or at least including support for) existing de-facto standards (NUnit and MbUnit in this case) already being used by .NET developers.</p>
<p>While I can hope that this might change (as said by others, some IDE competition would be great) I am afraid that it will not happen anytime soon. So what can we do in the meantime? I think it is important for those of us who are using OSS tools (or simply tools from other vendors) to promote them in the .NET community. I am not saying that there always exists a better alternative to Microsoft products, often there does not, but it is important that we help the rest of the community see and evaluate the alternatives. I think some good work is being done here. At <a href="http://www.oredev.org/">&ouml;redev</a>, the largest developer conference in Sweden, the .NET track consisted of ten seminars and two half-day workshops. Half of these (one workshop and five seminars) discussed some new technology from Microsoft (Atlas, .NET 3.0, Linq etc), but half of them where mostly about educating the .NET community about professional development using TDD, domain-driven design and AOP. These are competencies that are much more common and standard knowledge in the Java community than what they are in .NET.</p>
<p>At the latest <a href="http://www.snug.se/">SNUG</a> meeting I did my presentation on testable user interface code and <a href="http://joel.fjorden.se/">Joel Fjordén</a> and <a href="http://blog.houltz.se/">Richard Houltz</a> discussed tools for developer productivity (CodeRush/Refactor and Resharper was also mentioned), coding guidelines (from outside of Microsoft, sort of) and how to enforce them using Joel&#8217;s <a href="http://joel.fjorden.se/static.php?page=CodeStyleEnforcer">CodeStyleEnforcer</a> plugin. This is what we need to do, getting the .NET community together at meetings and facilitating discussions about professional development and creating better code, by showing what tools are available. This of course includes Microsoft tools, but we should not be limited to this one major vendor.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2006/12/11/plus-one-on-ayendes-oss-post/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2006/12/11/plus-one-on-ayendes-oss-post/</feedburner:origLink></item>
		<item>
		<title>Testable UI code presentation at SNUG</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/327390226/</link>
		<comments>http://www.hedgate.net/articles/2006/12/08/testable-ui-code-presentation-at-snug/#comments</comments>
		<pubDate>Fri, 08 Dec 2006 07:14:06 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false" />
		<description><![CDATA[I did a presentation two days ago at &#8220;SNUG&#8221;:http://www.snug.se/. The topic was *Testable UI Code*. The title of my presentation was actually &#8220;_Cleaning up the mess_&#8221; with the subtitle &#8220;_How to take control over monstrous UI classes_&#8221;. You can download the presentation and code (it was mostly code) in a zipped file.
I started out by [...]]]></description>
			<content:encoded><![CDATA[<p>I did a presentation two days ago at &#8220;SNUG&#8221;:http://www.snug.se/. The topic was *Testable UI Code*. The title of my presentation was actually &#8220;_Cleaning up the mess_&#8221; with the subtitle &#8220;_How to take control over monstrous UI classes_&#8221;. You can <a href='http://www.hedgate.net/wp-content/uploads/snug-20061206.zip' title='download the presentation and code'>download the presentation and code</a> (it was mostly code) in a zipped file.</p>
<p>I started out by showing a demo application, built in the all too common way of simply having all code in one form. Naturally, this was only an example so a real application would have multiple forms and maybe even reusable code in the form of some custom user controls. The problems with this application is that it is difficult to test the behaviour of it. Automating some sort of user interface driver to test it creates tests that are much too brittle and difficult to maintain (there are even those that take a screenshot of the UI and then compare the screenshots created by a test to the &#8220;correct&#8221; ones!).</p>
<p>I then showed how to take the first step to a better design, by separating the domain logic from the UI class. To my surprise only about half of the audience raised their hands when I asked how many do this in their applications. I guess that it might be that some just did not bother to raise their hands, while others did not really associate with the example I showed (maybe they are using a &#8220;Transaction Script&#8221;:http://www.martinfowler.com/eaaCatalog/transactionScript.html style rather than the &#8220;Domain Model&#8221;:http://www.martinfowler.com/eaaCatalog/domainModel.html I showed). This step is what Martin Fowler describes as &#8220;Separated Presentation&#8221;:http://www.martinfowler.com/eaaDev/SeparatedPresentation.html. My examples are very similar to the ones in Fowler&#8217;s texts, so it should be very easy to read his detailed writings and take a look at the examples I created to get a good understanding of the things I discussed in the presentation.</p>
<p>The next step I discussed is to move presentation logic from the UI class to a separate class, often called a presenter. The UI class will simply delegate user input to the presenter class, so I think a simple name for this pattern would be Delegated Input Handling (or similar), although I have never heard it called something like that. The common name for this is of course Model-View-Presenter, but I tried to avoid discussing Model-View-Presenter and Model-View-Controller until later in the talk. The demo (in my code) is called &#8220;Passive View&#8221;:http://www.martinfowler.com/eaaDev/PassiveScreen.html, since the view (the UI class) contains no logic at all. The view does not do anything else than signalling the presenter when user interaction happens (delegated input handling) and then acts as a getter/setter for the various UI elements that the presenter needs to control.</p>
<p>After this I showed a variation of the step above, where the presenter was simplified by replacing the simple plumbing logic with data binding. To accomplish this the presenter exposes the model (domain objects) to the view so that the view can bind the UI elements to properties of the model. The reasoning for doing this is that data binding is &#8220;automatic&#8221; and included in the framework, so we can safely use it even though we can no longer test this part of the presentation logic. Martin Fowler calls this pattern &#8220;Supervising Controller&#8221;:http://www.martinfowler.com/eaaDev/SupervisingPresenter.html (though I would call it Supervising Presenter as he discusses in the article), since the presenter now only supervise things by reacting to user input and letting the view automatically show the current state of the model. However, as a supervisor the presenter will also take control of those situations where automatic handling such as data binding is too difficult or impossible. In those situations it will work with the view in the same way as in Passive View. My demo has an example of this.</p>
<p>Finally, I showed a demo of &#8220;Presentation Model&#8221;:http://www.martinfowler.com/eaaDev/PresentationModel.html. This pattern is kind of similar in intention to MVP (Passive View and Supervising Controller), but it is differently realized. Here instead of having a presenter we create a separate class, PresentationModel, to hold the current state of the UI. The UI class then does nothing but delegate input handling to the presentation model, and synchronize it&#8217;s UI elements with the current state exposed by the presentation model. One of the good things about this is that unit tests become easier to write, since there is no need to fake out the view and test the interaction between the view and the presentation model. With the presentation model completely unaware of the view it is also easy to create the presentation logic (in the presentation model) without any view at all while testing.</p>
<p>Some other relevant links that where in some way mentioned in my talk are listed below.</p>
<p>* &#8220;Active Record&#8221;:http://castleproject.org/activerecord/index.html is a productive way of setting up a data access layer.<br />
* &#8220;MonoRail&#8221;:http://castleproject.org/monorail/index.html is an MVC-based web framework for the .NET platform.<br />
* Finally, I mentioned the &#8220;Agile &ouml;resund&#8221;:http://mawi.org/agileoresund/ user group that &#8220;Marcus Widerberg&#8221;:http://mawi.org/ and I are starting up with some others. If you are interested in meeting quite informally to discuss agile topics, please take a look at the wiki.<br />
* And if you missed it in the text above, you can download <a href='http://www.hedgate.net/wp-content/uploads/snug-20061206.zip' title='the demos and presentation I gave in a zipped file'>the demos and presentation I gave in a zipped file</a>.</p>
<p>On behalf of myself and &#8220;SNUG&#8221;:http://www.snug.se/, I want to thank those who attended the meeting an hope to see you again at the next meeting which will be in February.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2006/12/08/testable-ui-code-presentation-at-snug/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2006/12/08/testable-ui-code-presentation-at-snug/</feedburner:origLink></item>
		<item>
		<title>Quick should never imply dirty</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/327390227/</link>
		<comments>http://www.hedgate.net/articles/2006/12/06/quick-should-never-imply-dirty/#comments</comments>
		<pubDate>Wed, 06 Dec 2006 02:19:43 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<guid isPermaLink="false" />
		<description><![CDATA[My friend and former colleague &#8220;Magnus Mårtensson&#8221;:http://blog.noop.se/ recently wrote about &#8220;his feelings&#8221;:http://blog.noop.se/2006/12/02/When+Quick+And+Dirty+Becomes+Just+Dirty.aspx about &#8220;YAGNI&#8221;:http://c2.com/xp/YouArentGonnaNeedIt.html and how he instead would like us to follow what he calls &#8220;GYCFKSTF&#8221; (Give Yourself Credit For Knowing Some Things First). I do not quite agree with what he says (but I guess you knew that already Magnus ;) and started [...]]]></description>
			<content:encoded><![CDATA[<p>My friend and former colleague &#8220;Magnus Mårtensson&#8221;:http://blog.noop.se/ recently wrote about &#8220;his feelings&#8221;:http://blog.noop.se/2006/12/02/When+Quick+And+Dirty+Becomes+Just+Dirty.aspx about &#8220;YAGNI&#8221;:http://c2.com/xp/YouArentGonnaNeedIt.html and how he instead would like us to follow what he calls &#8220;GYCFKSTF&#8221; (Give Yourself Credit For Knowing Some Things First). I do not quite agree with what he says (but I guess you knew that already Magnus ;) and started to write a comment, but when it became a bit long I decided to post it here instead.</p>
<p>There is nothing in YAGNI (or other things in XP) that says you cannot &#8220;give yourself credit for knowing something&#8221;. From the C2 page linked above, here is a relevant quote:</p>
<p>bq. This doesn&#8217;t mean you should avoid building flexibility into your code. It means you shouldn&#8217;t overengineer something based on what you *think you might need later on*.</p>
<p>I do not interpret YAGNI the same way as Magnus does. I definitely agree that there is a need for some balancing critique of popular things such as agile and terms such as YAGNI. But I think that it will be difficult to come to a conclusion when the different sides have such different interpretations of what they are promoting/critizising. The readers will have to decide for themselves which interpretation they agree with.</p>
<p>What I find that Magnus is doing here is taking something he does not really like (YAGNI), looking at it from some angle and/or interpreting it in one way which makes it look like a bad thing, and then saying that this is the essence of that thing, so naturally it is a bad thing.</p>
<p>To me, YAGNI is just XP&#8217;s way of implementing the lean principle of deferring decisions until the latest responsible moment. I do not think that anyone can complain about how this principle works for Toyota and other lean (non-software) companies, but at the same time I realize that what I am doing is just the same thing as Magnus. I am looking at something that I like (YAGNI), from an angle that makes it look like a good thing, and saying that this is the essence of that thing, so naturally it is a good thing. Debates like these will never have any winner, but then again I do not think the meaning of debating is winning. By discussing it everyone is a winner, since hopefully we all learn something in the process. :)</p>
<p>On the smaller scale, YAGNI and TDD says that we should try and solve our problem (get to green) as fast as possible, cutting corners while doing so. This might result in us adding a &#8220;public IADAL AAccess&#8221; property. However, when we are at green we are encouraged to think, to remove duplication and to improve our design. In this case though we might just be happy with our implementation and add the next test, the one for the IBDAL. Since we need to get to green fast, we would again just add the &#8220;public IBDAL BAccess&#8221; property. However, now we start to see duplication. At this stage we must refactor to improve our design.</p>
<p>If we do not continuously refactor to improve the code and design, everything will turn into a &#8220;BigBallOfMud&#8221;:http://www.laputan.org/mud/. Therefore I do not agree that YAGNI will turn into YAGFI (You Ain&#8217;t Gonna Fix It!). Agile practices require a lot of disciple, more so than any other method I have encountered, and being professional and always thinking about how the code and design can be improved is part of this.</p>
<p>On the slightly larger scale, YAGNI says that we should &#8220;Always implement things when you *actually* need them, never when you just *foresee* that you need them.&#8221; It does not say anything about how we should implement things (e.g. &#8220;you are not allowed to use a generic version!&#8221;). I like to think about it as &#8220;do not design for future requirements, but do design for flexibility&#8221;. So what would be YAGNI then? Lets say that we &#8220;know&#8221; that in the future the DALAccess class will need to support feature X (maybe serialization or whatever). We &#8220;know&#8221; this because there is a story that has been created but not selected for this iteration* which will need this functionality. Lets say that we have done this sort of thing lots of times before, so we &#8220;know&#8221; that by simply creating an IXable interface and letting our class implement that (or maybe even just returning dummy values for now, the important thing is that the architecture is correct, right?) we will be good for the future. Doing this is violating YAGNI. First of all we do not even know if we need the feature. Implementing it, or at least designing for it now, will take unnecessary time and produce code that might possibly be unnecessary in the end. Next is the question of whether or not this design is the correct one. Based on our experience and what we know now we might be able to say that this design is the correct one. However, if we defer the decision to when we actually need the feature we will know even more and be able to make an even better decision.</p>
<p>So, from my positive point of view, YAGNI is a great guideline that helps me create software that is as simple as possible, but no simpler.</p>
<p>*: ~Again, this is an example of how YAGNI makes more sense for anyone really doing XP, since the fact that there exists a story does not even mean it will ever be selected for implementation.~</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2006/12/06/quick-should-never-imply-dirty/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2006/12/06/quick-should-never-imply-dirty/</feedburner:origLink></item>
		<item>
		<title>One assertion per test should come natural</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/327390228/</link>
		<comments>http://www.hedgate.net/articles/2006/11/17/one-assertion-per-test-should-come-natural/#comments</comments>
		<pubDate>Fri, 17 Nov 2006 06:57:36 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<guid isPermaLink="false" />
		<description><![CDATA[In an &#8220;earlier post&#8221;:/articles/2006/10/22/to-setup-or-not-to-setup I mentioned very briefly the _one-assert-per-test-method_ rule. This is something I think originally came from Dave Astels and definitely a guideline that I try to follow. The reason is of course that it helps make tests simpler and more expressive and therefore make them more helpful in locating problems. &#8220;Astels also [...]]]></description>
			<content:encoded><![CDATA[<p>In an &#8220;earlier post&#8221;:/articles/2006/10/22/to-setup-or-not-to-setup I mentioned very briefly the _one-assert-per-test-method_ rule. This is something I think originally came from Dave Astels and definitely a guideline that I try to follow. The reason is of course that it helps make tests simpler and more expressive and therefore make them more helpful in locating problems. &#8220;Astels also argue&#8221;:http://www.artima.com/weblogs/viewpost.jsp?thread=35578 that &#8220;_by adding the specification of the behavior one tiny piece at a time, you drive toward evolving the code in small, controllable, understandable steps_&#8221;.</p>
<p>Now there might of course be situations when it makes sense to have more than one assert. However, what is important to note about those situations is that they should not change the Arrange-Act-Assert structure of a test. So if there are multiple asserts in a test, they should all be at the end of the test. Definitely do not let your tests become Arrange-Act-Assert-Act-Assert-Act-Assert or similar.</p>
<p>However, even with nicely structured tests, I have come to think of multiple asserts as a kind of smell that the test (or rather the fixture) might not be really thought through. There is one specific situation that I have seen a couple of times where people say that the test is so simple that there is no reason to write it in multiple test methods. Let me show a typical example:</p>
<pre name="code" class="c-sharp">
[TestFixture]
public class FooBuilderTests
{
  [Test]
  public void FooIsBuiltCorrectly()
  {
    string fooThis = "foobar";
    string fooThat = "barfoo";
    FooBuilder fooBuilder = new FooBuilder();
    Foo foo = fooBuilder.Create(fooThis, fooThat);

    Assert.AreEqual(fooThis, foo.This);
    Assert.AreEqual(fooThat, foo.That);
  }
}
</pre>
<p>What we are testing is a simple builder class (FooBuilder) that is used to create object instances of the class Foo. It takes two strings which we expect to be set correctly on the appropriate properties of the Foo instance returned. Simple enough, right? Why would we ever want to create two separate test methods for these two asserts that are so linked to each other?</p>
<p>As I said, I smell something wrong here. And it is very obvious to me what it is. FooBuilderTests is not a good name for a test fixture, or rather the fixture is not a good one. We should not simply have a single &#8220;generic&#8221; fixture for every production class. What the fixture is all about is setting up everything in a specific state and then testing things in that state. So what would be a better fixture in this case? Look at the setup that is common for the tests that will be in the fixture. How about we call it AFooCreatedByAFooBuilder. This also makes it quite natural to use the setup method of xUnit frameworks, as I discussed in the &#8220;post mentioned earlier&#8221;:/articles/2006/10/22/to-setup-or-not-to-setup, although it of course works equally well to do setup in a method called directly from the test methods. Here is what this fixture would look like:</p>
<pre name="code" class="c-sharp">
[TestFixture]
public class AFooCreatedByAFooBuilder
{
  private Foo foo;
  private string fooThis = "foobar";
  private string fooThat = "barfoo";

  [SetUp]
  public void InitPerTest()
  {
    FooBuilder fooBuilder = new FooBuilder();
    foo = fooBuilder.Create(fooThis, fooThat);
  }
}
</pre>
<p>With this fixture it becomes quite natural to create two separate tests for the two asserts. Here is the code that goes for the tests:</p>
<pre name="code" class="c-sharp">
  [Test]
  public void ThisIsSetCorrectlyOnFooInstance()
  {
    Assert.AreEqual(fooThis, foo.This);
  }

  [Test]
  public void ThatIsSetCorrectlyOnFooInstance()
  {
    Assert.AreEqual(fooThat, foo.That);
  }
</pre>
<p>If we strive to organize our tests in a fixture oriented approach instead of a per-production-class oriented approach, I think having one assert per test method comes natural. By the way, with Behavior-Driven Development I do not think this would ever be an issue. With the contexts and specifications of BDD we write this way naturally. Even though BDD is not really a lot more than a different wording from TDD, it makes it so much easier to think correctly about writing your tests/specifications.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2006/11/17/one-assertion-per-test-should-come-natural/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2006/11/17/one-assertion-per-test-should-come-natural/</feedburner:origLink></item>
		<item>
		<title>To setup or not to setup</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/327390229/</link>
		<comments>http://www.hedgate.net/articles/2006/10/20/to-setup-or-not-to-setup/#comments</comments>
		<pubDate>Fri, 20 Oct 2006 08:03:36 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<guid isPermaLink="false" />
		<description><![CDATA[Recently I have been trying the &#8220;BDD&#8221;:http://behaviour-driven.org/
 (Behavior-Driven Development) approach to developing software. Normally, when I am doing TDD there are a couple of &#8220;house-rules&#8221; that I like to follow. These have developed over time, often following advice from either a colleague or other resource.
One such &#8220;rule&#8221; that has developed over time is that I [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I have been trying the &#8220;BDD&#8221;:http://behaviour-driven.org/<br />
 (Behavior-Driven Development) approach to developing software. Normally, when I am doing TDD there are a couple of &#8220;house-rules&#8221; that I like to follow. These have developed over time, often following advice from either a colleague or other resource.</p>
<p>One such &#8220;rule&#8221; that has developed over time is that I tend not to use the SetUp and TearDown methods that the xUnit tools have. These are used to execute some piece of setup and/or teardown code before/after every test method is executed. The reason to use these is of course that you might have some code that is needed to setup the system under test, and this setup code tends to be the same for all test methods in a fixture. To keep things &#8220;DRY&#8221;:http://en.wikipedia.org/wiki/Don&#8217;t_repeat_yourself you will naturally want to put this code in a single place and have it executed along with each test. The xUnit tools have different ways of accomplishing this. NUnit for instance uses reflection to find methods marked with the SetUpAttribute in a class and executes them before each test method is executed.</p>
<p>As I started out doing writing unit tests these methods seemed like a great idea. As soon as I learned about them all test fixtures would have them, in fact the first thing I did when creating a new fixture was to add these methods with a &#8220;copy-paste template&#8221; (or using snippets or similar when they exist). However, after a while a feeling of something being wrong started showing. Discussing the matter with &#8220;others&#8221;:http://www.taylor.se/blog and doing some &#8220;online reading&#8221;:http://www.agileprogrammer.com/dotnetguy/articles/SetupTeardown.aspx led me to the conclusion that SetUp/TearDown was *evil incarnated*.</p>
<p>One of the best things about using TDD is that you almost never need to do any debugging. One of the reasons for this is that when you do some modification to your code and then run the tests, if there is anything wrong you will instantly get feedback about it from a red test. You read the name and location (fixture) of the test and take a look at it, and if you have done things right the test will tell you exactly what it does. With this you will hopefully be able to more or less immediately figure out what you did wrong, and fix it. However, if the test is not well written and does not quickly and easily tell you what it does, then you lose this feedback, or at least a part of it. So what has this got to do with SetUp/TearDown? Well, when the test called Foo in fixture Bar blows up on you and you take a look at it, you want to quickly see what it does. If you are using a SetUp method then you will not get the full picture by simply looking at the test. You also need to take a look at the SetUp, and possibly the TearDown (and then TestFixtureSetUp/TestFixtureTearDown if it is really bad). And, of course we must also know that our xUnit tool works this way, since the test method code shows no evidence of a setup method being called. So, instead of using these tools that xUnit gives us, we should instead be refactoring the common setup code into a separate method and then call that method &#8220;explicitly&#8221; from each test method. That way it is clear when we look at the test method what it does.</p>
<p>Here is an example of a test fixture written this way (in C# using NUnit):</p>
<pre name="code" class="c-sharp">
using System;
using NUnit.Framework;
using SystemUnderTest;

namespace SystemUnderTest.Tests
{
	[TestFixture]
	public class AccountWithBalance100_WithoutSetup {
		private Account account;

		private void Init() {
			account = new Account(100);
		}

		[Test]
		public void Depositing50LeavesBalanceOf150() {
			Init();
			account.Deposit(50);
			Assert.AreEqual(150, account.Balance);
		}

		[Test]
		public void Withdrawing50LeavesBalanceOf50() {
			Init();
			account.Withdraw(50);
			Assert.AreEqual(50, account.Balance);
		}

		[Test]
		public void Withdrawing100LeavesBalanceOf0() {
			Init();
			account.Withdraw(100);
			Assert.AreEqual(0, account.Balance);
		}

		[Test]
		[ExpectedException(typeof(ArgumentException))]
		public void Withdrawing101ThrowsException() {
			Init();
			account.Withdraw(101);
		}
	}
}
</pre>
<p>So, that is the end of that story the, right? Well, I started out this blog entry writing about BDD, not about SetUp/TearDown. So I guess I need to tie this together now. As I said I have been trying BDD instead for a while now. Apart from calling tests specifications and fixtures contexts, there is not a whole lot different between TDD and BDD. At least on the surface, that is. The whole reason to change the terminology is to &#8220;force&#8221; people in doing TDD the right way. This means using the tests (specifications) to specify behavior, not testing bugs. This means that you will think a bit differently, depending on how you are used to thinking with TDD. It might not be a huge step for all, but for me it has made me reflect a bit.</p>
<p>I did not notice it until after a while, but one interesting reflection I make now is that I do not follow some of my old house-rules when specifying in BDD. Take this example, in &#8220;Boo&#8221;:http://boo.codehaus.org/ using &#8220;Specter&#8221;:http://specter.sourceforge.net/:</p>
<pre name="code" class="boo">
import System
import Specter
import SystemUnderTest

context "An account with a balance of 100":
	account as Account

	setup:
		account = Account(100)

	specify "Depositing 50 should leave a balance of 150":
		account.Deposit(50)
		account.Balance.Must.Equal(150)

	specify "Withdrawing 50 should leave a balance of 50":
		account.Withdraw(50)
		account.Balance.Must.Equal(50)

	specify "Withdrawing 100 should leave a balance of 0":
		account.Withdraw(100)
		account.Balance.Must.Equal(0)

	specify "Withdrawing 101 should throw an exception":
		{ account.Withdraw(101) }.Must.Throw(typeof(ArgumentException))
</pre>
<p>This code example shows a typical BDD context and specifications the way I have been writing them. Note the setup part. Specter, the &#8220;xUnit tool&#8221; I am using here, sees this and executes the setup code before each specification is executed. I used it without even thinking about it. The way the specs are qritten, following the *Given* _an account with a balance of 100_, *when* _a withdrawal of 50 is made_ *then* _there should be 50 left_ style, it seems so natural to setup the context in this way. I suppose it is also largely due to the way specifications is so often written using only a single row, or at least very short.</p>
<p>So, when I made this reflection, I thought that if you write unit tests following the one-assert-per-test-method rule, and of course write short test methods, and (maybe most important of all) create a test fixture per &#8220;situation&#8221; (or context&#8230;), then why should it not feel as natural to use setup here? Here is an example of the same tests as above but this time with the init code moved into a SetUp method.</p>
<pre name="code" class="c-sharp">
using System;
using NUnit.Framework;
using SystemUnderTest;

namespace SystemUnderTest.Tests
{
	[TestFixture]
	public class AccountWithBalance100_WithSetup {
		private Account account;

		[SetUp]
		public void Init() {
			account = new Account(100);
		}

		[Test]
		public void Depositing50LeavesBalanceOf150() {
			account.Deposit(50);
			Assert.AreEqual(150, account.Balance);
		}

		[Test]
		public void Withdrawing50LeavesBalanceOf50() {
			account.Withdraw(50);
			Assert.AreEqual(50, account.Balance);
		}

		[Test]
		public void Withdrawing100LeavesBalanceOf0() {
			account.Withdraw(100);
			Assert.AreEqual(0, account.Balance);
		}

		[Test]
		[ExpectedException(typeof(ArgumentException))]
		public void Withdrawing101ThrowsException() {
			account.Withdraw(101);
		}
	}
}
</pre>
<p>I am not quite finished with my thinking about this, so I am not sure if I think this is better. But I do not think that one of these tests, when blowing up in the test runner, would give me less information than the ones in the example without using the SetUp method. Since I know that the failing test is in the &#8220;AccountWithBalance100&#8243; fixture I can easily guess what the variable account holds. But I guess if the setup is more complex then it might not be as easy to name the fixture and/or understand the code.</p>
<p>Comments? Anyone else using BDD that find themselves using setup differently from when doing TDD?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hedgate.net/articles/2006/10/20/to-setup-or-not-to-setup/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.hedgate.net/articles/2006/10/20/to-setup-or-not-to-setup/</feedburner:origLink></item>
		<item>
		<title>FOR XML EXPLICIT</title>
		<link>http://feeds.feedburner.com/~r/ChrisHedgate/~3/327390230/</link>
		<comments>http://www.hedgate.net/articles/2006/10/09/for-xml-explicit/#comments</comments>
		<pubDate>Mon, 09 Oct 2006 06:38:56 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
		
		<guid isPermaLink="false" />
		<description><![CDATA[A couple of weeks ago I was engaged as trainer for the course &#8220;2779: Implementing a Microsoft SQL Server 2005 Database&#8221;:http://www.microsoft.com/learning/syllabi/en-us/2779afinal.mspx. The module that was by far the most difficult according to the attendees was the one on xml, with none of them having any practical experience with xml. One of the things that was [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of weeks ago I was engaged as trainer for the course &#8220;2779: Implementing a Microsoft SQL Server 2005 Database&#8221;:http://www.microsoft.com/learning/syllabi/en-us/2779afinal.mspx. The module that was by far the most difficult according to the attendees was the one on xml, with none of them having any practical experience with xml. One of the things that was specifically difficult to understand was the @FOR XML EXPLICIT@ clause to the @SELECT@ statement.</p>
<p>The EXPLICIT mode of the FOR XML clause is to be used when you need to create XML of a specific format that cannot be done with AUTO or RAW modes. You can use EXPLICIT to generate xml of more or less any format you wish. It is also the most complex mode to use. The AUTO and RAW modes are normally used to transform the result of an existing query from a tabular resultset into an xml stream. The key word in that sentence is existing, by which I mean that whether or not you want the results in xml or not you still use the same query. Just add the FOR XML clause and you&#8217;re good.</p>
<p>With the EXPLICIT mode it is not that easy. The transformation engine that creates the xml stream from the result of a query requires that the resultset is designed specifically for this task. The concept you must understand is what is called a universal table. This table will have all the information that is needed for the transformation engine to generate xml of the format you require. So what is a universal table then? I think it is easiest to start with an example:</p>
<pre name="code">
Tag | Parent | Employee!1!Id
 1  | null   | 280
</pre>
<p>So what does the above mean? First thing to note is the column names. This metadata is used by the transformation engine to create the nodes in the resulting xml output. We must make sure that the query we run (the one we use the FOR XML EXPLICIT clause with) returns a resultset like the one above.</p>
<p>The first two columns must always exist with those names. They are used to describe the  hierarchy of elements in the xml output. Every element that should exist in the needs to be represented by a row in the universal table. Every unique &#8220;type&#8221; of element (ie an element name at a specific level in the hierarchy of the xml fragment) needs to be uniquely idientified by an arbitrary tag number, which is specified in the first column. If the element is nested inside a parent element then the tag number of the parent element should be included in the column for that.</p>
<p>The rest of the column names (in this case only one) specify the names of the nodes in the resulting xml fragment. In our example we have <code>Employee!1!Id</code>. This cryptic combination says that the element tagged with number 1 should be called Employee, and it should have an attribute called Id. Then, for all the rows in the table the value in this column will end up in the Id attribute of element Employee. So the very simple xml fragment we get from the universal table above would look like this:</p>
<pre name="code" class="xml">
<Employee Id="280"></Employee>
</pre>
<p>This is about as much as the course documentation says about FOR XML EXPLICIT and universal tables. Well, it contains a little more but it is quite difficult to see how to use it for more complex examples than what you can easily create with the other modes. So I decided to create an example that does a little more, but still should be quite simple to understand.</p>
<p>Lets say that we have a requirement to produce an xml fragment like the one below.</p>
<pre name="code" class="xml">
<Employee Id="280"
    Login="adventure-works/pamela0"
    SalesLastYear="1927059.1780">
        <Customers>
                <Store CustomerId="1"
                    Name="A Bike Store"
                    Account="AW00000001"/>
                <Store CustomerId="19"
                    Name="Center Cycle Shop"
                    Account="AW00000343"/>
                ...
        </Customers>
</Employee>
</pre>
<p>What we want is an xml fragment describing a specific employee (id=280 in this case) and her customers. The data we need for this can be returned by the following query (run in the AdventureWorks database):</p>
<pre name="code" class="sql">
SELECT Employee.EmployeeId Id
	, Employee.LoginID [Login]
	, SalesPerson.SalesLastYear
	, Store.CustomerID CustomerId
	, Store.Name
	, Customer.AccountNumber Account
FROM HumanResources.Employee Employee
INNER JOIN Sales.SalesPerson SalesPerson
	ON Employee.EmployeeId = SalesPerson.SalesPersonId
INNER JOIN Sales.Store Store
	ON SalesPerson.SalesPersonId = Store.SalesPersonId
INNER JOIN Sales.Customer Customer
	ON Store.CustomerId = Customer.CustomerId
WHERE Employee.EmployeeId = 280
ORDER BY EmployeeId, CustomerID
</pre>
<p>This result includes all the data that should go in the resulting xml fragment. However it does not tell transformation engine how to create it. If we would simply add FOR XML AUTO or RAW we would not at all get the result we want. What we need to do is to create a query that will return a universal table consisting of the data above but in a resultset that includes the metadata needed to create the xml. The following query will do the trick:</p>
<pre name="code" class="sql">
SELECT 1 AS Tag
	, NULL AS Parent
	, Employee.EmployeeId AS [Em