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

<channel>
	<title>Elegant Code &#187; Jan Van Ryswyck</title>
	<atom:link href="http://elegantcode.com/author/jryswyck/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 20 Jul 2010 12:52:47 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Using TransactionScope with SQLite</title>
		<link>http://elegantcode.com/2010/07/02/using-transactionscope-with-sqlite/</link>
		<comments>http://elegantcode.com/2010/07/02/using-transactionscope-with-sqlite/#comments</comments>
		<pubDate>Fri, 02 Jul 2010 22:04:37 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/07/02/using-transactionscope-with-sqlite/</guid>
		<description><![CDATA[Earlier this week I ran into a little quirk with SQLite. Take a look at the following code snippet:
using(var transaction = new TransactionScope(TransactionScopeOption.Required))
{
    using(var connection1 = new SQLiteConnection(_connectionString))
    {
        connection1.Open();

        ... // Do stuff with [...]]]></description>
			<content:encoded><![CDATA[<p>Earlier this week I ran into a little quirk with SQLite. Take a look at the following code snippet:</p>
<pre class="csharpcode"><span class="kwrd">using</span>(var transaction = <span class="kwrd">new</span> TransactionScope(TransactionScopeOption.Required))
{
    <span class="kwrd">using</span>(var connection1 = <span class="kwrd">new</span> SQLiteConnection(_connectionString))
    {
        connection1.Open();

        ... <span class="rem">// Do stuff with the open connection</span>

    } <span class="rem">// Closes the connection (so we think …)</span>

    <span class="kwrd">using</span>(var connection2 = <span class="kwrd">new</span> SQLiteConnection(_connectionString))
    {
        <span class="rem">// This line of code throws a SQLiteException with an error </span>
        <span class="rem">// code 'Busy' after a certain timeout has been expired</span>
        connection2.Open();          

        ...
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>Everything works just fine with the first connection, but the second connection forms a bigger problem. Calling the <em>Open</em> method on the second connection throws a SQLiteException with the message “The database file is locked” and an error code <em>‘Busy’</em> after a particular timeout has been expired. </p>
<p>At first I didn’t have a clue, largely because the <em>TransactionScope</em> was nicely tucked away at a much higher level (NServiceBus deals with transactions for me). But after reading more about the intrinsic behavior of SQLite it all started to make sense. Apparently SQLite supports only one writer at a time. The TransactionScope holds an exclusive writer lock, even when disposing the first connection. Because the first connection cannot fully close itself, opening the second connection results in a lock error.</p>
<p>Hope this helps explain why the obvious isn’t obvious <img src='http://elegantcode.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> .</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/07/02/using-transactionscope-with-sqlite/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Book Review: Switch &#8211; How to Change Things When Change is Hard</title>
		<link>http://elegantcode.com/2010/07/02/book-review-switch-how-to-change-things-when-change-is-hard/</link>
		<comments>http://elegantcode.com/2010/07/02/book-review-switch-how-to-change-things-when-change-is-hard/#comments</comments>
		<pubDate>Fri, 02 Jul 2010 19:16:55 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[Books]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/07/02/book-review-switch-how-to-change-things-when-change-is-hard/</guid>
		<description><![CDATA[ 
After hearing about this book in an interview with Mary and Tom Poppendieck, I decided to immediately purchase the audio version on Audible and listen to it during my daily commute to and from work. This book is all about how to enable and inspire change in all kinds of environments, be it at [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://elegantcode.com/wp-content/uploads/2010/07/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="image" border="0" alt="image" align="left" src="http://elegantcode.com/wp-content/uploads/2010/07/image_thumb.png" width="212" height="276" /></a> </p>
<p>After hearing about this book in an <a href="http://www.infoq.com/interviews/poppendieck-interview">interview with Mary and Tom Poppendieck</a>, I decided to immediately purchase the audio version on Audible and listen to it during my daily commute to and from work. This book is all about how to enable and inspire change in all kinds of environments, be it at work, your local community or your private life.</p>
<p>The authors <a href="http://heathbrothers.com/">Chip Heath and Dan Heath</a> make the advice to focus on the so-called <em>“bright spots”. </em>Most people, including myself, focus on flawed behavior and the things that go wrong. Instead, we should first be looking at the the things that go right, copy and do more of it in order to make change happen. Scaling up the “bright spots” instead of focusing on the negative parts. </p>
<p>In the book, change management is compared with an elephant with a rider on his back who are following a certain path. </p>
<p>The topic of change is therefore broken down in three simple sections: </p>
<ol>
<li>Direct the <em>Rider -</em> This represents the rational and logical part of the brain. This thoughtful part responds well to reason, facts and provides long-term thinking. In order to tell the rider what to do, just provide good arguments. </li>
<li>Motivate the <em>Elephant -</em> This part of our brain responds to emotions and short-term gain. This is the biggest part and one where the <em>Rider</em> has limited control over, so both need to be convinced.</li>
<li>Shape the <em>Path -</em> This completes the analogy made by the authors representing the <em>Path</em> which the <em>Elephant</em> and <em>Rider</em> are following.</li>
</ol>
<p>When we’re faced in making a decision, we&#8217;re often torn between our rational, logical reasons    <br />and our emotional, intuitive feelings. The general consensus in the book is that if the <em>Rider</em> can direct the <em>Elephant</em> down a well prepared <em>Path</em> then there is a good chance for change. The authors filled the book with dozens of real-life, scientific and practical examples where these principles worked brilliantly (there’s even a story about BP and oil-drilling!!).</p>
<p>These are the nine steps that are illustrated by these anecdotal stories:</p>
<ol>
<li>Find the bright spots – Focus on the successes and not the failures.</li>
<li>Script the critical moves – Remove decision paralysis by laying down small and easy steps.</li>
<li>Point to the destination – Clearly describe and put out a goal that is hard to neglect and to which people can relate.</li>
<li>Find the feeling – Try to find an emotional connection.</li>
<li>Shrink the change – As agilists we all know the value of taking small steps. All big things are accomplished in tiny small steps. Change is no exception.</li>
<li>Grow your people – Stimulate the “growth mindset” in people, helping to create a new identity to which people can relate.</li>
<li>Tweak the environment – Make the necessary changes to peoples’ environment in order to point to the right direction. </li>
<li>Build habits – Change peoples’&#8217; habits in order to change long-term behavior.</li>
<li>Rally the herd – Use the power of group behavior. </li>
</ol>
<ol>The first three steps are targeted at directing the <em>Rider</em>, the next three steps on motivating the <em>Elephant</em> and the last three steps on shaping the <em>Path</em>.</ol>
<ol>You just need to read this book for yourself and utilize all the information that you’ve picked up from it. Just give it a try. Its a quick read (or listen) and afterwards, you’d be glad you did.</ol>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/07/02/book-review-switch-how-to-change-things-when-change-is-hard/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Enter a Parallel Universe Using IKVM.NET</title>
		<link>http://elegantcode.com/2010/06/25/enter-a-parallel-universe-using-ikvm-net/</link>
		<comments>http://elegantcode.com/2010/06/25/enter-a-parallel-universe-using-ikvm-net/#comments</comments>
		<pubDate>Fri, 25 Jun 2010 23:20:27 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/06/25/enter-a-parallel-universe-using-ikvm-net/</guid>
		<description><![CDATA[IKVM.NET is something I’ve been playing with for a while now, but seeing this awesome trailer today reminded me that I should write a post about it. 
I always considered Java to be some kind of parallel universe compared to .NET where a lot of interesting lessons can be learned. I never did any serious [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ikvm.net/index.html">IKVM.NET</a> is something I’ve been playing with for a while now, but seeing <a href="http://jz10.java.no/java-4-ever-trailer.html">this awesome trailer</a> today reminded me that I should write a post about it. </p>
<p>I always considered Java to be some kind of parallel universe compared to .NET where a lot of interesting lessons can be learned. I never did any serious Java development throughout my professional career, but I like to follow up on the trends in the Java community. Although the Java community suffers from some of the same diseases as the .NET community, the wide-spread acceptance of open-source and the adoption of new, fascinating languages on top of the JVM is an interesting evolution that I feel is lacking in the .NET world. Although the CLR/DLR is probably better designed to host a wider diversity of programming languages than the JVM, the rise of programming languages like <a href="http://www.scala-lang.org/">Scala</a>, <a href="http://clojure.org/">Clojure</a>, <a href="http://groovy.codehaus.org/">Groovy</a> and others is more sparse in the Java universe. Some of the most useful open-source projects in .NET today&#160; initially started out by porting the code of established Java libraries, like NUnit, NHibernate and Spring.NET, etc. …. Anyway, we’re wandering off.</p>
<p>Did you ever need to interoperate with a Java library while developing .NET applications? I have to admit, it doesn’t come up very often but when it does (especially when using IBM products <img src='http://elegantcode.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  ), IKVM.NET might save you from a whole lot of trouble. </p>
<p>With IKVM.NET its possible to use Java API’s from a .NET application or even to use the Java language to develop .NET applications. Let me show you a quick example.</p>
<p>Say for example that you’re done with the DateTime class in .NET and you need a library that gives you more power in dealing with dates and time in your .NET applications. You do a little searching on the web and there it is, a full blown API like <a href="http://joda-time.sourceforge.net/">Joda Time</a> (I’m well aware that honorable <a href="http://msmvps.com/blogs/jon_skeet/">Jon Skeet</a> has <a href="http://code.google.com/p/noda-time/">ported this framework to .NET</a> already, but bear with me).</p>
<p>All we have to do to start using Joda Time in a .NET application is to download <em>joda-time.jar</em> and feed it to the <em>ikvmc.exe</em> command-line tool that comes with the binaries of IKVM.NET. Out comes a full blown .NET assembly by executing the following command:</p>
<blockquote><p>ikvmc -target:library joda-time-1.6.jar</p>
</blockquote>
<p>There are a whole slew of other options that you can specify here, like signing the resulting assembly (who still does that, really), specifying the assembly version, etc. …</p>
<p>This is how the generated assembly looks like in Reflector.</p>
<p><a href="http://elegantcode.com/wp-content/uploads/2010/06/Reflector.jpg"><img style="border-bottom: 0px; border-left: 0px; display: inline; margin-left: 0px; border-top: 0px; margin-right: 0px; border-right: 0px" title="Reflector" border="0" alt="Reflector" src="http://elegantcode.com/wp-content/uploads/2010/06/Reflector_thumb.jpg" width="240" height="210" /></a> </p>
<p>The following block of code is small utility that I developed to deal with the time zone arithmetic for the <a href="http://europevan.blogspot.com/">Europe Virtual ALT.NET</a>. </p>
<pre class="csharpcode"><span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Windows.Forms;
<span class="kwrd">using</span> org.joda.time;
<span class="kwrd">using</span> org.joda.time.format;
<span class="kwrd">using</span> DateTime = org.joda.time.DateTime;
<span class="kwrd">using</span> TimeZone = java.util.TimeZone;

<span class="kwrd">public</span> <span class="kwrd">partial</span> <span class="kwrd">class</span> Main : Form
{
    <span class="kwrd">private</span> <span class="kwrd">const</span> String London = <span class="str">&quot;Europe/London&quot;</span>;
    <span class="kwrd">private</span> <span class="kwrd">const</span> String Brussels = <span class="str">&quot;Europe/Brussels&quot;</span>;
    <span class="kwrd">private</span> <span class="kwrd">const</span> String EST = <span class="str">&quot;EST&quot;</span>;
    <span class="kwrd">private</span> <span class="kwrd">const</span> String MST = <span class="str">&quot;MST&quot;</span>;
    <span class="kwrd">private</span> <span class="kwrd">const</span> String PST = <span class="str">&quot;PST&quot;</span>;

    <span class="kwrd">public</span> Main()
    {
        InitializeComponent();
        DateTimeTextBox.Text = CurrentDateAndTime();
    }

    <span class="kwrd">private</span> <span class="kwrd">void</span> ConvertButton_Click(Object sender, EventArgs e)
    {
        var dateTime = <span class="kwrd">new</span> DateTime(DateTimeTextBox.Text, DateTimeZone.UTC);

        var london = ConvertToTimeZone(London, dateTime);
        var brussels = ConvertToTimeZone(Brussels, dateTime);
        var est = ConvertToTimeZone(EST, dateTime);
        var mst = ConvertToTimeZone(MST, dateTime);
        var pst = ConvertToTimeZone(PST, dateTime);

        var formatter = BuildDateTimeFormatter();

        ResultTextBox.Text = String.Format(
            <span class="str">&quot;{0} UK, {1} Brussels, {2} EST, {3} MST and {4} PST.&quot;</span>,
            london.toString(formatter),
            brussels.toString(formatter),
            est.toString(formatter),
            mst.toString(formatter),
            pst.toString(formatter));
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> String CurrentDateAndTime()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> DateTime(DateTimeZone.UTC).ToString();
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> DateTime ConvertToTimeZone(String timeZone, DateTime dateTime)
    {
        var targetTimeZone = DateTimeZone
            .forTimeZone(TimeZone.getTimeZone(timeZone));
        <span class="kwrd">return</span> dateTime.toDateTime(targetTimeZone);
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> DateTimeFormatter BuildDateTimeFormatter()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> DateTimeFormatterBuilder()
            .appendHourOfHalfday(2)
            .appendLiteral(<span class="str">&quot;:&quot;</span>)
            .appendMinuteOfHour(2)
            .appendLiteral(<span class="str">&quot; &quot;</span>)
            .appendHalfdayOfDayText()
            .toFormatter();
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>The distribution of IKVM.NET also comes with .NET implementation of a whole slew of Java class libraries that you can directly use in a .NET application whenever needed.</p>
<p><a href="http://elegantcode.com/wp-content/uploads/2010/06/IKVM.jpg"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="IKVM" border="0" alt="IKVM" src="http://elegantcode.com/wp-content/uploads/2010/06/IKVM_thumb.jpg" width="400" height="377" /></a> </p>
<p>But remember, as with all things that seem too good to be true, there are a couple of major downsides as well. The one that you run into fairly quickly is generics. I tried generating a .NET assembly from <a href="http://code.google.com/p/make-it-easy/">Make It Easy</a> the other day and I noticed that some of the types in the resulting assembly where plain classes while they were defined as generics in the original JAR file. The explanation that I found was that Java checks generics only at compile time and not at runtime. In .NET generics are provided at runtime. If the generics from Java would convert to .NET, then every Java compiler warning would produce a runtime error. All the old code would not run. There is many old code in the Java VM itself. </p>
<p>The <a href="http://weblog.ikvm.net/">IKVM.NET blog</a> is a great resource for some of the other interoperability issues you might experience. Maybe this will come in handy someday, who knows?</p>
<p>Till next time.</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/06/25/enter-a-parallel-universe-using-ikvm-net/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Learning JavaScript &#8211; Checking The Declaration of a Variable</title>
		<link>http://elegantcode.com/2010/06/25/learning-javascript-checking-the-declaration-of-a-variable/</link>
		<comments>http://elegantcode.com/2010/06/25/learning-javascript-checking-the-declaration-of-a-variable/#comments</comments>
		<pubDate>Fri, 25 Jun 2010 19:53:05 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/06/25/learning-javascript-checking-the-declaration-of-a-variable/</guid>
		<description><![CDATA[Judging from my previous post, some people might have come to the conclusion that I’m in the process of learning a wonderful programming language called JavaScript. Well, they’re right! It is a fascinating programming language although it has its quirks and pitfalls.
Have a look at the following piece of code:
var someString = &#34;Hi there&#34;;
if(someVariable)
  [...]]]></description>
			<content:encoded><![CDATA[<p>Judging from my <a href="http://elegantcode.com/2010/05/24/book-review-javascript-the-good-parts/">previous post</a>, some people might have come to the conclusion that I’m in the process of learning a wonderful programming language called JavaScript. Well, they’re right! It is a fascinating programming language although it has its quirks and pitfalls.</p>
<p>Have a look at the following piece of code:</p>
<pre class="csharpcode"><span class="kwrd">var</span> someString = <span class="str">&quot;Hi there&quot;</span>;
<span class="kwrd">if</span>(someVariable)
    someString = <span class="str">&quot;Hello JS Ninja&quot;</span>;</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>The if statement tries to check for the existence of a variable called <em>someVariable</em> which is not declared. Because it’s not declared, the code generated the following reference error:</p>
<blockquote>
<p>&quot;someVariable is not defined&quot;</p>
</blockquote>
<p>Nonetheless, the following line of code nicely outputs the text <em>“Hi there”</em> which means that the previous code block still executes.</p>
<pre class="csharpcode">alert(someString);</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>Suppose we did bother to declare <em>someVariable</em> but that it doesn’t contain a value that evaluates to <em>true.</em> In that case we’d still have the same outcome which is not what we intended.&#160; </p>
<p>A better way to check for the existence of <em>someVariable</em> is to use <em>typeof</em> instead:</p>
<pre class="csharpcode"><span class="kwrd">var</span> someString = <span class="str">&quot;Hi there&quot;</span>;
<span class="kwrd">if</span>(<span class="str">&quot;undefined&quot;</span> ==! <span class="kwrd">typeof</span> someVariable)
    someString = <span class="str">&quot;Hello JS Ninja&quot;</span>;</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>This still yields the same output as the previous code sample but now without the reference error. <em>typeof</em> always returns a string no matter what, but the difference now is that we’re testing whether the variable has a value besides <em>undefined</em>.</p>
<p>So the following piece of code outputs “Hello JS Ninja” on the screen:</p>
<pre class="csharpcode"><span class="kwrd">var</span> someString = <span class="str">&quot;Hi there&quot;</span>;
<span class="kwrd">var</span> someVariable = <span class="kwrd">false</span>;

<span class="kwrd">if</span>(<span class="str">&quot;undefined&quot;</span> !== <span class="kwrd">typeof</span> someVariable)
    someString = <span class="str">&quot;Hello JS Ninja&quot;</span>;

alert(someString);</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>On the other hand, the following piece of code again results in the message <em>“Hi there”:</em></p>
<pre class="csharpcode"><span class="kwrd">var</span> someString = <span class="str">&quot;Hi there&quot;</span>;
<span class="kwrd">var</span> someVariable;
<span class="kwrd">if</span>(<span class="str">&quot;undefined&quot;</span> !== <span class="kwrd">typeof</span> someVariable)
    someString = <span class="str">&quot;Hello JS Ninja&quot;</span>;

alert(someString);</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>This is the part where I usually get a headache and have to go search for aspirin.</p>
<p>Till next time.</p>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/06/25/learning-javascript-checking-the-declaration-of-a-variable/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Book Review: JavaScript &#8211; The Good Parts</title>
		<link>http://elegantcode.com/2010/05/24/book-review-javascript-the-good-parts/</link>
		<comments>http://elegantcode.com/2010/05/24/book-review-javascript-the-good-parts/#comments</comments>
		<pubDate>Mon, 24 May 2010 19:36:17 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[Books]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/05/24/book-review-javascript-the-good-parts/</guid>
		<description><![CDATA[
Today I finished reading JavaScript – The Good Parts written by Douglas Crockford. That picture on his website of him speaking with Chuck Norris on the background should make you run to the local bookstore to buy a copy of his book  . I instantly knew after listening to one or two podcasts, where [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://elegantcode.com/wp-content/uploads/2010/05/image5.png"><img style="border-right-width: 0px; margin: 0px 10px 0px 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" align="left" src="http://elegantcode.com/wp-content/uploads/2010/05/image_thumb4.png" width="172" height="228" /></a></p>
<p>Today I finished reading <a href="http://www.amazon.com/exec/obidos/ASIN/0596517742/elegantcode-20">JavaScript – The Good Parts</a> written by <a href="http://www.crockford.com/">Douglas Crockford</a>. That picture on <a href="http://www.crockford.com/">his website</a> of him speaking with Chuck Norris on the background should make you run to the local bookstore to buy a copy of his book <img src='http://elegantcode.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> . I instantly knew after listening to one or two podcasts, where the author appeared as a guest, that his book just had to be good. One can easily notice by the way the author speaks and writes about <a href="http://nl.wikipedia.org/wiki/JavaScript">JavaScript</a> that the author definitely knows his stuff on the subject.</p>
<p>This book is a rather quick read because its only 100 pages long (with appendixes ~145 pages). I started reading this book as a complete rookie when it comes to JavaScript. I must say that I can’t recommend this book as a first book on JavaScript. Don’t get me wrong. I really learned a lot from this book without any foreknowledge&#160; whatsoever. But still, I wish the author had written some sort of a “JavaScript for Beginners” book that could precede “The Good Parts” book in order to get up to speed on all the different parts of the language. </p>
<p>This book is so full of little gems on the JavaScript programming language that I don’t know where to begin. The part of chapter 4 on <em>Functions</em> that describe the four patterns of invocation were a real eye opener and the examples on scope with closures really blew my mind. The chapter on regular expressions is also highly recommended. The only chapter that I didn’t like that much is chapter 8 called <em>Methods</em>. This chapter is completely composed with some kind of API documentation of the <em>Array</em>, <em>Number</em>, <em>Object</em> and <em>RegExp</em> and <em>String</em> objects which I found a bit weird in the book. Also make sure to read through the appendixes where the awful and bad parts are written down as well. These explain the particular language features that are best avoided and why they’re not as good as they look.</p>
<p>Nonetheless, I really enjoyed reading this book and learning about the good and also the bad parts of JavaScript. I think I’m going to read one or two beginner books on JavaScript after which I’m going to give it another thorough read. </p>
<p>Until next time</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/05/24/book-review-javascript-the-good-parts/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Linfu Duck Typing Part 1 &#8211; Revealing Secrets</title>
		<link>http://elegantcode.com/2010/04/16/linfu-duck-typing-part-1-revealing-secrets/</link>
		<comments>http://elegantcode.com/2010/04/16/linfu-duck-typing-part-1-revealing-secrets/#comments</comments>
		<pubDate>Fri, 16 Apr 2010 19:10:47 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/04/16/linfu-duck-typing-part-1-revealing-secrets/</guid>
		<description><![CDATA[Don’t you just hate it when a class in the .NET Framework or another third-party library or framework provides that particular feature you’re looking for only to realize that this class has not been made accessible? One blatant example of this is the SqlCommandSet class in the System.Data.SqlClient namespace. 
One can use reflection in order [...]]]></description>
			<content:encoded><![CDATA[<p>Don’t you just hate it when a class in the .NET Framework or another third-party library or framework provides that particular feature you’re looking for only to realize that this class has not been made accessible? One blatant example of this is the <a href="http://ayende.com/Blog/archive/2006/09/14/ThereBeDragonsRhinoCommonsSqlCommandSet.aspx">SqlCommandSet</a> class in the <a href="http://ayende.com/Blog/archive/2006/09/14/ThereBeDragonsRhinoCommonsSqlCommandSet.aspx">System.Data.SqlClient</a> namespace. </p>
<p>One can use reflection in order to access and use this private class. An even better and more efficient approach would be to <a href="http://elegantcode.com/2010/01/28/calling-non-public-methods/">use delegates</a> instead. But there’s also another simple and elegant solution which I briefly mentioned in <a href="http://elegantcode.com/2010/03/26/dont-give-up-on-the-state-pattern-just-yet-revisited/">a previous post</a> namely <a href="http://en.wikipedia.org/wiki/Duck_typing">duck typing</a>.</p>
<p>Now in order to access the <em>SqlCommandSet</em> class we need to define an interface with all of the methods we want to access from our code. <a href="http://www.red-gate.com/products/reflector/">Reflector</a> can come in handy in this case to determine which particular methods we need.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">interface</span> ISqlCommandSet : IDisposable
{
    SqlConnection Connection { get; set; }

    <span class="kwrd">void</span> Append(SqlCommand command);
    Int32 ExecuteNonQuery();
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>&#160;</p>
<p>This is pretty much what we need from a <em>SqlCommandSet</em>. Now we can create a factory class for creating instances of the <em>SqlCommandSet </em>class.</p>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> SqlCommandSetFactory
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> Type _typeOfSqlCommandSet;

    <span class="kwrd">public</span> SqlCommandSetFactory()
    {
        var system_data = Assembly.Load(<span class="str">&quot;System.Data,
                                         Version=2.0.0.0,
                                         Culture=neutral,
                                         PublicKeyToken=b77a5c561934e089&quot;</span>);

        _typeOfSqlCommandSet =
            system_data.GetType(<span class="str">&quot;System.Data.SqlClient.SqlCommandSet&quot;</span>);
    }

    <span class="kwrd">public</span> ISqlCommandSet CreateSqlCommandSet()
    {
        var instance = Activator.CreateInstance(_typeOfSqlCommandSet, <span class="kwrd">true</span>);
        var dynamicObject = <span class="kwrd">new</span> DynamicObject(instance);
        <span class="kwrd">return</span> dynamicObject.CreateDuck&lt;ISqlCommandSet&gt;();
    }
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>&#160;</p>
<p>The <em>System.Data</em> assembly is loaded and the type of the <em>SqlCommandSet</em> is determined in the constructor of the factory class. In the factory method itself we first create an instance of the <em>SqlCommandSet</em> class and then use LinFu’s <em>DynamicObject</em> to <em>‘cast’</em> it to our <em>ISqlCommandSet</em> interface. And this is pretty much it. Now we can use a <em>SqlCommandSet</em> at will. </p>
<pre class="csharpcode"><span class="kwrd">using</span>(var connection = <span class="kwrd">new</span> SqlConnection(<span class="str">@&quot;...&quot;</span>))
{
    connection.Open();

    <span class="kwrd">using</span>(var command1 = <span class="kwrd">new</span> SqlCommand(<span class="str">&quot;INSERT INTO BLABLA ...&quot;</span>))
    <span class="kwrd">using</span>(var command2 = <span class="kwrd">new</span> SqlCommand(<span class="str">&quot;INSERT INTO BLA BLA ...&quot;</span>))
    {
        var commandSet = <span class="kwrd">new</span> SqlCommandSetFactory().CreateSqlCommandSet();
        commandSet.Connection = connection;
        commandSet.Append(command1);
        commandSet.Append(command2);
        commandSet.ExecuteNonQuery();
    }
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>&#160;</p>
<p>Again I’d like to mention that I’ve been using the <em>DynamicObject</em> class from Linfu 1.0 which you can download <a href="http://code.google.com/p/linfu/downloads/list">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/04/16/linfu-duck-typing-part-1-revealing-secrets/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Book Review: ASP.NET MVC in Action</title>
		<link>http://elegantcode.com/2010/04/09/book-review-asp-net-mvc-in-action/</link>
		<comments>http://elegantcode.com/2010/04/09/book-review-asp-net-mvc-in-action/#comments</comments>
		<pubDate>Fri, 09 Apr 2010 22:38:11 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[Books]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/04/09/book-review-asp-net-mvc-in-action/</guid>
		<description><![CDATA[ 
Earlier this week I finished reading ASP.NET MVC in Action written by Jeffrey Palermo, Ben Scheirman and Jimmy Bogard.&#160; I came across several good reviews about this book so I finally decided to give a read.&#160; 
This book is not just about the API’s of the ASP.NET MVC framework but also about good design [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://elegantcode.com/wp-content/uploads/2010/04/ASP.NETMVCinAction.jpg"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="ASP.NET MVC in Action" border="0" alt="ASP.NET MVC in Action" align="left" src="http://elegantcode.com/wp-content/uploads/2010/04/ASP.NETMVCinAction_thumb.jpg" width="188" height="233" /></a> </p>
<p>Earlier this week I finished reading <a href="http://www.amazon.com/exec/obidos/ASIN/1933988622/elegantcode-20">ASP.NET MVC in Action</a> written by <a href="http://jeffreypalermo.com/">Jeffrey Palermo</a>, <a href="http://flux88.com/">Ben Scheirman</a> and <a href="http://www.lostechies.com/blogs/jimmy_bogard/default.aspx">Jimmy Bogard</a>.&#160; I came across several good reviews about this book so I finally decided to give a read.&#160; </p>
<p>This book is not just about the API’s of the ASP.NET MVC framework but also about good design principles for creating long-lived web applications. When you’re not familiar with the <a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod">S.O.L.I.D. principles</a> and also want to learn about the very basics of <a href="http://en.wikipedia.org/wiki/Domain-driven_design">Domain-Driven Design</a> in the context of web applications, then this book is definitely for you. For me personally, being indoctrinated with this stuff for quite some time now, I didn’t pick up that many new things except for some of the ins and outs of the&#160; ASP.NET MVC framework.&#160; </p>
<p>Nonetheless, I strongly believe that this kind of books are still highly needed to raise the bar of quality in the .NET community. Practices like unit testing, continuous integration, DRY, etc. are sadly enough not part of the mainstream yet. The authors also had the courage to provide an entire chapter where they explore other MVC frameworks like <a href="http://www.castleproject.org/monorail/">MonoRail</a> and <a href="http://rubyonrails.org/">Ruby on Rails</a> which, from my point of view, adds tremendous value to the awareness of the unsuspecting .NET developer.</p>
<p>The first three chapters provide an in dept overview of the parts that constitute the MVC pattern, namely the Model, the View and the Controller. I must say that I’m still not a big fan of the way ASP.NET MVC passes a dictionary of data to its views. I know that you don’t have to use it this way and that a single strongly typed model can be passed to the view. But the presence of a dictionary for me is just a too big a risk that can easily result in creating a mess. </p>
<p>Chapter 5 provides a solid overview of the routing capabilities of the .NET framework including some nice examples. Chapter 6 contains information on how to extend ASP.NET MVC using controller factories, action filters, custom view engines, etc. … . Chapter 7 discusses how to leverage view helpers and creating partial views which I find are quite important features for composing scalable web applications. </p>
<p>Chapter 8 is the one I skimmed through very quickly as it shows how to use existing ASP.NET features with ASP.NET MVC. The part on using existing ASP.NET server controls is totally unnecessary and although you can pull it off in a couple of cases, I advise you to not apply these techniques in a production application.</p>
<p>Chapter 9 shows how to use AJAX in ASP.NET MVC. Pretty basic examples there. </p>
<p>Chapter 10 talks about deployed and contains some interesting ideas on how to use MsBuild, NAnt, Rake, … for automatically deploying a web application into a testing and/or production environment including configuration and environmental setup.&#160; </p>
<p>As already mentioned, chapter 11 shows some basic features of other MVC frameworks. In the last two chapters, the authors provide some best practices and recipes for ASP.NET MVC.</p>
<p>As I already mentioned, if you’re only goal is to get up to speed with the API of ASP.NET MVC then I guess there are better resources out there. For that reason I also bought the <a href="http://www.tekpub.com/preview/aspmvc">Mastering ASP.NET MVC 2.0 series on TekPub</a> to fill in the potential gaps and also to learn more about the new stuff in ASP.NET MVC 2.0.</p>
<p>All in all, I enjoyed reading this book. If I have to give one suggestion for improvement, then I would advocate to add more cohesion to the book. I feel that some topics are scattered all over the place. For example, the use of Castle validators is discussed in two different chapters in the book with some degree of overlap. If only one part of the book was devoted to validation, then its far more easier to go back there for future reference. </p>
<p>I noticed that a <a href="http://www.manning.com/palermo2/">second edition</a> of ASP.NET MVC in Action is already available as an early access edition. While looking at the table of contents, some of the content from the first edition has certainly been moved around which I consider to be a good thing. I also hope that the second edition will also include some comparisons with features from <a href="http://github.com/darthfubumvc/fubumvc">Fubu MVC</a> and <a href="http://trac.caffeine-it.com/openrasta">OpenRasta</a>.</p>
<p>Until next time</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/04/09/book-review-asp-net-mvc-in-action/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Don&#8217;t Give Up on the State Pattern Just Yet &#8211; Revisited</title>
		<link>http://elegantcode.com/2010/03/26/dont-give-up-on-the-state-pattern-just-yet-revisited/</link>
		<comments>http://elegantcode.com/2010/03/26/dont-give-up-on-the-state-pattern-just-yet-revisited/#comments</comments>
		<pubDate>Sat, 27 Mar 2010 00:05:25 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/03/26/dont-give-up-on-the-state-pattern-just-yet-revisited/</guid>
		<description><![CDATA[In my previous post on the subject, I showed how you can remove some of the friction caused by applying the State pattern. In fact, as some of you rightfully pointed out, this friction isn’t caused by the State pattern itself but by a violation of the Interface Segregation Principle.&#160;&#160; The use of role interfaces [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://elegantcode.com/2010/03/19/dont-give-up-on-the-state-pattern-just-yet/">previous post</a> on the subject, I showed how you can remove some of the friction caused by applying the <a href="http://en.wikipedia.org/wiki/State_pattern">State pattern</a>. In fact, as some of you rightfully pointed out, this friction isn’t caused by the State pattern itself but by a violation of the <a href="http://www.objectmentor.com/resources/articles/isp.pdf">Interface Segregation Principle</a>.&#160;&#160; The use of <a href="http://martinfowler.com/bliki/RoleInterface.html">role interfaces</a> somewhat mitigated this violation but caused some type checking and casting in the context class (named <em>Account</em> in our example).</p>
<p>I just wanted to put out a slight variation of our solution that defers this kind of type checking until runtime. In other words, we’re going to apply some <a href="http://en.wikipedia.org/wiki/Duck_typing">duck typing</a> in order to come up with some improvements. </p>
<p>But hang on, isn’t C# supposed to be a static language and isn’t duck typing an exclusive feature of dynamic languages like Ruby or Python? Heck no! One can have duck typing in a static language as well. A good example of this is the <a href="http://boo.codehaus.org/">Boo programming language</a> which is a static language but provides <a href="http://boo.codehaus.org/Duck+Typing">the ability to give up this safety net</a>. But I do believe that dynamic languages like Ruby or Python provide a more supple syntax for supplying duck typing capabilities while a static language usually requires a bit more ceremony. </p>
<p>The latest C# 4.0 compiler delivers some dynamic language features using the <a href="http://msdn.microsoft.com/en-us/library/dd264736%28VS.100%29.aspx">dynamic</a> keyword which in turn accomplishes it’s functionality by leveraging the <em><a href="http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject%28VS.100%29.aspx">DynamicObject</a></em> class (which seems to live in the System.Dynamic namespace). I have to admit that I didn’t spent much time on this yet.</p>
<p>But while the rest of the world is still on .NET 3.5 or earlier versions of the .NET framework, we don’t have to wait until the next upgrade to use some of the dynamic language features like duck typing, mixins and the like. </p>
<p>Let me first show you the code of the <em>Account</em> class from the previous post that demonstrates the type checking and casting to a role interface:&#160; </p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> Withdraw(<span class="kwrd">double</span> amount)
{
    <span class="rem">// One can not always withdraw</span>
    <span class="kwrd">if</span>(<span class="kwrd">false</span> == CanWithdraw())
    {
        <span class="rem">// Should throw an exception or at least a towel</span>
        Console.WriteLine(<span class="str">&quot;No funds available for withdrawal!&quot;</span>);
        <span class="kwrd">return</span>;
    }

    var canWithdraw = (ICanWithdraw)State;
    canWithdraw.Withdraw(amount);

    ...
}

<span class="kwrd">private</span> Boolean CanWithdraw()
{
    <span class="kwrd">return</span> State <span class="kwrd">is</span> ICanWithdraw;
}</pre>
<p>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</p>
<p>What I would like to do is to remove the <em>CanWithdraw</em> check entirely without running into a <em>NullReferenceException</em> when a particular state doesn’t support withdrawing money. But first, I want to slightly decouple the <em>Account</em> class from the <em>SilverState</em>, <em>GoldState</em> and <em>RedState</em> classes by introducing an interface named <em>IAccountStateChanger</em>.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">interface</span> IAccountStateChanger
{
    <span class="kwrd">void</span> InstituteStateTo(State newState);
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>&#160;</p>
<p>This is now used by the state classes to change the state of the <em>Account</em> class without using a property setter in order to get rid of <a href="http://elegantcode.com/2008/09/26/properties-a-false-sense-of-encapsulation/">the false sense of encapsulation</a>. The implementation of this interface by the <em>Account</em> class is where the fun begins.</p>
<pre class="csharpcode"><span class="kwrd">void</span> IAccountStateChanger.InstituteStateTo(State newState)
{
    _state = newState;
    _dynamicState = <span class="kwrd">new</span> DynamicObject(_state) + _missingStateMethodHandler;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>&#160;</p>
<p>Besides having a state we also introduced a dynamic state which is simply an instance of <a href="http://github.com/philiplaureano/LinFu">Linfu</a>’s <em>DynamicObject</em> class. I’ll talk about the missing state method handler part shortly, but first let’s look what we can do with our dynamic state object.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> Withdraw(Double amount)
{
    var canWithdraw = _dynamicState.CreateDuck&lt;ICanWithdraw&gt;();
    canWithdraw.Withdraw(amount);

    ...
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>&#160;</p>
<p>Notice that we got rid of the type checking part. But what if a particular state doesn’t support withdrawing money? Here’s were the method missing piece of the puzzle falls in. Linfu provides an interface named <em>IMethodMissingCallback</em> which lets you decide what to do when the requested method call cannot be resolved.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> MissingStateMethodHandler : IMethodMissingCallback
{
    <span class="kwrd">public</span> <span class="kwrd">void</span> MethodMissing(Object source, MethodMissingParameters missingParameters)
    {
        <span class="kwrd">if</span>(<span class="kwrd">typeof</span>(ICanWithdraw).GetMethods()[0].Name == missingParameters.MethodName)
        {
            Console.WriteLine(<span class="str">&quot;No funds available for withdrawal!&quot;</span>);

            <span class="rem">// Let Linfu know we're on top of things        </span>
            missingParameters.Handled = <span class="kwrd">true</span>;
        }
    }

    <span class="kwrd">public</span> Boolean CanHandle(MethodInfo method)
    {
        <span class="kwrd">return</span> <span class="kwrd">false</span>;
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>&#160;</p>
<p>You can do pretty much anything in here like delegating the call to another method, but for demonstration purposes we just write a message to console. As shown earlier we literally add an instance of this handler to the dynamic object and we’re all set up. Using this approach yields the same results but without the type checking.</p>
<p>I’d like to mention that I’ve been using the <em>DynamicObject</em> class from Linfu 1.0 which you can download <a href="http://code.google.com/p/linfu/downloads/list">here</a>. For some reason this class hasn’t been included in the 2.0 release and higher which is a bit sad because I really like some of the possibilities it has to offer. I’ll cover some of these in one of my next posts.</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/03/26/dont-give-up-on-the-state-pattern-just-yet-revisited/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Don&#8217;t Give Up on the State Pattern Just Yet</title>
		<link>http://elegantcode.com/2010/03/19/dont-give-up-on-the-state-pattern-just-yet/</link>
		<comments>http://elegantcode.com/2010/03/19/dont-give-up-on-the-state-pattern-just-yet/#comments</comments>
		<pubDate>Sat, 20 Mar 2010 00:02:29 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/03/19/dont-give-up-on-the-state-pattern-just-yet/</guid>
		<description><![CDATA[Last week, Greg Young wrote a blog post about State Pattern Misuse. In this post he talks about how ugly the State pattern can become if some operations are not allowed when the context object is in a particular state. The solution he proposes is to use a separate domain class for each state in [...]]]></description>
			<content:encoded><![CDATA[<p>Last week, <a href="http://codebetter.com/blogs/gregyoung/">Greg Young</a> wrote a blog post about <a href="http://codebetter.com/blogs/gregyoung/archive/2010/03/09/state-pattern-misuse.aspx">State Pattern Misuse</a>. In this post he talks about how ugly the <a href="http://en.wikipedia.org/wiki/State_pattern">State pattern</a> can become if some operations are not allowed when the context object is in a particular state. The solution he proposes is to use a separate domain class for each state in the model so that it contributes to the Ubiquitous Language. </p>
<p>Just to be clear, I agree and value this approach when it makes sense in the domain model. However, I do not like to entirely give up on the use of the State pattern either. We can eliminate some of the friction by using a very simple approach, namely <a href="http://martinfowler.com/bliki/RoleInterface.html">role interfaces</a>.</p>
<p>To show you a simple example, I took the code of one of the samples on the <a href="http://www.dofactory.com/Patterns/PatternState.aspx">DoFactory web site</a> and put in some refactoring. Please take a look at the original code before reading any further.</p>
<p>Now instead of having abstract methods on the <em>State</em> base class, I created three separate role interfaces:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">interface</span> ICanDeposit
{
    <span class="kwrd">void</span> Deposit(Double amount);
}

<span class="kwrd">public</span> <span class="kwrd">interface</span> ICanWithdraw
{
    <span class="kwrd">void</span> Withdraw(Double amount);
}

<span class="kwrd">public</span> <span class="kwrd">interface</span> ICanPayInterest
{
    <span class="kwrd">void</span> PayInterest();
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>&#160;</p>
<p>Both the <em>SilverState</em> and the <em>GoldState</em> class implement all these interfaces, but the one we’re particularly interested in is the <em>RedState</em> class because only deposits should be allowed for this state.</p>
<pre class="csharpcode"><span class="kwrd">class</span> RedState : State, ICanDeposit
{
    <span class="kwrd">private</span> <span class="kwrd">const</span> Double UpperLimit = 0.0;

    <span class="kwrd">public</span> RedState(State state)
    {
        Balance = state.Balance;
        Account = state.Account;
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> Deposit(<span class="kwrd">double</span> amount)
    {
        Balance += amount;
        StateChangeCheck();
    }

    <span class="kwrd">private</span> <span class="kwrd">void</span> StateChangeCheck()
    {
        <span class="kwrd">if</span>(Balance &gt; UpperLimit)
            Account.State = <span class="kwrd">new</span> SilverState(<span class="kwrd">this</span>);
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>&#160;</p>
<p>The RedState therefore only implements the <em>ICanDeposit</em> interface. Just for the record, the code of the <em>State</em> base class is now dramatically reduced.</p>
<pre class="csharpcode"><span class="kwrd">abstract</span> <span class="kwrd">class</span> State
{
    <span class="kwrd">public</span> Account Account { get; <span class="kwrd">protected</span> set; }
    <span class="kwrd">public</span> Double Balance { get; <span class="kwrd">protected</span> set; }
}</pre>
<p>&#160;</p>
<p>With this setup we can use these role interfaces in the <em>Account</em> class to determine whether a particular operation is allowed for the current state.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> Withdraw(<span class="kwrd">double</span> amount)
{
    <span class="rem">// One can not always withdraw</span>
    <span class="kwrd">if</span>(<span class="kwrd">false</span> == CanWithdraw())
    {
        <span class="rem">// Should throw an exception or at least a towel</span>
        Console.WriteLine(<span class="str">&quot;No funds available for withdrawal!&quot;</span>);
        <span class="kwrd">return</span>;
    }

    var canWithdraw = (ICanWithdraw)State;
    canWithdraw.Withdraw(amount);

    ...
}

<span class="kwrd">private</span> Boolean CanWithdraw()
{
    <span class="kwrd">return</span> State <span class="kwrd">is</span> ICanWithdraw;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>&#160;</p>
<p>This way we’re able to eliminate all operations that don’t make sense for a particular state while still being able to determine all of its capabilities when needed. </p>
<p>Hope this helps.</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/03/19/dont-give-up-on-the-state-pattern-just-yet/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Behaviors with MSpec</title>
		<link>http://elegantcode.com/2010/02/26/behaviors-with-mspec/</link>
		<comments>http://elegantcode.com/2010/02/26/behaviors-with-mspec/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 23:33:28 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/26/behaviors-with-mspec/</guid>
		<description><![CDATA[In my previous posts, I showed the syntax for context/specifications using Machine.Specifications (or MSpec for short) and how to use an auto mocking container in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called behaviors.
Suppose we have to create some [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous posts, I showed the <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">syntax for context/specifications</a> using <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and <a href="http://elegantcode.com/2010/02/23/mspec-and-auto-mocking">how to use an auto mocking container</a> in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called <em>behaviors</em>.</p>
<p>Suppose we have to create some sort of specification that validates the format of an e-mail address. We typically use some regular expression in order to ensure that a specified e-mail address is properly formatted.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> EmailSpecification
{
    <span class="kwrd">private</span> <span class="kwrd">const</span> String EmailRegexPattern = <span class="str">@&quot;.. SOME_REGEX_PATTERN ...&quot;</span>;

    <span class="kwrd">public</span> Boolean IsSatisfiedBy(String candidate)
    {
        var regex = <span class="kwrd">new</span> Regex(EmailRegexPattern);
        <span class="kwrd">return</span> regex.IsMatch(candidate);
    }
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>&#160;</p>
<p>I guess this is pretty common and straightforward. One way to provide some unit tests for this particular piece of code is to check a whole number of e-mail addresses that either pass or fail the specification. The following example shows only a couple of scenarios:</p>
<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one2@three.com&quot;</span>));
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one@two3.com&quot;</span>));
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two.com&quot;</span>), Is.False);
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two@&quot;</span>), Is.False);
    }
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>&#160;</p>
<p>A slightly more concise approach for these kind of unit tests can be accomplished by utilizing a feature of any decent unit test framework called <em>row tests. </em>With this approach we can, at the very least, reduce the number of asserts we have to write for each unit test.<em>&#160;</em></p>
<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email__approach_2
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [RowTest]
    [Row(<span class="str">&quot;one2@three.com&quot;</span>)]
    [Row(<span class="str">&quot;one@two3.com&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email));
    }

    [RowTest]
    [Row(<span class="str">&quot;one_two.com&quot;</span>)]
    [Row(<span class="str">&quot;one_two@&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email), Is.False);
    }
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>&#160;</p>
<p>Notice that I explicitly called both of these approaches <em>unit tests</em> as they don’t have much to do with BDD in my opinion. I’m not saying that using regular unit tests is a bad thing, but with&#160; behavior-driven development context is king. So these unit tests are perfect examples of ‘<a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">context betrayal</a>’ when following the BDD approach. </p>
<p>Lets see what MSpec can bring to the table for these kind of scenarios:</p>
<pre class="csharpcode">[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_local_part
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one2@three.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_domain_name
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one@two3.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_an_At_sign
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two.com&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_a_domain
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two@&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>&#160;</p>
<p>In order to escape ‘context betrayal’, we’ve split up every context into a separate context/specification. In order to reduce the amount of effort caused by duplicate code, we stripped the context setup to the bare minimum (just a particular e-mail address in this case). The observations are isolated into MSpec behaviors which provides a very readable description of their outcome. Lets take a look at what is needed in order to get these <em>behaviors</em> to work.</p>
<p>But first lets take at look at the abstract base class that we’ve used for the context/specifications we’ve just shown.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> email_specification_specs
{
    Establish context = () =&gt;
    {
        SUT = <span class="kwrd">new</span> EmailSpecification();
    };

    Because of = () =&gt;
        Result = SUT.IsSatisfiedBy(EmailAddress);

    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> String EmailAddress { get; set; }
    <span class="kwrd">protected</span> <span class="kwrd">static</span> EmailSpecification SUT { get; set; }
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</p>
<p>&#160;</p>
<p>We abstracted as much as possible into this base class in order to remove duplication in the context/specifications. The creation of the subject-under-test and the calling of its <em>IsSatisfiedBy</em> method, but the important one is the declaration of the <em>Result</em> field. This field contains the outcome of the <em>IsSatisfiedBy</em> method. Finally, lets have a look at the behaviors themselves:</p>
<pre class="csharpcode">[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> SatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;

    It should_satisfy_the_specification = () =&gt;
        Result.ShouldBeTrue();
}

[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> UnsatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;

    It should_not_satisfy_the_specification = () =&gt;
        Result.ShouldBeFalse();
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>&#160;</p>
<p>In order to create an MSpec behavior, we just have to create a separate class that we decorate with the <em>Behaviors</em> attribute. Also notice that we have the same declaration of the <em>Result</em> field. MSpec ensures that this field gets initialized with the value of the other <em>Result</em> field that is set in the base class of the context/specifications. Note that you don’t necessarily need to put this field in a base class. You can have that field in every context/specification if you’d like (not sure why) as long as the names match with the fields used in the defined behaviors.</p>
<p>I personally like the way how the MSpec contributors tried to solve testing the same logic with different input patterns and the syntax they provided to back this up.&#160;&#160; </p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/26/behaviors-with-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
