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

<channel>
	<title>Headspring &#187; Patrick Lioi</title>
	<atom:link href="http://www.headspring.com/author/plioi/feed" rel="self" type="application/rss+xml" />
	<link>http://www.headspring.com</link>
	<description>Custom software... Done right the first time.</description>
	<lastBuildDate>Wed, 16 May 2012 18:27:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2</generator>
	<copyright>Copyright © Headspring 2012 </copyright>
	<managingEditor>marketing@headspring.com (Jeffrey Palermo and Kevin Hurwitz)</managingEditor>
	<webMaster>marketing@headspring.com (Jeffrey Palermo and Kevin Hurwitz)</webMaster>
	<ttl>1440</ttl>
	<image>
		<url>http://www.headspring.com/wp-content/uploads/2012/05/HeadspringFlair144.jpg</url>
		<title>Headspring</title>
		<link>http://www.headspring.com</link>
		<width>144</width>
		<height>144</height>
	</image>
	<itunes:subtitle>We believe there is a better way</itunes:subtitle>
	<itunes:summary>Are you a lifelong learner?  Are you always searching for better ways to develop and maintain software?  So are we!  A passion for learning and growth is a core value at Headspring.  In this podcast, Headspring consultants, programmers, software developers, managers, and executives share the skills, techniques, patterns, and tools that have proven effective on clients&#039; consulting projects.  Headspring is a software consulting company in Austin, TX and has been recognized on the Inc 500 list and the Austin Business Journal&#039;s Best Place to Work award.</itunes:summary>
	<itunes:keywords>headspring, software, line, business, enterprise, applications, custom, MVC, Net, C, database, SQL</itunes:keywords>
	<itunes:category text="Technology" />
	<itunes:category text="Business" />
	<itunes:category text="Education">
		<itunes:category text="Training" />
	</itunes:category>
	<itunes:author>Jeffrey Palermo and Kevin Hurwitz</itunes:author>
	<itunes:owner>
		<itunes:name>Jeffrey Palermo and Kevin Hurwitz</itunes:name>
		<itunes:email>marketing@headspring.com</itunes:email>
	</itunes:owner>
	<itunes:block>no</itunes:block>
	<itunes:explicit>no</itunes:explicit>
	<itunes:image href="http://www.headspring.com/wp-content/uploads/2012/05/HeadspringFlair600.jpg" />
		<item>
		<title>Dependency Injection Ceremony</title>
		<link>http://www.headspring.com/2012/05/dependency-injection-ceremony</link>
		<comments>http://www.headspring.com/2012/05/dependency-injection-ceremony#comments</comments>
		<pubDate>Fri, 11 May 2012 18:39:45 +0000</pubDate>
		<dc:creator>Patrick Lioi</dc:creator>
				<category><![CDATA[Developer Deep Dive]]></category>

		<guid isPermaLink="false">http://www.headspring.com/?p=5109</guid>
		<description><![CDATA[The vast majority of the time, I enjoy working with dependency injection. ...]]></description>
			<content:encoded><![CDATA[<p>The vast majority of the time, I enjoy working with <a href="http://en.wikipedia.org/wiki/Dependency_injection">dependency injection</a>.  Sometimes, however, I find myself rolling my eyes at the amount of &#8220;ceremony&#8221; boilerplate code it takes in order to take advantage of it.  <em>Disclaimer: This is more a limitation of C# having been created before DI containers became common than a problem with DI itself.</em><br />
<span id="more-5109"></span></p>
<p>DI and its benefits have been written about for years, but the short version is that your classes can accept interface arguments through their constructors, and these arguments represent the class&#8217;s dependencies.  A simple example can be seen in the <a href="https://github.com/DarthFubuMVC/fubumvc-examples/blob/master/src/Actions/HandlerStyle/SimpleWebsite/Handlers/Movies/ListHandler.cs">FubuMVC samples</a>:</p>
<div id="gist-2641353" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">public</span> <span class="k">class</span> <span class="nc">ListHandler</span></div><div class='line' id='LC2'><span class="p">{</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">private</span> <span class="k">readonly</span> <span class="n">IRepository</span> <span class="n">_repository</span><span class="p">;</span></div><div class='line' id='LC4'><br/></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">public</span> <span class="nf">ListHandler</span><span class="p">(</span><span class="n">IRepository</span> <span class="n">repository</span><span class="p">)</span></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">_repository</span> <span class="p">=</span> <span class="n">repository</span><span class="p">;</span></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC9'><br/></div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">public</span> <span class="n">ListMoviesViewModel</span> <span class="nf">Execute</span><span class="p">()</span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span></div><div class='line' id='LC12'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="k">new</span> <span class="n">ListMoviesViewModel</span> <span class="p">{</span> <span class="n">Movies</span> <span class="p">=</span> <span class="n">_repository</span><span class="p">.</span><span class="n">Query</span><span class="p">&lt;</span><span class="n">Movie</span><span class="p">&gt;()</span> <span class="p">};</span></div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC14'><span class="p">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/2641353/619063b0d1c536543953bfc6664803d6d5aab044/ListHandler.cs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/2641353#file_list_handler.cs" style="float:right;margin-right:10px;color:#666">ListHandler.cs</a>
            <a href="https://gist.github.com/2641353">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>Here, the ListHandler class is declaring, incidentally to the compiler but primarily to the <em>reader</em>, that it depends on a repository to do its work.  Rather than construct a <code>new Repository()</code> itself, it assumes a pre-constructed <code>IRepository</code> will be provided.</p>
<p>At a minimum, this is convenient in the case that the <code>Repository</code> constructor itself has potentially-tricky-to-instantiate arguments, each of which may have their own constructors to call, ad nauseum.</p>
<p>More importantly, since your class no longer has to &#8216;new up&#8217; the dependencies itself, it is decoupled from the concrete implementations of those dependencies.  At test time, you can pass in a mock or stub implementation to prove that your class makes use of the abstraction as expected, and at run time you can trust a tool like <a href="http://docs.structuremap.net/">StructureMap</a> to create and pass in the real implementation.  When looking at a class written in this style, you can quickly see what it depends on by looking at its constructor, rather than looking through the entire class definition.</p>
<h2>Playing Devil&#8217;s Advocate</h2>
<p>The ListHandler class is easy to read, easy to understand, so easy to test that it might not be worth the bother, and it absolutely follows the Single Responsibility Principle.  It&#8217;s simple, basically the &#8220;Hello, World!&#8221; of Dependency Injection, but simple is a good thing to shoot for whenever we put our hands on a keyboard.  It&#8217;s a Good Class.</p>
<p>However, when I find myself writing similar single-responsibility classes with a dependency or two passed to the constructor, a little imaginary Devil pops up on my left shoulder, accompanied by his Angel twin on my right.  The Devil wispers, &#8220;Why in the <em>heck</em> are you writing all that boilerplate!?&#8221; and the little Angel looks at the class and says, &#8220;Yeah, I hate to say this, but I think you should be listening to <em>that</em> guy.&#8221;</p>
<p>What does this class tell the reader?  First, it says &#8220;I depend on a repository.&#8221;  Then it says &#8220;And when I say repository, I mean repository.&#8221;  Followed by &#8220;No, seriously dude, we&#8217;re talking about a repository here.&#8221;  When we inject an interface like this, we pay the syntax tax by saying &#8216;repository&#8217; <strong>six times in a row</strong>.  12 lines so that we could say the 1 line that we actually wanted to say.</p>
<p>Of course, this is not a problem with DI itself.  This is a problem of the language not knowing DI would be so prevalent.  What we really want, in these single-method dependency-injected classes, is effectively a global function, with some arguments specially-marked as dependencies.  Consider a hypothetical C# from the future:</p>
<div id="gist-2641473" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">public</span> <span class="n">ListMoviesViewModel</span> <span class="nf">ListHandler</span><span class="p">(</span><span class="n">inject</span> <span class="n">IRepository</span> <span class="n">repository</span><span class="p">)</span></div><div class='line' id='LC2'><span class="p">{</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="k">new</span> <span class="n">ListMoviesViewModel</span> <span class="p">{</span> <span class="n">Movies</span> <span class="p">=</span> <span class="n">_repository</span><span class="p">.</span><span class="n">Query</span><span class="p">&lt;</span><span class="n">Movie</span><span class="p">&gt;()</span> <span class="p">};</span></div><div class='line' id='LC4'><span class="p">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/2641473/894bc1dae035cbf0ab9540577d21336cd3dd930d/InjectableFunction.cs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/2641473#file_injectable_function.cs" style="float:right;margin-right:10px;color:#666">InjectableFunction.cs</a>
            <a href="https://gist.github.com/2641473">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>Such a function, if it could be declared, could be called with zero arguments when we want a real IRepository injected, and could be passed an IRepository at test time.  What do you think?  Would this kind of language support be useful in practice?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.headspring.com/2012/05/dependency-injection-ceremony/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Delegate Frustration</title>
		<link>http://www.headspring.com/2012/05/delegate-frustration</link>
		<comments>http://www.headspring.com/2012/05/delegate-frustration#comments</comments>
		<pubDate>Fri, 04 May 2012 14:57:01 +0000</pubDate>
		<dc:creator>Patrick Lioi</dc:creator>
				<category><![CDATA[Developer Deep Dive]]></category>

		<guid isPermaLink="false">http://www.headspring.com/?p=5065</guid>
		<description><![CDATA[One of the things I like about C#&#8217;s delegate types, compared to ...]]></description>
			<content:encoded><![CDATA[<p>One of the things I like about C#&#8217;s delegate types, compared to similar concepts in other languages, is that C#&#8217;s take on the concept lets you give a useful <em>name</em> to a family of functions:</p>
<div id="gist-2582885" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">public</span> <span class="k">delegate</span> <span class="n">TResult</span> <span class="n">Converter</span><span class="p">&lt;</span><span class="n">T</span><span class="p">,</span> <span class="n">TResult</span><span class="p">&gt;(</span><span class="n">T</span> <span class="n">input</span><span class="p">);</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/2582885/f1c5b3acd5a2f4071d6e1413a2de180a465ae53d/Converter.cs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/2582885#file_converter.cs" style="float:right;margin-right:10px;color:#666">Converter.cs</a>
            <a href="https://gist.github.com/2582885">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>With this definition, all functions that turn one thing into another thing are Converters.  Nice.</p>
<p>We also have some generically-named <code>Action&lt;…&gt;</code> and <code>Func&lt;…&gt;</code> delegate types defined for us, and these have become ubiquitous ever since LINQ was introduced.  They&#8217;re not as communicative, but still extremely useful, and for the most part the naming stays out of the way.</p>
<p>Delegate types allow you to give a name to a family of functions.  However, you can run into trouble when you use two different names to refer to the <em>same</em> family of functions:</p>
<p><span id="more-5065"></span></p>
<div id="gist-2582784" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">public</span> <span class="kt">string</span> <span class="nf">Stringify</span><span class="p">(</span><span class="kt">int</span> <span class="n">x</span><span class="p">)</span></div><div class='line' id='LC2'><span class="p">{</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="n">x</span><span class="p">.</span><span class="n">ToString</span><span class="p">();</span></div><div class='line' id='LC4'><span class="p">}</span></div><div class='line' id='LC5'><br/></div><div class='line' id='LC6'><br/></div><div class='line' id='LC7'><span class="c1">//Later...</span></div><div class='line' id='LC8'><br/></div><div class='line' id='LC9'><span class="n">Func</span><span class="p">&lt;</span><span class="kt">int</span><span class="p">,</span> <span class="kt">string</span><span class="p">&gt;</span> <span class="n">func</span> <span class="p">=</span> <span class="n">Stringify</span><span class="p">;</span></div><div class='line' id='LC10'><span class="n">Converter</span><span class="p">&lt;</span><span class="kt">int</span><span class="p">,</span> <span class="kt">string</span><span class="p">&gt;</span> <span class="n">convert</span> <span class="p">=</span> <span class="n">Stringify</span><span class="p">;</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/2582784/2d663d46e880cf458ed746c84e343ee788b02955/Stringify.cs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/2582784#file_stringify.cs" style="float:right;margin-right:10px;color:#666">Stringify.cs</a>
            <a href="https://gist.github.com/2582784">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>Since all methods are compatable with any delegate type that has matching input/output types, why aren&#8217;t the following queries equivalent?</p>
<div id="gist-2582790" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="kt">int</span><span class="p">[]</span> <span class="n">integers</span> <span class="p">=</span> <span class="k">new</span><span class="p">[]</span> <span class="p">{</span><span class="m">1</span><span class="p">,</span> <span class="m">2</span><span class="p">,</span> <span class="m">3</span><span class="p">};</span></div><div class='line' id='LC2'><br/></div><div class='line' id='LC3'><span class="n">integers</span><span class="p">.</span><span class="n">Select</span><span class="p">(</span><span class="n">func</span><span class="p">);</span> <span class="c1">// returns &quot;1&quot;, &quot;2&quot;, &quot;3&quot;</span></div><div class='line' id='LC4'><span class="n">integers</span><span class="p">.</span><span class="n">Select</span><span class="p">(</span><span class="n">convert</span><span class="p">);</span> <span class="c1">// fails to compile!</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/2582790/ddc0e0334005f38197ce8788cfef20da4a1d300d/Select.cs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/2582790#file_select.cs" style="float:right;margin-right:10px;color:#666">Select.cs</a>
            <a href="https://gist.github.com/2582790">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>This was a little frustrating when C# 3 came out.  Before then, all the delegate types we were used to working with had explicit names like <code>Converter</code> and <code>Predicate</code>.  When C# 3 introduced lambdas and LINQ, we gained <code>Func&lt;…&gt;</code> and <code>Action&lt;…&gt;</code>, and I found myself stumbling while converting older code to use the new LINQ extension methods like <code>Select</code>, which takes a <code>Func&lt;T, TResult&gt;</code>.</p>
<p>It&#8217;s extra-frustrating because <em>every single Converter&lt;T, TResult> method that ever lived is also a Func&lt;T, TResult>!</em> I know it, you know it, Grandma tweeted it.  We can drive that point home by making the <code>convert</code> delegate work with <code>Select</code> by wrapping it in a trivial do-nothing lambda: <code>integers.Select(x =&gt; convert(x));</code>  Yeesh!</p>
<p>To help make sense of this behavior, we can make an analogy between delegates and interfaces.</p>
<p>Think of a delegate <em>type</em> as a special kind of interface type.  The interface has only one method, called &#8220;Call&#8221;.  Since it is <em>always</em> called &#8220;Call&#8221;, you can shorten the reader-unfriendly <code>convert.Call(5)</code> to simply <code>convert(5)</code>.</p>
<p>Think of a method as an <em>instance</em> of these interfaces.  All methods implement the infinite number of possible delegate &#8216;interfaces&#8217; that match their input and output types.  <code>Stringify</code> is an object that implements the imaginary <code>IConverter&lt;int, string&gt;</code> interface, and also implements the imaginary <code>IFunc&lt;int, string&gt;</code> interface.  Both of these interfaces just happen to contain the imaginary method with the signature: <code>string Call(int x)</code>.</p>
<p>Now, the example above makes more sense.  We have two variables declared as &#8216;interface&#8217; types, and assign the same object to both variables.  <code>Select</code> is written to accept instances of one &#8216;interface&#8217; type, and although <code>convert</code> points at a method compatable with <code>Select</code>, <code>convert</code> itself can only be seen as having some other, incompatible type.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.headspring.com/2012/05/delegate-frustration/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Architecture Resists Change</title>
		<link>http://www.headspring.com/2012/04/architecture-resists-change</link>
		<comments>http://www.headspring.com/2012/04/architecture-resists-change#comments</comments>
		<pubDate>Fri, 27 Apr 2012 18:11:49 +0000</pubDate>
		<dc:creator>Patrick Lioi</dc:creator>
				<category><![CDATA[Developer Deep Dive]]></category>

		<guid isPermaLink="false">http://www.headspring.com/?p=5023</guid>
		<description><![CDATA[In a conversation about large software projects, the word &#8220;architecture&#8221; is bound ...]]></description>
			<content:encoded><![CDATA[<p>In a conversation about large software projects, the word &#8220;architecture&#8221; is bound to come up sooner or later.  Most programmers have a gut feeling for what this really means with regard to software, but if you asked 10 programmers to define it, you&#8217;d get 10 different answers.</p>
<p>In <a href="http://martinfowler.com/ieeeSoftware/whoNeedsArchitect.pdf">Who Needs an Architect?</a>, Martin Fowler covers a few definitions which he ultimately boils down to one simple concept: <strong>architecture is the decisions that are hard to change.</strong></p>
<p><span id="more-5023"></span></p>
<p>Depending on the tone you use when reading that definition, it&#8217;s almost a <em>pejorative</em>.  Joel Spolsky even warned us of <a href="http://www.joelonsoftware.com/articles/fog0000000018.html">Architecture Astronauts</a>, people who effectively over-engineer and abstract things to the point that they&#8217;re no longer solving real problems.</p>
<p>Yes, <strong>an</strong> architecture can be bad.  If the decisions that are hard to change form obstacles between you and the true goal of your project, you&#8217;ve got a bad architecture.  On the other hand, some decisions that are hard to change may be a driving force for your success.  It&#8217;s just important to be aware of which decisions form your architecture as you make them.</p>
<h2>Example: The Onion Architecture</h2>
<p>With the <a href="http://www.headspring.com/2012/03/onion-architecture-part-4-after-four-years">Onion Architecture</a>, the hard-to-change decision is to define realtively-unstable infrastructure on the outside, depending on a core application that is ignorant of infrastructure details like persistence.</p>
<p>This decision is hard to change, but it is justified.  As Jeffrey Palermo said during a presentation on the O.A., an assembly is only as stable as its least-stable dependency.  Therefore, for an application to stand the test of time, we need to maximize the stable portion and minimize our dependency on things that are too likely to change.  If your app integrates with Twitter today, it likely won&#8217;t in 5 years after Twitter goes the way of the blue Dodo bird, so you are better off defining your Twitter integration outside of the core assembly, dependent on the core assembly rather than the other way around.</p>
<h2>Example: Parsley</h2>
<p>A few months back I described a hobby project to illustrate <a href="http://www.headspring.com/2011/11/recognizing-covariance-issues-in-your-code">covariance issues</a>.  This project lets you parse text by describing what a valid input looks like (similar to regular expressions).  There were two key decisions that would be impossible to change without starting from scratch:</p>
<blockquote>
<p>First, the user would describe what a valid input looks like by gluing together tiny <a href="http://domaindrivendesign.org/node/127">side-effect-free</a> functions.<br />
  Second, I would use read-only data structures to represent progress through the input.</p>
</blockquote>
<p>These two decisions are made frequently when using functional languages, but not so much in C# projects.  Despite being unusual, I found these decisions to be extremely helpful for this kind of problem, regardless of the language used to implement it.</p>
<p>The samples contain a <a href="https://github.com/plioi/parsley/blob/0b0b1cdddab040c1513344f3b768a8c348bed138/src/Parsley.Test/IntegrationTests/Json/JsonGrammar.cs">JSON parser</a>, which amounts to describing what valid JSON looks like.  The bulk of the description is summed up in a few lines:</p>
<div id="gist-2495421" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="n">Json</span><span class="p">.</span><span class="n">Rule</span> <span class="p">=</span></div><div class='line' id='LC2'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">Choice</span><span class="p">(</span><span class="n">True</span><span class="p">,</span> <span class="n">False</span><span class="p">,</span> <span class="n">Null</span><span class="p">,</span> <span class="n">Number</span><span class="p">,</span> <span class="n">Quotation</span><span class="p">,</span> <span class="n">Dictionary</span><span class="p">,</span> <span class="n">Array</span><span class="p">);</span></div><div class='line' id='LC3'><br/></div><div class='line' id='LC4'><span class="n">Dictionary</span><span class="p">.</span><span class="n">Rule</span> <span class="p">=</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">from</span> <span class="n">pairs</span> <span class="k">in</span> <span class="nf">Between</span><span class="p">(</span><span class="n">Token</span><span class="p">(</span><span class="s">&quot;{&quot;</span><span class="p">),</span> <span class="n">ZeroOrMore</span><span class="p">(</span><span class="n">Pair</span><span class="p">,</span> <span class="n">Token</span><span class="p">(</span><span class="s">&quot;,&quot;</span><span class="p">)),</span> <span class="n">Token</span><span class="p">(</span><span class="s">&quot;}&quot;</span><span class="p">))</span></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">select</span> <span class="nf">ToDictionary</span><span class="p">(</span><span class="n">pairs</span><span class="p">);</span></div><div class='line' id='LC7'><br/></div><div class='line' id='LC8'><span class="n">Pair</span><span class="p">.</span><span class="n">Rule</span> <span class="p">=</span></div><div class='line' id='LC9'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">from</span> <span class="n">key</span> <span class="k">in</span> <span class="n">Quotation</span></div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">from</span> <span class="n">colon</span> <span class="k">in</span> <span class="nf">Token</span><span class="p">(</span><span class="s">&quot;:&quot;</span><span class="p">)</span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">from</span> <span class="k">value</span> <span class="k">in</span> <span class="n">Json</span></div><div class='line' id='LC12'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">select</span> <span class="k">new</span> <span class="n">KeyValuePair</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">,</span> <span class="kt">object</span><span class="p">&gt;(</span><span class="n">key</span><span class="p">,</span> <span class="k">value</span><span class="p">);</span></div><div class='line' id='LC13'><br/></div><div class='line' id='LC14'><span class="n">Array</span><span class="p">.</span><span class="n">Rule</span> <span class="p">=</span></div><div class='line' id='LC15'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">from</span> <span class="n">items</span> <span class="k">in</span> <span class="nf">Between</span><span class="p">(</span><span class="n">Token</span><span class="p">(</span><span class="s">&quot;[&quot;</span><span class="p">),</span> <span class="n">ZeroOrMore</span><span class="p">(</span><span class="n">Json</span><span class="p">,</span> <span class="n">Token</span><span class="p">(</span><span class="s">&quot;,&quot;</span><span class="p">)),</span> <span class="n">Token</span><span class="p">(</span><span class="s">&quot;]&quot;</span><span class="p">))</span></div><div class='line' id='LC16'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">select</span> <span class="n">items</span><span class="p">.</span><span class="n">ToArray</span><span class="p">();</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/2495421/b7824133307f751412fd346d1d2610c5c162fc21/Json.cs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/2495421#file_json.cs" style="float:right;margin-right:10px;color:#666">Json.cs</a>
            <a href="https://gist.github.com/2495421">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>Because of the two architectural decisions, all the details about tracking progress, success, and failure can be completely hidden.  The user can solve the task at hand by describing the task at hand, and the architectural decisions enable that ability.</p>
<h2>Making Your Own Decisions</h2>
<p>As you make a decision that affects your project&#8217;s structure, ask yourself, &#8220;Is this a part of our architecture?  Is it going to be hard to change later if we go forward with it?  If so, does it <em>earn the right</em> to be included anyway?&#8221;  If not, try to restructure it so that it <em>is</em> easy to change, or consider chucking it entirely.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.headspring.com/2012/04/architecture-resists-change/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>From WebForms to MVC</title>
		<link>http://www.headspring.com/2012/04/from-webforms-to-mvc</link>
		<comments>http://www.headspring.com/2012/04/from-webforms-to-mvc#comments</comments>
		<pubDate>Fri, 20 Apr 2012 16:25:49 +0000</pubDate>
		<dc:creator>Patrick Lioi</dc:creator>
				<category><![CDATA[Developer Deep Dive]]></category>

		<guid isPermaLink="false">http://www.headspring.com/?p=4855</guid>
		<description><![CDATA[Most of my first job out of college was spent doing desktop ...]]></description>
			<content:encoded><![CDATA[<p>Most of my first job out of college was spent doing desktop development, some of which was in VB6.  I didn&#8217;t love it, but it was easy to learn.  When <em>this</em> button is clicked, <em>that</em> function runs in response to it.  Easy.</p>
<p>The controls-and-event-handlers model combined with the language also made it exceptionally easy to create a tangled pile of misplaced responsibilities, but I think you&#8217;ve got to experience that kind of pain before you can see that alternatives even <em>exist</em>.  Once you&#8217;ve felt the pain, you can better-evaluate which guidance is actually going to be helpful.<br />
<span id="more-4855"></span></p>
<h2>WebForms Was Designed for Desktop Developers</h2>
<p>Right around that time, .NET was released.  ASP.NET WebForms shared little with classic ASP.  The primary goal was to let desktop VB developers make a smooth transition to both .NET and web development at the same time.  With that goal in mind, WebForms provided a similar controls-and-event-handlers model.  Making a web app felt like making a desktop app.</p>
<p>In order to support that approach, WebForms had to make the stateless world of HTTP <em>feel</em> stateful.  View State, the Page Life Cycle, and event handlers allowed the developer to go through the familiar motions of dropping controls onto a designer and wiring up methods to control events, <em>all while ignoring everything that was actually happening</em>.</p>
<p>Abstractions leak, though, and this was a <em>huge</em> abstraction.  It helped me get over the initial hurdle to get a web app up and running, but I found the code I wrote was suspiciously like the desktop VB6 mess I&#8217;d wanted to grow beyond.  I was frequently surprised by the effects of the Page Life Cycle, and every time that happened I had to learn a little bit more about how the abstraction worked under the hood:</p>
<blockquote><p>
  &#8220;Oh! There&#8217;s a Big Honking &lt;form&gt; Tag for the whole page, and it contains an Enormous Encoded &lt;input&gt; Tag containing the current state of all the controls, so whenever I need to hit a button click handler I&#8217;m really submitting a normal HTML form and then…&#8221;
</p></blockquote>
<p>Ugh. Eventually, you just have to know what HTML and HTTP are, even when using WebForms, so the abstraction was no longer helping.</p>
<h2>Many Page Life Cycles Later&#8230;</h2>
<p>While working for a previous employer, ASP.NET MVC came out.  We wanted to try out the new approach, and the timing coincided with a new project that was starting up.  However, there wasn&#8217;t much guidance available yet on how to do it <em>well</em>.  We were challenged at first by the lack of View State, and in order to keep our old &#8220;stateful stateless web&#8221; habit going we ended up storing a <em>lot</em> of things into the user&#8217;s session object.  We also kept treating controller actions like they were event handlers, leading to some awkward-looking URLs.  Distracted by these initial pains, our controllers started absorbing responsibilities like a sponge.  Actually, our <em>controller</em> started absorbing responsibilities &#8211; there was only controller in the whole app!</p>
<p>I was writing a lot of controller actions like this:</p>
<div id="gist-2410072" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">public</span> <span class="n">ActionResult</span> <span class="nf">Edit</span><span class="p">()</span></div><div class='line' id='LC2'><span class="p">{</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kt">var</span> <span class="n">conferenceName</span> <span class="p">=</span> <span class="n">Request</span><span class="p">[</span><span class="s">&quot;ConferenceName&quot;</span><span class="p">]</span> <span class="k">as</span> <span class="kt">string</span><span class="p">;</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kt">var</span> <span class="n">repository</span> <span class="p">=</span> <span class="k">new</span> <span class="n">ConferenceRepository</span><span class="p">();</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kt">var</span> <span class="n">conference</span> <span class="p">=</span> <span class="n">repository</span><span class="p">.</span><span class="n">GetByName</span><span class="p">(</span><span class="n">conferenceName</span><span class="p">);</span></div><div class='line' id='LC6'><br/></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">if</span> <span class="p">(</span><span class="n">conference</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="nf">View</span><span class="p">(</span><span class="s">&quot;ConferenceNotFound&quot;</span><span class="p">);</span></div><div class='line' id='LC9'><br/></div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">ViewData</span><span class="p">[</span><span class="s">&quot;ConferenceId&quot;</span><span class="p">]</span> <span class="p">=</span> <span class="n">conference</span><span class="p">.</span><span class="n">Id</span><span class="p">,</span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">ViewData</span><span class="p">[</span><span class="s">&quot;ConferenceName&quot;</span><span class="p">]</span> <span class="p">=</span> <span class="n">conference</span><span class="p">.</span><span class="n">Name</span></div><div class='line' id='LC12'><br/></div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="nf">View</span><span class="p">();</span></div><div class='line' id='LC14'><span class="p">}</span></div><div class='line' id='LC15'><br/></div><div class='line' id='LC16'><span class="k">public</span> <span class="n">ActionResult</span> <span class="nf">Save</span><span class="p">()</span></div><div class='line' id='LC17'><span class="p">{</span></div><div class='line' id='LC18'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kt">var</span> <span class="n">conferenceName</span> <span class="p">=</span> <span class="n">Request</span><span class="p">[</span><span class="s">&quot;ConferenceName&quot;</span><span class="p">]</span> <span class="k">as</span> <span class="kt">string</span></div><div class='line' id='LC19'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">if</span> <span class="p">(</span><span class="kt">string</span><span class="p">.</span><span class="n">IsNullOrEmpty</span><span class="p">(</span><span class="n">conferenceName</span><span class="p">))</span></div><div class='line' id='LC20'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span></div><div class='line' id='LC21'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">ViewBag</span><span class="p">.</span><span class="n">ErrorMessage</span> <span class="p">=</span> <span class="s">&quot;Conference Name is required&quot;</span><span class="p">;</span></div><div class='line' id='LC22'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="nf">View</span><span class="p">(</span><span class="s">&quot;Edit&quot;</span><span class="p">);</span></div><div class='line' id='LC23'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC24'><br/></div><div class='line' id='LC25'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kt">var</span> <span class="n">repository</span> <span class="p">=</span> <span class="k">new</span> <span class="n">ConferenceRepository</span><span class="p">();</span></div><div class='line' id='LC26'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kt">var</span> <span class="n">conference</span> <span class="p">=</span> <span class="n">repository</span><span class="p">.</span><span class="n">GetById</span><span class="p">(</span><span class="k">new</span> <span class="n">Guid</span><span class="p">(</span><span class="n">Request</span><span class="p">[</span><span class="s">&quot;ConferenceId&quot;</span><span class="p">]</span> <span class="k">as</span> <span class="kt">string</span><span class="p">));</span></div><div class='line' id='LC27'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">conference</span><span class="p">.</span><span class="n">ChangeName</span><span class="p">(</span><span class="n">Request</span><span class="p">[</span><span class="s">&quot;ConferenceName&quot;</span><span class="p">]</span> <span class="k">as</span> <span class="kt">string</span><span class="p">);</span></div><div class='line' id='LC28'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">_repository</span><span class="p">.</span><span class="n">Save</span><span class="p">(</span><span class="n">conference</span><span class="p">);</span></div><div class='line' id='LC29'><br/></div><div class='line' id='LC30'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="nf">RedirectToRoute</span><span class="p">(</span><span class="s">&quot;Default&quot;</span><span class="p">,</span> <span class="k">new</span> <span class="p">{</span> <span class="n">action</span> <span class="p">=</span> <span class="s">&quot;Index&quot;</span><span class="p">});</span></div><div class='line' id='LC31'><span class="p">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/2410072/768775fc9c638f6b2e3f1658883f44c00fc4f626/Before.cs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/2410072#file_before.cs" style="float:right;margin-right:10px;color:#666">Before.cs</a>
            <a href="https://gist.github.com/2410072">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>What I saw was the same thing I saw in WebForms development.  The Controller was the new Code Behind, and I was underwhelmed.  WebForms&#8217;s Page Life Cycle and View State hurt, but the real daily pains came from working with classes that were growing out of control, and I was seeing the same thing with my MVC code.  It seemed like the abstractions were lighter-weight, and it felt right to work with HTML more directly, but I was definitely missing some guidance.</p>
<h2>Turning the Corner</h2>
<p>Several coworkers got to take an <a href="http://www.headspring.com/services/developer-training/mvc-bootcamp">MVC Boot Camp</a> course here at Headspring, and I got to learn by osmosis from them upon their return.  At last, I had a good picture in my head of what it looks like when you&#8217;ve succeeded with these tools.  Our controllers started to get much more lean:</p>
<div id="gist-2416902" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="na">[HttpGet]</span></div><div class='line' id='LC2'><span class="k">public</span> <span class="n">ActionResult</span> <span class="nf">Edit</span><span class="p">(</span><span class="n">Conference</span> <span class="n">conference</span><span class="p">)</span></div><div class='line' id='LC3'><span class="p">{</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="n">AutoMapView</span><span class="p">&lt;</span><span class="n">ConferenceEditModel</span><span class="p">&gt;(</span><span class="n">View</span><span class="p">(</span><span class="n">conference</span><span class="p">));</span></div><div class='line' id='LC5'><span class="p">}</span></div><div class='line' id='LC6'><br/></div><div class='line' id='LC7'><span class="na">[HttpPost]</span></div><div class='line' id='LC8'><span class="k">public</span> <span class="n">ActionResult</span> <span class="nf">Edit</span><span class="p">(</span><span class="n">ConferenceEditModel</span> <span class="n">form</span><span class="p">)</span></div><div class='line' id='LC9'><span class="p">{</span></div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">if</span> <span class="p">(!</span><span class="n">ViewData</span><span class="p">.</span><span class="n">ModelState</span><span class="p">.</span><span class="n">IsValid</span><span class="p">)</span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="nf">View</span><span class="p">(</span><span class="n">form</span><span class="p">);</span></div><div class='line' id='LC12'><br/></div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kt">var</span> <span class="n">conference</span> <span class="p">=</span> <span class="n">_repository</span><span class="p">.</span><span class="n">GetById</span><span class="p">(</span><span class="n">form</span><span class="p">.</span><span class="n">Id</span><span class="p">);</span></div><div class='line' id='LC14'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">conference</span><span class="p">.</span><span class="n">ChangeName</span><span class="p">(</span><span class="n">form</span><span class="p">.</span><span class="n">Name</span><span class="p">);</span></div><div class='line' id='LC15'><br/></div><div class='line' id='LC16'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="n">RedirectToAction</span><span class="p">&lt;</span><span class="n">DefaultController</span><span class="p">&gt;(</span><span class="n">c</span> <span class="p">=&gt;</span> <span class="n">c</span><span class="p">.</span><span class="n">Index</span><span class="p">());</span></div><div class='line' id='LC17'><span class="p">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/2416902/630923b811b8ff2fd2954d2004a8c297de418f1b/After.cs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/2416902#file_after.cs" style="float:right;margin-right:10px;color:#666">After.cs</a>
            <a href="https://gist.github.com/2416902">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>I started to see how the <a href="http://jeffreypalermo.com/blog/the-onion-architecture-part-1/">Onion Architecture</a>, dependency injection, model binders, AutoMapper, and the like help you to keep your controllers small.  MVC wasn&#8217;t a silver bullet; its primary benefit compared to WebForms was that you could make it <em>get out of the way</em> so you could actually start laying down a solid architecture.</p>
<p>ASP.NET MVC has been around for a few years now.  Community contributions like <a href="http://mvccontrib.codeplex.com/">MvcContrib</a> helped to motivate change in subsequent releases, and now ASP.NET MVC is legitimately open-sourced.  Better-yet, guidance on how to do this well has had years to mature.</p>
<p>MVC is a sharper tool than WebForms.  It acknowledges the reality of web technologies like HTML and HTTP, while providing some reasonably-sized abstractions on top of that, such as routing and model binding.  Having a better tool in your toolbelt isn&#8217;t enough, though.  You have to see what it looks like when used correctly.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.headspring.com/2012/04/from-webforms-to-mvc/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>NuGet Package Restore</title>
		<link>http://www.headspring.com/2012/04/nuget-package-restore</link>
		<comments>http://www.headspring.com/2012/04/nuget-package-restore#comments</comments>
		<pubDate>Fri, 13 Apr 2012 14:43:32 +0000</pubDate>
		<dc:creator>Patrick Lioi</dc:creator>
				<category><![CDATA[Developer Deep Dive]]></category>

		<guid isPermaLink="false">http://www.headspring.com/?p=4797</guid>
		<description><![CDATA[Text is easy. Source control tools slice and dice text all day. ...]]></description>
			<content:encoded><![CDATA[<p>Text is easy.</p>
<p>Source control tools slice and dice text all day.  It&#8217;s easy to compare, easy to merge, and easy to compress.  Even in a busy project, large portions of your code don&#8217;t really change all that often.  Git, for instance, can pretend to store every commit as a point-in-time copy of your whole source tree by <a href="http://progit.org/book/ch1-3.html">sharing large unchanged blobs</a> of text with other commits.</p>
<p>Text is easy.  Binary is tough.<span id="more-4797"></span></p>
<h2>Do you pass the &#8220;New Hire Day 1&#8243; test?</h2>
<p>We often store binaries in our source control tools, and with good reason.  We want to make it easy to spin up a new development environment.  When you hire a new developer, they should be able to pull down your project from source control <em>and just go</em>.  Dependencies such as libraries, build tools, and the like should be versioned with the project.</p>
<p>The alternative experience can be painful.  You show up for your first day at a new job, pull down the project, and try to run it… <strong>THUD</strong>.  It won&#8217;t even build.  You try to install the right third-party libraries and tools after diagnosing each build error, and hopefully you&#8217;re using the same version as everyone else.  Maybe the Dependency Gods smile upon you, and you&#8217;ll be up and running before the end of the day.</p>
<p>It&#8217;s easy to avoid these problems by including your dependencies, both libraries and tools, in source control, but can we do better?</p>
<h2>Binary is Tough</h2>
<p>You can store binaries in source control, but binaries are tough.  Even small changes in functionality can result in dramatically different file contents, so it&#8217;s impractical to diff/merge them.  Changes in a binary file over time have to be stored without the sneaky compression tricks used for text files.</p>
<p>NuGet makes it easy to install libraries into your projects, but this means dumping a whole lot of DLLs into source control.  <strong>Your repo might start to grow impractically large.</strong></p>
<h2>Package Restore</h2>
<p>Fortunately, though, we can have the best of both worlds.  We can provide our team with a reliable and easy way to set up new development environments, and benefit from NuGet&#8217;s version/dependency smarts, without having to actually store NuGet package binaries in source control.</p>
<p>First, <a href="http://docs.nuget.org/docs/start-here/installing-nuget">install NuGet</a> if you haven&#8217;t already.</p>
<p>Next, go to Solution Explorer, right click on the Solution itself, and select &#8220;Enable Nuget Package Restore&#8221;.  This adds some files to a special .nuget folder, and adjusts the projects of your solution to use that folder at build time.</p>
<p>Lastly, note that NuGet has been placing downloaded packages under a <code>packages/</code> folder near your *.sln.  You can wipe this out.  When using git, I also add this folder to my <code>.gitignore</code> so that its contents no longer get saved to the repository.</p>
<p>Read that last step again.  <strong>We deliberately deleted away all the versioned packages that NuGet has been maintaining for us!</strong></p>
<p>When enabling Package Restore in your solution, you changed the way that your solution builds.  When you try to build again, NuGet will notice that your projects reference specific packages that are no longer found under <code>packages/</code>.  Fortunately, your solution still contains <code>packages.config</code> files which list dependencies along with their version numbers.  Armed with these config files, NuGet will pull down the missing files into <code>packages/</code> for you right before your project gets compiled.  Upon the next build, it will just use the files already in <code>packages/</code>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.headspring.com/2012/04/nuget-package-restore/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Publishing a Library to SymbolSource.org</title>
		<link>http://www.headspring.com/2012/04/publishing-a-library-to-symbolsource-org</link>
		<comments>http://www.headspring.com/2012/04/publishing-a-library-to-symbolsource-org#comments</comments>
		<pubDate>Fri, 06 Apr 2012 16:54:23 +0000</pubDate>
		<dc:creator>Patrick Lioi</dc:creator>
				<category><![CDATA[Developer Deep Dive]]></category>

		<guid isPermaLink="false">http://www.headspring.com/?p=4616</guid>
		<description><![CDATA[Last week, we saw how to publish a library with NuGet. By ...]]></description>
			<content:encoded><![CDATA[<p>Last week, we saw how to <a href="http://www.headspring.com/2012/03/publishing-a-library-with-nuget">publish a library with NuGet</a>.  By including DLL files in our NuGet package under the special &#8220;lib&#8221; folder, NuGet knows to install them as assembly references in the target project.  This is a great way to get your open-source library into the hands of your audience, but it also provides them with a pretty lame debugging scenario.<span id="more-4616"></span></p>
<h2>Black Box Debugging</h2>
<p>Using that NuGet package from last week, I installed <a href="https://github.com/plioi/parsley">Parsley</a> into another project that consumes it.  While trying to debug <em>that</em> project, I got to a point where I wanted to just step the debugger into one of Parsley&#8217;s methods.  Even with the PDB file included in the NuGet package, Visual Studio just plain didn&#8217;t have enough information to let me step through Parsley&#8217;s code.</p>
<p>Too much information about the original source gets lost when a PDB is produced.  We need to make the source code available to the consumer when they install our packages, and we need to so in a way that Visual Studio can take advantage of at debugging time.</p>
<h2>Publishing a Symbol Package</h2>
<p>Fortunately there is a free service, <a href="http://SymbolSource.org">SymbolSource.org</a>, which is easy to integrate with both NuGet (for the publisher) and Visual Studio (for the consumer).  Although getting a SymbolSource account is an option, you won&#8217;t actually need one.  You&#8217;ll be able to publish a special variant of your NuGet package to NuGet.org, and then NuGet.org shakes hands with SymbolSource.org on your behalf.  All it takes is a slight tweak to your <code>.nuspec</code> file, and an extra command-line argument when converting that <code>.nuspec</code> into a <code>.nupkg</code>!</p>
<p>The previous version of my <code>.nuspec</code>&#8216;s <code>files</code> tag just copied DLLs and PDBs into the package&#8217;s special &#8220;lib&#8221; folder:</p>
<div id="gist-2231973" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="nt">&lt;files&gt;</span></div><div class='line' id='LC2'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nt">&lt;file</span> <span class="na">src=</span><span class="s">&quot;$package_dir\*.dll&quot;</span> <span class="na">target=</span><span class="s">&quot;lib\net40&quot;</span> <span class="nt">/&gt;</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nt">&lt;file</span> <span class="na">src=</span><span class="s">&quot;$package_dir\*.pdb&quot;</span> <span class="na">target=</span><span class="s">&quot;lib\net40&quot;</span> <span class="nt">/&gt;</span></div><div class='line' id='LC4'><span class="nt">&lt;/files&gt;</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/2231973/d1c5ce7bf58c87a70bbd80e7a8ec8311b1d57683/PublishingAssemblies.xml" style="float:right;">view raw</a>
            <a href="https://gist.github.com/2231973#file_publishing_assemblies.xml" style="float:right;margin-right:10px;color:#666">PublishingAssemblies.xml</a>
            <a href="https://gist.github.com/2231973">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>The new version also copies all of the source code to the package&#8217;s special &#8220;src&#8221; folder.  We don&#8217;t need to copy auxiliary files like <code>.csproj</code> or <code>.sln</code>.  We just need to copy the code files that the debugger will need to display, namely all the *.cs files:</p>
<div id="gist-2288725" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="nt">&lt;files&gt;</span></div><div class='line' id='LC2'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nt">&lt;file</span> <span class="na">src=</span><span class="s">&quot;$package_dir\*.dll&quot;</span> <span class="na">target=</span><span class="s">&quot;lib\net40&quot;</span> <span class="nt">/&gt;</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nt">&lt;file</span> <span class="na">src=</span><span class="s">&quot;$package_dir\*.pdb&quot;</span> <span class="na">target=</span><span class="s">&quot;lib\net40&quot;</span> <span class="nt">/&gt;</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nt">&lt;file</span> <span class="na">src=</span><span class="s">&quot;$source_dir\**\*.cs&quot;</span> <span class="na">target=</span><span class="s">&quot;src&quot;</span> <span class="nt">/&gt;</span></div><div class='line' id='LC5'><span class="nt">&lt;/files&gt;</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/2288725/fc954ef0b31287e06b282def83ecdbecbbca75ab/PublishingAssembliesAndSource.xml" style="float:right;">view raw</a>
            <a href="https://gist.github.com/2288725#file_publishing_assemblies_and_source.xml" style="float:right;margin-right:10px;color:#666">PublishingAssembliesAndSource.xml</a>
            <a href="https://gist.github.com/2288725">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>I used this single <code>.nuspec</code> to produce <em>two</em> <code>.nupkg</code> files, by including the <code>-Symbols</code> command line argument:</p>
<blockquote><p>
  $ nuget pack Parsley.nuspec -Symbols
</p></blockquote>
<p>This produced Parsley.0.0.2.nupkg like normal, but it also produced Parsley.0.0.2.symbols.nupkg.  NuGet.exe is smart enough to know that the first package only needed the DLLs (used at installation time), and that the symbol package needs to contain the PDBs and C# files (used at debugging time).  When I pushed the main package to NuGet.org, NuGet.exe noticed the symbol package was also present, and submitted that one too:</p>
<blockquote>
<p>$ nuget push Parsley.0.0.2.nupkg<br />
    Pushing Parsley 0.0.2 to the NuGet gallery (https://www.nuget.org)&#8230;<br />
    Your package was pushed.<br />
    Pushing Parsley 0.0.2 to the symbol server (http://nuget.gw.symbolsource/Public/NuGet)&#8230;<br />
    Your package was pushed.</p>
</blockquote>
<p>I then followed the instructions for <a href="http://www.symbolsource.org/Public/Home/VisualStudio">configuring Visual Studio to work with SymbolSource.org</a>.  Remember, you don&#8217;t have to follow the suggestion to create a SymbolSource account.</p>
<p>I updated the package in the consumer project, which installed the DLLs.  The next time I tried to step into a Parsley method, I got a quick dialog that said it was downloading the relevant files from SymbolSource, and then I was able to step through the read-only C# files found within the symbol package!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.headspring.com/2012/04/publishing-a-library-to-symbolsource-org/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Publishing a Library with NuGet</title>
		<link>http://www.headspring.com/2012/03/publishing-a-library-with-nuget</link>
		<comments>http://www.headspring.com/2012/03/publishing-a-library-with-nuget#comments</comments>
		<pubDate>Fri, 30 Mar 2012 19:09:10 +0000</pubDate>
		<dc:creator>Patrick Lioi</dc:creator>
				<category><![CDATA[Developer Deep Dive]]></category>

		<guid isPermaLink="false">http://www.headspring.com/?p=4449</guid>
		<description><![CDATA[Last week, we saw how to publish a simple NuGet package. When ...]]></description>
			<content:encoded><![CDATA[<p>Last week, we saw how to <a href="http://www.headspring.com/2012/03/publishing-a-simple-nuget-package">publish a simple NuGet package</a>.  When installed into your solution in Visual Studio, that package would copy some text files into the target project.  That&#8217;s convenient, but it isn&#8217;t a typical use case for NuGet.  Instead, you usually want to publish compiled assemblies, and you want installation to add those assemblies to the target project&#8217;s list of assembly references.<span id="more-4449"></span></p>
<p>In <a href="http://www.headspring.com/2011/11/recognizing-covariance-issues-in-your-code">Recognizing Covariance Issues in Your Code</a>, I introduced my hobby project, <a href="https://github.com/plioi/Parsley">Parsley</a>.  This project has gotten fairly stable in recent weeks, and I decided to publish it so that I could use NuGet to install it in other projects.</p>
<p>In the <a href="http://www.headspring.com/2012/03/publishing-a-simple-nuget-package">simple NuGet package</a>, we created a *.nuspec file containing a <code>files</code> tag.  That <code>files</code> tag listed the files we wanted to copy into the target project upon installation.  We described the target path starting with &#8220;content&#8221;:</p>
<div id="gist-2231965" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="nt">&lt;files&gt;</span></div><div class='line' id='LC2'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nt">&lt;file</span> <span class="na">src=</span><span class="s">&quot;Enumeration.cs&quot;</span> <span class="na">target=</span><span class="s">&quot;content\Headspring\Enumeration.cs&quot;</span> <span class="nt">/&gt;</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nt">&lt;file</span> <span class="na">src=</span><span class="s">&quot;LICENSE.txt&quot;</span> <span class="na">target=</span><span class="s">&quot;content\Headspring\LICENSE.txt&quot;</span> <span class="nt">/&gt;</span></div><div class='line' id='LC4'><span class="nt">&lt;/files&gt;</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/2231965/080dfa9c975db72f066253f58946e6bd834e8adc/PublishingContent.xml" style="float:right;">view raw</a>
            <a href="https://gist.github.com/2231965#file_publishing_content.xml" style="float:right;margin-right:10px;color:#666">PublishingContent.xml</a>
            <a href="https://gist.github.com/2231965">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p><a href="https://github.com/plioi/parsley/blob/c89236d7f253a13f0eaa3354b9714488d1742d65/default.ps1">Parsley&#8217;s build script</a> generates a *.nuspec file with a slightly different naming convention for the target paths:</p>
<div id="gist-2231973" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="nt">&lt;files&gt;</span></div><div class='line' id='LC2'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nt">&lt;file</span> <span class="na">src=</span><span class="s">&quot;$package_dir\*.dll&quot;</span> <span class="na">target=</span><span class="s">&quot;lib\net40&quot;</span> <span class="nt">/&gt;</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nt">&lt;file</span> <span class="na">src=</span><span class="s">&quot;$package_dir\*.pdb&quot;</span> <span class="na">target=</span><span class="s">&quot;lib\net40&quot;</span> <span class="nt">/&gt;</span></div><div class='line' id='LC4'><span class="nt">&lt;/files&gt;</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/2231973/d1c5ce7bf58c87a70bbd80e7a8ec8311b1d57683/PublishingAssemblies.xml" style="float:right;">view raw</a>
            <a href="https://gist.github.com/2231973#file_publishing_assemblies.xml" style="float:right;margin-right:10px;color:#666">PublishingAssemblies.xml</a>
            <a href="https://gist.github.com/2231973">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>Starting these paths with &#8220;lib&#8221; instead of &#8220;content&#8221; indicates to NuGet that they are libraries and should be added to the target project&#8217;s list of referenced assemblies.  The &#8220;net40&#8243; folder is also a part of the naming convention, indicating that the assembly was built for .NET 4.0.  If we&#8217;re targeting several different runtimes, we could include them all in one package using folder names like &#8220;net11&#8243;, &#8220;net20&#8243;, etc&#8230;</p>
<p>Above, I&#8217;m also copying the *.pdb files into the package.  Next week, we&#8217;ll see a better alternative to enhance the debugging experience for your library&#8217;s users: integrating with <a href="http://symbolsource.org/">SymbolSource.org</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.headspring.com/2012/03/publishing-a-library-with-nuget/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Publishing a Simple NuGet Package</title>
		<link>http://www.headspring.com/2012/03/publishing-a-simple-nuget-package</link>
		<comments>http://www.headspring.com/2012/03/publishing-a-simple-nuget-package#comments</comments>
		<pubDate>Fri, 23 Mar 2012 15:07:56 +0000</pubDate>
		<dc:creator>Patrick Lioi</dc:creator>
				<category><![CDATA[Developer Deep Dive]]></category>

		<guid isPermaLink="false">http://www.headspring.com/?p=4214</guid>
		<description><![CDATA[NuGet is a Visual Studio extension that makes it easy to pull ...]]></description>
			<content:encoded><![CDATA[<p><a href="http://nuget.org/">NuGet</a> is a Visual Studio extension that makes it easy to pull third-party libraries into your projects.  It can also bring in their dependencies, along the same lines as gems for Ruby development.</p>
<p>I recently <a href="http://www.headspring.com/2012/03/migrating-from-bitbucket-to-github">migrated Headspring&#8217;s Enumeration class to GitHub</a>.  This is a simple class that, for the most part, replaces the need for .NET enum types.  One of the simplest things a NuGet package can do is add a file to your project, so creating and publishing an updated NuGet package for Enumeration was a great way to get my feet wet.</p>
<p>Unlike most things, it was as easy as it should be.<span id="more-4214"></span></p>
<p>First, I created an account on <a href="http://nuget.org">nuget.org</a> and installed the extension using the link on the front page.  Next, I downloaded the <a href="http://nuget.codeplex.com/releases/view/58939">NuGet.exe command-line tool</a> and made sure it was included in my PATH.  On my account profile page, I&#8217;m given the chance to see my API Key.  Keep this secret.  At the command line, we need to issue a one-time command so that this key can be active during subsequent nuget commands:</p>
<p><code>$ nuget setApiKey 123-abc-123-abc-123</code></p>
<p>You create a *.nuspec file which describes the files you want to publish.  Then you ask nuget.exe to turn that file into a *.nupkg file.  A nupkg file is actually a zip file containing the files to be deployed as well as some metadata.</p>
<p>At this point, the project consisted of 3 files: a README, LICENSE.txt, and Enumeration.cs.  While in this folder, I issued a command to create a skeleton of a nuspec file:</p>
<p><code>$ nuget spec</code></p>
<p>This creates Package.nuspec, which I renamed to Enumeration.nuspec and populated:</p>
<div id="gist-2155348" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'>&lt;?xml version=&quot;1.0&quot;?&gt;</div><div class='line' id='LC2'>&lt;package&gt;</div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;&lt;metadata&gt;</div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;id&gt;Enumeration&lt;/id&gt;</div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;version&gt;1.0.4&lt;/version&gt;</div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;authors&gt;Headspring&lt;/authors&gt;</div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;owners&gt;Headspring&lt;/owners&gt;</div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;licenseUrl&gt;https://github.com/HeadspringLabs/Enumeration/blob/master/content/Headspring/LICENSE.txt&lt;/licenseUrl&gt;</div><div class='line' id='LC9'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;projectUrl&gt;https://github.com/HeadspringLabs/Enumeration&lt;/projectUrl&gt;</div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;iconUrl&gt;https://bitbucket-assetroot.s3.amazonaws.com/c/photos/2010/May/14/spray_avatar.png&lt;/iconUrl&gt;</div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;requireLicenseAcceptance&gt;false&lt;/requireLicenseAcceptance&gt;</div><div class='line' id='LC12'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;description&gt;A utility class. Common uses include Java-like enumerations, dispatch table, flyweight, and drop-down list items/select options.&lt;/description&gt;</div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;tags&gt;utility enumeration&lt;/tags&gt;</div><div class='line' id='LC14'>&nbsp;&nbsp;&nbsp;&nbsp;&lt;/metadata&gt;</div><div class='line' id='LC15'>&nbsp;&nbsp;&nbsp;&nbsp;&lt;files&gt;</div><div class='line' id='LC16'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;file src=&quot;Enumeration.cs&quot; target=&quot;content\Headspring\Enumeration.cs&quot; /&gt;</div><div class='line' id='LC17'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;file src=&quot;LICENSE.txt&quot; target=&quot;content\Headspring\LICENSE.txt&quot; /&gt;</div><div class='line' id='LC18'>&nbsp;&nbsp;&nbsp;&nbsp;&lt;/files&gt;</div><div class='line' id='LC19'>&lt;/package&gt;</div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/2155348/dd2bb57b30d8c6b1489f70cbddaca49fdfffb166/Enumeration.nuspec" style="float:right;">view raw</a>
            <a href="https://gist.github.com/2155348#file_enumeration.nuspec" style="float:right;margin-right:10px;color:#666">Enumeration.nuspec</a>
            <a href="https://gist.github.com/2155348">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>There isn&#8217;t much going on here.  We say what version number we want to publish, a few descriptive fields, and then list the files we want to be included in the nupkg &#8216;zip&#8217; file.  In the file tags, <code>src</code> refers to the files relative to the location of the nuspec file, and <code>target</code> describes the path we want to copy it to <em>within</em> the zip.  Starting these paths with &#8220;content&#8221; means that when someone installs the package into one of their own projects, the files will be copied and then added to the target project file.</p>
<p>To publish, we just need to issue the following commands:</p>
<p><code>$ nuget pack Enumeration.nuspec</code><br />
<code>$ nuget push Enumeration.1.0.4.nupkg</code><br />
<code>$ del Enumeration.1.0.4.nupkg</code></p>
<p><code>nuget pack</code> converts a nuspec into a nupkg, and <code>nuget push</code> submits it to <a href="http://nuget.org/">nuget.org</a>.  After that, we don&#8217;t need to keep a copy of the nupgk, so we delete it.</p>
<p>That&#8217;s it!  Next week, we&#8217;ll cover the slightly more involved scenario of publishing a whole open-source library.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.headspring.com/2012/03/publishing-a-simple-nuget-package/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Escape Analysis</title>
		<link>http://www.headspring.com/2012/03/escape-analysis</link>
		<comments>http://www.headspring.com/2012/03/escape-analysis#comments</comments>
		<pubDate>Fri, 16 Mar 2012 16:38:25 +0000</pubDate>
		<dc:creator>Patrick Lioi</dc:creator>
				<category><![CDATA[Developer Deep Dive]]></category>

		<guid isPermaLink="false">http://www.headspring.com/?p=4157</guid>
		<description><![CDATA[In languages like Java and C#, most objects wind up on the ...]]></description>
			<content:encoded><![CDATA[<p>In languages like Java and C#, most objects wind up on the heap instead of the stack.  Heap-allocated objects can only be cleaned up by garbage collection, while stack-allocated objects get cleaned up &#8216;for free&#8217; when the function that they were created in returns.</p>
<p>If you have a method that constructs a new instance of a class, uses it a little, and then discards it, there&#8217;s no real reason to put it on the heap.  It&#8217;s not going to need to exist after we return, so we might as well put it on the stack and get the deallocation for free.</p>
<p>If you instead have a method that constructs a new instance of a class and <em>returns</em> that to the caller, we <strong>definitely</strong> have to put it on the heap, because we need to ensure it still exists after we return.  There are lots of things we might do with an object that would require us to use the heap.  We can return it, pass it to another thread, pass it to another function that passes it to another thread, etc.<span id="more-4157"></span></p>
<p>The basic idea is that if, after your function exits, there could not possibly be any remaining references to that object, then it might as well be put on the stack and cleaned away without the need for garbage collection.</p>
<p><a href="http://en.wikipedia.org/wiki/Escape_analysis">Escape analysis</a> is a compiler optimization that can be applied to languages like these.  If the compiler can prove to itself that the object can&#8217;t &#8220;escape&#8221; beyond the lifetime of the method, it will use the stack.</p>
<p>Although escape analysis really just refers to this compiler trick, I like to use the term to describe a specific kind of refactoring effort.  Before I get to that, though, we need to talk about your arch-nemesis.</p>
<h2>Code Doesn&#8217;t Just Rot</h2>
<p>Over the long life of a software project, certain parts of the code will become more difficult than they deserve to be.  One area might be a frequent source of bugs, and the fixes applied by many hands may make it needlessly complex, for instance.</p>
<p>Sometimes it seems that even when an area doesn&#8217;t go through much flux, it still rots.  Newer and better ideas are introduced to the project, and one area may be left behind the times.  By the time you come across it again, it feels like it&#8217;s rotting away.</p>
<p>Code rot taken to its extreme gives you a <a href="http://miksovsky.blogs.com/flowstate/2010/09/every-app-has-a-scary-basement.html">spooky basement</a>, the part of the project <em>nobody</em> wants to touch.  It&#8217;s a tangled mass of patches and awkward abstractions.</p>
<p>I don&#8217;t really like the code rot metaphor because it makes the problem code out to be a passive byproduct.  I prefer to think of bad/awkward/old design decisions as being an <strong>active and malicious adversary hell-bent on escaping from the confines of its files</strong> with the goal of making the rest of your project rot along with it.</p>
<p>Code doesn&#8217;t just rot.  The rot escapes and spreads.  This thing is out to get you.</p>
<h2>Escape Analysis at Refactoring Time</h2>
<p>When I&#8217;m working in a clean area of a project, refactoring is an easy process.  You rename things to make them read better, extract a method or class here or there to organize responsibilities better, and the like.</p>
<p>When I&#8217;m working on a spooky basement, or even a not-so-bad eerie breakfast nook, I put on the Escape Analysis Hat.  Unlike the compiler optimization which asks &#8220;At runtime, how can this <em>instance</em> escape into the rest of the running system&#8221;, I ask &#8220;How do <em>references</em> to this unwanted method/property/field/class escape into the rest of the code?&#8221;</p>
<p>This starts with ReSharper, but tools like this can only get you started.  You find usages of the unwanted thing&#8217;s identifier, and then find usages of those usages, and usages of <em>those</em> usages, to start to get a feel for what other areas depend on it.</p>
<p>That&#8217;s not enough!  Remember, this method/property/field/class is actively trying to escape into the rest of your system.  It wants to escape in any sneaky, devious way it can.  Maybe it gets AutoMapped to some other type, whose usages you&#8217;ll need to investigate.  Maybe it gets serialized to JSON which in turn gets consumed by some javascript you&#8217;ll need to investigate.  Maybe it gets accessed via reflection, or appears in a binding in a XAML file, or gets passed to a web service…</p>
<h2>A Particularly Tricky Example</h2>
<p>I was recently refactoring an area of a project that wasn&#8217;t a serious problem yet.  Left alone, the complexity would have eventually gotten out of control, so we decided to address a particular source of the growing complexity.  I encountered a property in a View Model class that I wanted to simplify; I didn&#8217;t quite see the need for it at first.  After seeing how references to this property escaped into the rest of the system, my first thought was &#8220;Oh, this really does get used in a lot of places, and not just in the UI layer.  It needs to exist.&#8221;</p>
<p>After looking into the escape paths again, though, I realized it was largely unnecessary.  It satisfied a UI requirement, but that could have been satisfied in a simpler way and in only the UI layer.</p>
<p>The escape path was pretty intricate.  This property had a few real and meaningful usages.  Additionally, it got AutoMapped to another type, which ultimately got serialized and later deserialized so it could be AutoMapped <em>back</em> to the original type.  This circuitous route was not actually used for anything (anymore) and could be removed.</p>
<p>The next time you find yourself refactoring, and you reach a point where it&#8217;s not obvious what the next step should be, find a suspicious identifier and see where he&#8217;s escaping to.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.headspring.com/2012/03/escape-analysis/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Finding Closure</title>
		<link>http://www.headspring.com/2012/03/finding-closure</link>
		<comments>http://www.headspring.com/2012/03/finding-closure#comments</comments>
		<pubDate>Fri, 09 Mar 2012 15:47:26 +0000</pubDate>
		<dc:creator>Patrick Lioi</dc:creator>
				<category><![CDATA[Developer Deep Dive]]></category>
		<category><![CDATA[developing with C#]]></category>

		<guid isPermaLink="false">http://www.headspring.com/?p=3990</guid>
		<description><![CDATA[When writing software, we constantly create abstractions. The goal each time is ...]]></description>
			<content:encoded><![CDATA[<p>When writing software, we constantly create abstractions.  The goal each time is to present a simple interface in front of something more complex, hiding the gory details from us so we can focus on other things.  The problem is, <a href="http://en.wikipedia.org/wiki/Leaky_abstraction">abstractions leak</a>.  Even when you go to great effort to create a really exellent abstraction, some unfortunate implementation detail manages to rear its ugly head.  This even happens with things so fundamental that we take them for granted.  Take the &#8216;foreach&#8217; keyword in C#:<span id="more-3990"></span></p>
<div id="gist-1990055" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="kt">var</span> <span class="n">delayedGreetings</span> <span class="p">=</span> <span class="k">new</span> <span class="n">List</span><span class="p">&lt;</span><span class="n">Func</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">&gt;&gt;();</span></div><div class='line' id='LC2'><br/></div><div class='line' id='LC3'><span class="k">foreach</span> <span class="p">(</span><span class="kt">var</span> <span class="n">name</span> <span class="k">in</span> <span class="k">new</span><span class="p">[]</span> <span class="p">{</span> <span class="s">&quot;Larry&quot;</span><span class="p">,</span> <span class="s">&quot;Moe&quot;</span><span class="p">,</span> <span class="s">&quot;Curly&quot;</span> <span class="p">})</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">delayedGreetings</span><span class="p">.</span><span class="n">Add</span><span class="p">(()</span> <span class="p">=&gt;</span> <span class="s">&quot;Hello, &quot;</span> <span class="p">+</span> <span class="n">name</span> <span class="p">+</span> <span class="s">&quot;!&quot;</span><span class="p">);</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div><div class='line' id='LC6'><span class="c1">//Some time later...</span></div><div class='line' id='LC7'><span class="k">foreach</span> <span class="p">(</span><span class="kt">var</span> <span class="n">greeting</span> <span class="k">in</span> <span class="n">delayedGreetings</span><span class="p">)</span></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="n">greeting</span><span class="p">());</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1990055/7f378eef09f899b537db12c7ddab7ab0a612b46d/Fail.cs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1990055#file_fail.cs" style="float:right;margin-right:10px;color:#666">Fail.cs</a>
            <a href="https://gist.github.com/1990055">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>Where we would expect the output to be:<br />
    Hello, Larry!<br />
    Hello, Moe!<br />
    Hello, Curly!</p>
<p>Instead, we see:<br />
    Hello, Curly!<br />
    Hello, Curly!<br />
    Hello, Curly!</p>
<p>Fortunately, ReSharper points out that something fishy is going on with the reference to <code>name</code> that appears in the loop body: <strong>&#8220;Access to modified closure.&#8221;</strong>  If you follow the ReSharper suggested fix, you get this:</p>
<div id="gist-1990084" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">foreach</span> <span class="p">(</span><span class="kt">var</span> <span class="n">name</span> <span class="k">in</span> <span class="k">new</span><span class="p">[]</span> <span class="p">{</span> <span class="s">&quot;Larry&quot;</span><span class="p">,</span> <span class="s">&quot;Moe&quot;</span><span class="p">,</span> <span class="s">&quot;Curly&quot;</span> <span class="p">})</span></div><div class='line' id='LC2'><span class="p">{</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kt">string</span> <span class="n">name1</span> <span class="p">=</span> <span class="n">name</span><span class="p">;</span> <span class="c1">//Added a seemingly-pointless local variable!</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">delayedGreetings</span><span class="p">.</span><span class="n">Add</span><span class="p">(()</span> <span class="p">=&gt;</span> <span class="s">&quot;Hello, &quot;</span> <span class="p">+</span> <span class="n">name1</span> <span class="p">+</span> <span class="s">&quot;!&quot;</span><span class="p">);</span></div><div class='line' id='LC5'><span class="p">}</span></div><div class='line' id='LC6'><br/></div><div class='line' id='LC7'><span class="c1">//Some time later...</span></div><div class='line' id='LC8'><span class="k">foreach</span> <span class="p">(</span><span class="kt">var</span> <span class="n">greeting</span> <span class="k">in</span> <span class="n">delayedGreetings</span><span class="p">)</span></div><div class='line' id='LC9'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="n">greeting</span><span class="p">());</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1990084/9ae8d19272dcdb75ac55c9560ef6484f4f7ae474/ReSharperFix.cs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1990084#file_re_sharper_fix.cs" style="float:right;margin-right:10px;color:#666">ReSharperFix.cs</a>
            <a href="https://gist.github.com/1990084">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>Oddly, introducing this local variable <em>does</em> fix the output, but why?  To find out, let&#8217;s first rewrite the original version using a transformation from a <code>foreach</code> loop to a <code>while</code> loop, since that&#8217;s the first thing the compiler does for us.  It still erroneously prints &#8220;Hello, Curly!&#8221; three times:</p>
<div id="gist-1990116" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="kt">var</span> <span class="n">delayedGreetings</span> <span class="p">=</span> <span class="k">new</span> <span class="n">List</span><span class="p">&lt;</span><span class="n">Func</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">&gt;&gt;();</span></div><div class='line' id='LC2'><br/></div><div class='line' id='LC3'><span class="p">{</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">e</span> <span class="p">=</span> <span class="p">((</span><span class="n">IEnumerable</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">&gt;)</span><span class="k">new</span><span class="p">[]</span> <span class="p">{</span> <span class="s">&quot;Larry&quot;</span><span class="p">,</span> <span class="s">&quot;Moe&quot;</span><span class="p">,</span> <span class="s">&quot;Curly&quot;</span> <span class="p">}).</span><span class="n">GetEnumerator</span><span class="p">())</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="kt">string</span> <span class="n">name</span><span class="p">;</span></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">while</span> <span class="p">(</span><span class="n">e</span><span class="p">.</span><span class="n">MoveNext</span><span class="p">())</span></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span></div><div class='line' id='LC9'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">name</span> <span class="p">=</span> <span class="n">e</span><span class="p">.</span><span class="n">Current</span><span class="p">;</span></div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">delayedGreetings</span><span class="p">.</span><span class="n">Add</span><span class="p">(()</span> <span class="p">=&gt;</span> <span class="s">&quot;Hello, &quot;</span> <span class="p">+</span> <span class="n">name</span> <span class="p">+</span> <span class="s">&quot;!&quot;</span><span class="p">);</span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC12'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC13'><span class="p">}</span></div><div class='line' id='LC14'><br/></div><div class='line' id='LC15'><span class="c1">//Some time later...</span></div><div class='line' id='LC16'><span class="k">foreach</span> <span class="p">(</span><span class="kt">var</span> <span class="n">greeting</span> <span class="k">in</span> <span class="n">delayedGreetings</span><span class="p">)</span></div><div class='line' id='LC17'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="n">greeting</span><span class="p">());</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1990116/7b27aced3f4476962973377e61fcbe1635e8bd52/ForeachToWhile.cs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1990116#file_foreach_to_while.cs" style="float:right;margin-right:10px;color:#666">ForeachToWhile.cs</a>
            <a href="https://gist.github.com/1990116">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>ReSharper still highlights the use of <code>name</code> within the loop body, and still says it is an &#8220;Access to modified closure.&#8221;  Before we can try to fix the problem, we&#8217;re going to have to make sense of that warning.</p>
<h2>What&#8217;s a Closure?</h2>
<p>The word &#8220;closure&#8221; comes up a lot when talking about any language that has anonymous inline functions.  In C#, that means anonymous delegates and their shorthand lambda expressions introduced with <code>=&gt;</code>.  You have comparable anonymous functions in Javascript, Ruby, Python, etc.  Whenever you have an anonymous function whose body refers to identifiers in the surrounding scope, the function earns the right to call itself a closure.</p>
<p>Lambdas are really shorthand for a class with one method as well as the instantiation of that class.  In our example above, the lambdas are living beyond the execution of the loop, and that means they need to live beyond the normal scope of the loop variable, <code>name</code>.  In order to work, they&#8217;ll need to hold onto something about that variable.  In fact, they hold onto the <em>environment</em> that was in effect at the moment the lambda was reached.  By environment, I mean <em>all</em> of the local variables they might be referring to.  It is as if we wrote the following, which also prints &#8220;Hello, Curly!&#8221; three times:</p>
<div id="gist-1990154" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">public</span> <span class="k">class</span> <span class="nc">Environment</span></div><div class='line' id='LC2'><span class="p">{</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">public</span> <span class="kt">string</span> <span class="n">name</span><span class="p">;</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="c1">//As well as one field for each of the</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="c1">//original loop&#39;s local variables, if</span></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="c1">//there were any...</span></div><div class='line' id='LC7'><span class="p">}</span></div><div class='line' id='LC8'><br/></div><div class='line' id='LC9'><span class="k">public</span> <span class="k">class</span> <span class="nc">Greeter</span></div><div class='line' id='LC10'><span class="p">{</span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">private</span> <span class="k">readonly</span> <span class="n">Environment</span> <span class="n">_environment</span><span class="p">;</span></div><div class='line' id='LC12'><br/></div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">public</span> <span class="nf">Greeter</span><span class="p">(</span><span class="n">Environment</span> <span class="n">environment</span><span class="p">)</span></div><div class='line' id='LC14'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span></div><div class='line' id='LC15'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">_environment</span> <span class="p">=</span> <span class="n">environment</span><span class="p">;</span></div><div class='line' id='LC16'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC17'><br/></div><div class='line' id='LC18'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">public</span> <span class="kt">string</span> <span class="nf">Execute</span><span class="p">()</span></div><div class='line' id='LC19'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span></div><div class='line' id='LC20'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="s">&quot;Hello, &quot;</span> <span class="p">+</span> <span class="n">_environment</span><span class="p">.</span><span class="n">name</span> <span class="p">+</span> <span class="s">&quot;!&quot;</span><span class="p">;</span></div><div class='line' id='LC21'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC22'><span class="p">}</span></div><div class='line' id='LC23'><br/></div><div class='line' id='LC24'><span class="k">static</span> <span class="k">void</span> <span class="nf">Main</span><span class="p">(</span><span class="kt">string</span><span class="p">[]</span> <span class="n">args</span><span class="p">)</span></div><div class='line' id='LC25'><span class="p">{</span></div><div class='line' id='LC26'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kt">var</span> <span class="n">delayedGreetings</span> <span class="p">=</span> <span class="k">new</span> <span class="n">List</span><span class="p">&lt;</span><span class="n">Greeter</span><span class="p">&gt;();</span></div><div class='line' id='LC27'><br/></div><div class='line' id='LC28'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span></div><div class='line' id='LC29'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">e</span> <span class="p">=</span> <span class="p">((</span><span class="n">IEnumerable</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">&gt;)</span><span class="k">new</span><span class="p">[]</span> <span class="p">{</span> <span class="s">&quot;Larry&quot;</span><span class="p">,</span> <span class="s">&quot;Moe&quot;</span><span class="p">,</span> <span class="s">&quot;Curly&quot;</span> <span class="p">}).</span><span class="n">GetEnumerator</span><span class="p">())</span></div><div class='line' id='LC30'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span></div><div class='line' id='LC31'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="kt">var</span> <span class="n">environment</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Environment</span><span class="p">();</span></div><div class='line' id='LC32'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">while</span> <span class="p">(</span><span class="n">e</span><span class="p">.</span><span class="n">MoveNext</span><span class="p">())</span></div><div class='line' id='LC33'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span></div><div class='line' id='LC34'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">environment</span><span class="p">.</span><span class="n">name</span> <span class="p">=</span> <span class="n">e</span><span class="p">.</span><span class="n">Current</span><span class="p">;</span></div><div class='line' id='LC35'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">delayedGreetings</span><span class="p">.</span><span class="n">Add</span><span class="p">(</span><span class="k">new</span> <span class="n">Greeter</span><span class="p">(</span><span class="n">environment</span><span class="p">));</span></div><div class='line' id='LC36'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC37'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC38'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC39'><br/></div><div class='line' id='LC40'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="c1">//Some time later...</span></div><div class='line' id='LC41'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">foreach</span> <span class="p">(</span><span class="kt">var</span> <span class="n">greeting</span> <span class="k">in</span> <span class="n">delayedGreetings</span><span class="p">)</span></div><div class='line' id='LC42'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="n">greeting</span><span class="p">.</span><span class="n">Execute</span><span class="p">());</span></div><div class='line' id='LC43'><br/></div><div class='line' id='LC44'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">Console</span><span class="p">.</span><span class="n">ReadLine</span><span class="p">();</span></div><div class='line' id='LC45'><span class="p">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1990154/b001bc9285ce807a9c737c31aff40d79e1581361/VerboseYetEquivalent.cs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1990154#file_verbose_yet_equivalent.cs" style="float:right;margin-right:10px;color:#666">VerboseYetEquivalent.cs</a>
            <a href="https://gist.github.com/1990154">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>AHA! See how we have only <em>one</em> instance of Environment shared by all the <code>Greeter</code>s, and each iteration of the loop messes with the <code>name</code> field <em>inside</em> that shared Environment?  No wonder our final loop prints out the same thing each time: all the items in <code>delayedGreetings</code> refer to the same Environment, which contains only one name, which equals whatever we set it to <em>last</em>.</p>
<p>They call these lambdas &#8220;closures&#8221; because the secret object behind the scenes is grasping-at / enveloping / <em>closing-on</em> the local environment.  As we see in the last example, even after the environment is closed on, we can still affect that environment.  We say that the lambda is closing on the <em>variables themselves</em> rather than simply holding a reference to their <em>values</em>.</p>
<p><strong>Even foreach leaks.</strong></p>
<h2>Fixing foreach</h2>
<p>So we&#8217;ve got this fancy compiler that can take a combination of <code>foreach</code> and lambda expressions, rewriting them into some equivalent-yet-verbose code, which in turn is easier to compile.  It&#8217;s a big abstraction that usually works so well we don&#8217;t stop to think it&#8217;s even <em>happening</em>.  How could we fix it?</p>
<p>It seems the whole problem comes down to the fact that with one shared environment, each iteration messes with a shared mutable object.  We get one environment per scope, though, and the <code>while</code> loop body introduces a new, more-local scope of its own!  We could take advantage of that by declaring the loop-iteration variable <code>name</code> <em>within</em> the <code>while</code> instead of <em>before</em> it.  This way, each iteration will get its own Environment with its own <code>name</code>.  Nothing shared, nothing mutated, leaving us with the three distinct greetings we wanted.  In other words, we wish that <code>foreach</code> gets translated into a <code>while</code> loop like so:</p>
<div id="gist-1990196" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="kt">var</span> <span class="n">delayedGreetings</span> <span class="p">=</span> <span class="k">new</span> <span class="n">List</span><span class="p">&lt;</span><span class="n">Func</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">&gt;&gt;();</span></div><div class='line' id='LC2'><br/></div><div class='line' id='LC3'><span class="p">{</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">e</span> <span class="p">=</span> <span class="p">((</span><span class="n">IEnumerable</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">&gt;)</span><span class="k">new</span><span class="p">[]</span> <span class="p">{</span> <span class="s">&quot;Larry&quot;</span><span class="p">,</span> <span class="s">&quot;Moe&quot;</span><span class="p">,</span> <span class="s">&quot;Curly&quot;</span> <span class="p">}).</span><span class="n">GetEnumerator</span><span class="p">())</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">while</span> <span class="p">(</span><span class="n">e</span><span class="p">.</span><span class="n">MoveNext</span><span class="p">())</span></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="kt">string</span> <span class="n">name</span> <span class="p">=</span> <span class="n">e</span><span class="p">.</span><span class="n">Current</span><span class="p">;</span> <span class="c1">//Variable declaration inside the while.</span></div><div class='line' id='LC9'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">delayedGreetings</span><span class="p">.</span><span class="n">Add</span><span class="p">(()</span> <span class="p">=&gt;</span> <span class="s">&quot;Hello, &quot;</span> <span class="p">+</span> <span class="n">name</span> <span class="p">+</span> <span class="s">&quot;!&quot;</span><span class="p">);</span></div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC12'><span class="p">}</span></div><div class='line' id='LC13'><br/></div><div class='line' id='LC14'><span class="c1">//Some time later...</span></div><div class='line' id='LC15'><span class="k">foreach</span> <span class="p">(</span><span class="kt">var</span> <span class="n">greeting</span> <span class="k">in</span> <span class="n">delayedGreetings</span><span class="p">)</span></div><div class='line' id='LC16'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="n">greeting</span><span class="p">());</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1990196/d1bdfa7186732e5ca47c1e07a68740ef63a0c468/FixedWhile.cs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1990196#file_fixed_while.cs" style="float:right;margin-right:10px;color:#666">FixedWhile.cs</a>
            <a href="https://gist.github.com/1990196">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>ReSharper&#8217;s suggestions basically accomplish the same thing.  By introducing a seemingly-redundant copy within the smaller scope, the environment used by the lambdas is different in each iteration.</p>
<p>Usually when something as fundamental as a looping keyword has a problem like this, the language designers don&#8217;t really have the option of correcting it.  It&#8217;s technically a breaking change to make all <code>foreach</code> loops translate to the better version of the <code>while</code> seen in the last example.  <strong>However, they are going to be <a href="http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx">fixing foreach in C#5</a>.</strong> It&#8217;s a breaking change, but one that will <em>fix</em> more mistakes than it <em>creates</em>!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.headspring.com/2012/03/finding-closure/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Served from: www.headspring.com @ 2012-05-18 12:53:41 -->
