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

<channel>
	<title>Matthew Spivey</title>
	<atom:link href="http://matthewspivey.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://matthewspivey.com</link>
	<description>Just another WordPress site</description>
	<lastBuildDate>Wed, 02 Nov 2011 16:34:16 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Legacy Best Practices</title>
		<link>http://matthewspivey.com/blog/legacy-best-practices/</link>
		<comments>http://matthewspivey.com/blog/legacy-best-practices/#comments</comments>
		<pubDate>Thu, 15 Jul 2010 01:42:26 +0000</pubDate>
		<dc:creator>Matthew Spivey</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Refactor]]></category>

		<guid isPermaLink="false">http://matthewspivey.com/?p=310</guid>
		<description><![CDATA[This disturbing code snippet comes from the Daily WTF.
public boolean isBooleanFalse&#40;boolean value&#41; &#123;
&#160; &#160;boolean response = false;
&#160; &#160;if &#40;value == true&#41; &#123;
&#160; &#160; &#160; &#160;response = false;
&#160; &#160;&#125; else &#123;
&#160; &#160; &#160; &#160;response = true;
&#160; &#160;&#125;
&#160; &#160;return response;
&#125;

It&#8217;s difficult to imagine what the author was thinking.  I&#8217;d like to believe it&#8217;s a contrived example, ...]]></description>
			<content:encoded><![CDATA[<p>This disturbing code snippet comes from the <a href="http://thedailywtf.com/Articles/Bulletproofed-Boolean.aspx">Daily WTF</a>.</p>
<div class="codecolorer-container java default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:700px;"><div class="java codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> isBooleanFalse<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">boolean</span> value<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp;<span style="color: #000066; font-weight: bold;">boolean</span> response <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp;<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>value <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp;response <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp;<span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp;response <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">true</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp;<span style="color: #009900;">&#125;</span><br />
&nbsp; &nbsp;<span style="color: #000000; font-weight: bold;">return</span> response<span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span></div></div>
<p><span id="more-310"></span><br />
It&#8217;s difficult to imagine what the author was thinking.  I&#8217;d like to believe it&#8217;s a contrived example, but I&#8217;ve seen similar code.  This method could easily be reduced to <code class="codecolorer text default"><span class="text">public boolean isBooleanFalse(boolean value) { return !value; }</span></code>.  Better yet, calls to the could be replaced with <code class="codecolorer text default"><span class="text">!value</span></code>.</p>
<p>Why do programmers write code like this?  My first thought was blame the programmer for not having learned how to use the <code class="codecolorer text default"><span class="text">!</span></code> operator.  Or maybe it&#8217;s Martin Folwer&#8217;s fault for publishing the Replace Temp with Query refactor that recommends trivial methods like this.  However, I think part of the responsibility falls on antiquated best practices and coding standards, like those left over from K&#038;R C.</p>
<p>An Assistant Professor of Psychology at Stanford, wrote, &#8220;one&#8217;s native language appears to exert a strong influence over how one thinks.&#8221;[<a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.11.3251&#038;rep=rep1&#038;type=pdf">pdf</a>]  It&#8217;s reasonable to extend this conclusion to programming languages.  The style we use and the coding standards we follow affect how we solve problems.</p>
<p>Consider how reversing the following guidelines push the suspect code snippet closer to the optimal solution.</p>
<dl>
<dt>Declare variables at the top of methods</dt>
<dd>By habit, some C programmers declare and initialize variables before the first instruction.  One of many side effects is that temporary variables seem to be created early in the processes, leading to variables that are not necessary.</dd>
<dt>Single exit point</dt>
<dd>This single exit point practice states that there should be a single return.  The optimal version of this method requires only one return.  However, adding a return to each case of the if-else would remove the temporary variable, leading the programmer one step closer.  There are coding standards <i>today</i> that still forbid this.</dd>
<dt>No ternary operators</dt>
<dd>Some organizations hire developers that can&#8217;t grok <code class="codecolorer text default"><span class="text">(expression) ? true : false;</span></code>, so they forbid it&#8217;s use.  The <code class="codecolorer text default"><span class="text">?</span></code> operator is abused, but so are switch statements, inheritance, reflection, and function pointers.</dd>
<dt>Not using Booleans like Booleans</dt>
<dd>C added bool over a decade ago, though some developers are still waiting to use them.  Since these guys are typically using integers, the correct expression is <code class="codecolorer text default"><span class="text">if (MyBool == OVERLOADED_TRUE)</span></code>, rather than the more concise <code class="codecolorer text default"><span class="text">if (MyBool)</span></code>.  These developers even bring this style into Java and C#, without considering why it existed.</dd>
</dl>
<p><br/><br />
These apply less today than they did on mainframes in 1978.  Not only do they add noise, they also hinder our problem solving abilities.  I&#8217;m not advocating the use every good tool or pattern that comes along, but we need to be more skeptical of long standing conventions.</p>
]]></content:encoded>
			<wfw:commentRss>http://matthewspivey.com/blog/legacy-best-practices/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Replace guard clauses with code contracts</title>
		<link>http://matthewspivey.com/blog/replace-guard-clauses-with-code-contracts/</link>
		<comments>http://matthewspivey.com/blog/replace-guard-clauses-with-code-contracts/#comments</comments>
		<pubDate>Mon, 17 May 2010 16:46:27 +0000</pubDate>
		<dc:creator>matthew spivey</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Code Contracts]]></category>
		<category><![CDATA[Refactor]]></category>

		<guid isPermaLink="false">http://matthewspivey.com/blog/?p=54</guid>
		<description><![CDATA[.NET developers should consider replacing guard clauses with code contracts.

Guard Clauses
Kent Beck or Martin Fowler championed Guard Clauses.  There aren&#8217;t many excuses to write functions with many levels in indentation.
void GetSalesTax&#40;&#41;
&#123;
if&#40;_StateTaxRate == null &#124;&#124; _CountyTaxRate == null&#41;
&#160; return;
return &#40;salesPrice * _StateTaxRate&#41; + &#40;salesPrice * _CountyTaxRate&#41;;
&#125;
Advantages

placement makes it more obvious that these are preconditions (xUnit ...]]></description>
			<content:encoded><![CDATA[<div id="attachment_365" class="wp-caption aligncenter" style="width: 650px"><a href="http://matthewspivey.com/blog/replace-guard-clauses-with-code-contracts/2163034259_034959e7e4_z/" rel="attachment wp-att-365"><img src="http://matthewspivey.com/wp-content/uploads/2010/05/2163034259_034959e7e4_z.jpg" alt="" title="Guard" width="640" height="465" class="size-full wp-image-365" /></a><p class="wp-caption-text">From <a href='http://www.flickr.com/photos/library_of_congress/'>The Library of Congress</a>, via <a href='http://www.flickr.com/photos/library_of_congress/2163034259/'>Flickr</a></p></div>
<p>.NET developers should consider replacing guard clauses with code contracts.<br />
<span id="more-54"></span></p>
<h4>Guard Clauses</h4>
<p>Kent Beck or Martin Fowler championed Guard Clauses.  There aren&#8217;t many excuses to write functions with many levels in indentation.</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:700px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #6666cc; font-weight: bold;">void</span> GetSalesTax<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
<span style="color: #0600FF; font-weight: bold;">if</span><span style="color: #008000;">&#40;</span>_StateTaxRate <span style="color: #008000;">==</span> <span style="color: #0600FF; font-weight: bold;">null</span> <span style="color: #008000;">||</span> _CountyTaxRate <span style="color: #008000;">==</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span><br />
&nbsp; <span style="color: #0600FF; font-weight: bold;">return</span><span style="color: #008000;">;</span><br />
<span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">&#40;</span>salesPrice <span style="color: #008000;">*</span> _StateTaxRate<span style="color: #008000;">&#41;</span> <span style="color: #008000;">+</span> <span style="color: #008000;">&#40;</span>salesPrice <span style="color: #008000;">*</span> _CountyTaxRate<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
<span style="color: #008000;">&#125;</span></div></div>
<p>Advantages</p>
<ul>
<li>placement makes it more obvious that these are preconditions (<a href="http://xunitpatterns.com/Guard%20Clause.html">xUnit Patterns</a>)</li>
<li>&#8220;the guard clause says, &#8216;This is rare, and if it happens, do something and get out.&#8217;&#8221;, Martin Factor in <a href="http://martinfowler.com/books.html#refactoring">Refactor</a></li>
<li>avoids the <a href="http://c2.com/cgi/wiki?ArrowAntiPattern">arrow anti-pattern</a></li>
</ul>
<h4>Code Contracts</h4>
<p>Microsoft <a href="http://research.microsoft.com/en-us/projects/contracts/">Code Contracts</a> provide a better alternative for software using .NET.</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:700px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #6666cc; font-weight: bold;">void</span> GetSalesTax<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; Contract<span style="color: #008000;">.</span><span style="color: #0000FF;">Requires</span><span style="color: #008000;">&#40;</span>_StateTaxRate <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
&nbsp; Contract<span style="color: #008000;">.</span><span style="color: #0000FF;">Requires</span><span style="color: #008000;">&#40;</span>_CountyTaxRate <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
<br />
&nbsp; <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">&#40;</span>salesPrice <span style="color: #008000;">*</span> _StateTaxRate<span style="color: #008000;">&#41;</span> <span style="color: #008000;">+</span> <span style="color: #008000;">&#40;</span>salesPrice <span style="color: #008000;">*</span> _CountyTaxRate<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
<span style="color: #008000;">&#125;</span></div></div>
<p>Advantages</p>
<ul>
<li>same benefits as guard clauses</li>
<li><a href="http://en.wikipedia.org/wiki/Declarative_programming">declarative</a></li>
<li>can be statically verified</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://matthewspivey.com/blog/replace-guard-clauses-with-code-contracts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Comment trick</title>
		<link>http://matthewspivey.com/blog/comment-trick/</link>
		<comments>http://matthewspivey.com/blog/comment-trick/#comments</comments>
		<pubDate>Mon, 17 May 2010 01:39:55 +0000</pubDate>
		<dc:creator>matthew spivey</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://matthewspivey.com/blog/?p=143</guid>
		<description><![CDATA[Maybe I&#8217;m the last to know, but I recently learned this little trick.  When temporarily commenting out a block of code in a C++ flavored language, close the comments with // */.  This lets you to toggle the code on and off using only the opening /*.

Old way
/*
disabled_command();
*/
New way
/*
disabled_command();
// */
Thanks Zach.
]]></description>
			<content:encoded><![CDATA[<p>Maybe I&#8217;m the last to know, but I recently learned this little trick.  When temporarily commenting out a block of code in a C++ flavored language, close the comments with <code class="codecolorer csharp default"><span class="csharp"><span style="color: #008080; font-style: italic;">// */</span></span></code>.  This lets you to toggle the code on and off using only the opening <code class="codecolorer csharp default"><span class="csharp"><span style="color: #008080; font-style: italic;">/*</span></span></code>.<br />
<span id="more-143"></span></p>
<h3>Old way</h3>
<div class="codecolorer-container text default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:700px;"><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">/*<br />
disabled_command();<br />
*/</div></div>
<h3>New way</h3>
<div class="codecolorer-container text default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:700px;"><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">/*<br />
disabled_command();<br />
// */</div></div>
<p>Thanks <a href="http://blog.zacharylew.is/">Zach</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://matthewspivey.com/blog/comment-trick/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Measuring LINQ’s Performance</title>
		<link>http://matthewspivey.com/blog/measuring-linqs-performance/</link>
		<comments>http://matthewspivey.com/blog/measuring-linqs-performance/#comments</comments>
		<pubDate>Mon, 03 May 2010 16:50:26 +0000</pubDate>
		<dc:creator>matthew spivey</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://matthewspivey.com/blog/?p=88</guid>
		<description><![CDATA[Back when LINQ was the next big thing, I remember the excitement of showing it to a fellow developer.  He frowned and said it looked to slow to be usable.  Not wanting to have my new toy taken away, I set out on a quest to justify it.
To compare LINQ to non-LINQ implementations, ...]]></description>
			<content:encoded><![CDATA[<p>Back when LINQ was the next big thing, I remember the excitement of showing it to a fellow developer.  He frowned and said it looked to slow to be usable.  Not wanting to have my new toy taken away, I set out on a quest to justify it.<span id="more-88"></span></p>
<p>To compare LINQ to non-LINQ implementations, we must measure the execution time of each.   If you&#8217;re a Computer Scientist type, you know we can analyze our algorithms using <a href="http://en.wikipedia.org/wiki/Big_O_notation">big O notation</a>.  One problem with this is that it requires having the LINQ source code.  It also ignores the other potential costs, like increased function calls.</p>
<h3>Intersection Results</h3>
<p>The last post <a>compared the maintainability of four methods</a> that computed the intersection of two sets.  The following graph illustrates how the run time increases as the set sizes grow.</p>
<p><img src="http://matthewspivey.com/wp-content/uploads/2010/07/linq-performance.png" alt="" title="linq-performance" width="640" height="434" class="aligncenter size-full wp-image-288" /></p>
<p>Our goal is to compare the examples, so the curve of each line is more important than the actual times and set sizes.</p>
<p>What does the graph tell us?</p>
<ul>
<li>The nested <code class="codecolorer csharp default"><span class="csharp"><span style="color: #0600FF; font-weight: bold;">foreach</span></span></code> is slow, because as the set size increases, the execution time increases exponentially.</li>
<li>The highly tweaked sort first algorithm out performed the LINQ query.</li>
<li>The LINQ call (<code class="codecolorer csharp default"><span class="csharp">IEnumerable<span style="color: #008000;">.</span><span style="color: #0000FF;">Intersect</span></span></code>) outperformed them all.</li>
</ul>
<p>So for this example, the call to <code class="codecolorer csharp default"><span class="csharp">IEnumerable<span style="color: #008000;">.</span><span style="color: #0000FF;">Intersect</span></span></code> is both the simplest and fastest approach.  If didn&#8217;t already exist, the verbose sort first would be our fastest option.</p>
<h3>How to measure performance</h3>
<p>We need to write some code to exercise the different algorithms we want to compare.  To produce the graph above, I used C# and the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx"><code class="codecolorer csharp default"><span class="csharp"><span style="color: #000000;">System.<span style="color: #0000FF;">Diagnostics</span></span><span style="color: #008000;">.</span><span style="color: #0000FF;">Stopwatch</span></span></code></a>.</p>
<p>For each set size on the graphs x-axis, we run each function against a random set of values.  The range and distribution of the values in the set should be tailored to your needs.<br />
To get a nice smooth curve, each test should be executed thousands of times (I did 100,000), and then an average should be taken.</p>
<p>There is one caveat.  LINQ uses <a href="http://en.wikipedia.org/wiki/Lazy_evaluation">lazy evaluation</a>, which means that the query is not performed until it is need.  So if you want to time the query, you need to invoke the query.  The <code class="codecolorer csharp default"><span class="csharp">IList<span style="color: #008000;">.</span><span style="color: #0000FF;">ToArray</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span></span></code> method does this.</p>
]]></content:encoded>
			<wfw:commentRss>http://matthewspivey.com/blog/measuring-linqs-performance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Comparing LINQ’s maintainability</title>
		<link>http://matthewspivey.com/blog/linq-is-more-maintainable/</link>
		<comments>http://matthewspivey.com/blog/linq-is-more-maintainable/#comments</comments>
		<pubDate>Mon, 26 Apr 2010 02:49:23 +0000</pubDate>
		<dc:creator>matthew spivey</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://matthewspivey.com/blog/?p=27</guid>
		<description><![CDATA[
LINQ hides the gory details of how algorithms work, making code measurably more maintainable. Maintainability is correlated with both cost[pdf] and defects[pdf].  In the following example, we&#8217;ll use Visual Studio 2010 to measure maintainability.

Set Intersection
Imagine we have two sets of integers, and we need to find the intersection &#8211; that is, numbers that are ...]]></description>
			<content:encoded><![CDATA[<p><a href="http://matthewspivey.com/?attachment_id=289"><img src="http://matthewspivey.com/wp-content/uploads/2010/07/1a34867r1.jpg" alt="" title="Maintain" width="640" height="518" class="aligncenter size-full wp-image-289" /></a></p>
<p>LINQ hides the gory details of how algorithms work, making code measurably more maintainable. Maintainability is correlated with both cost[<a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.116.35&amp;rep=rep1&amp;type=pdf">pdf</a>] and defects[<a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.33.4527&amp;rep=rep1&amp;type=pdf">pdf</a>].  In the following example, we&#8217;ll use Visual Studio 2010 to measure maintainability.<br />
<span id="more-27"></span></p>
<h3>Set Intersection</h3>
<p>Imagine we have two sets of integers, and we need to find the intersection &#8211; that is, numbers that are in both sets.  In addition, the intersection set should not contain duplicates. Below are four C# functions, followed by a comparison of their maintainability indexes.</p>
<h4>Function 1</h4>
<p>A junior developer might begin by taking each number in set A, and searching set B for that number.  The C# code for this might look like:</p>
<div class="codecolorer-container text default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:700px;"><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">int[] ForEach(List SetA, List SetB)<br />
{<br />
&nbsp; var intersections = new List();<br />
&nbsp; foreach (int a in SetA)<br />
&nbsp; &nbsp; foreach (int b in SetB)<br />
&nbsp; &nbsp; &nbsp; if (a == b)<br />
&nbsp; &nbsp; &nbsp; &nbsp; if (Contains(intersections, a))<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; intersections.Add(a);<br />
&nbsp; return intersections.ToArray();<br />
}<br />
bool Contains(List set, int target)<br />
{<br />
&nbsp; foreach (int i in set)<br />
&nbsp; &nbsp; if (i == target)<br />
&nbsp; &nbsp; &nbsp; return true;<br />
&nbsp; return false;<br />
}</div></div>
<h4>Function 2</h4>
<p>A more senior developer might review Function 1 and notice that it is slow when operating on large sets.  There are three nested loops, including the .Contains, which is great than O(n2) complexity.<br />
A more efficient solution would be to sort both sets first, so that we can find the intersection using a single loop.  For example:</p>
<div class="codecolorer-container text default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:700px;height:600px;"><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">int[] SortFirst(List SetA, List SetB)<br />
{<br />
&nbsp; //sort sets and use parallel pointers O(n)<br />
&nbsp; var sortedA = new List(SetA);<br />
&nbsp; var sortedB = new List(SetB);<br />
&nbsp; var intersect = new List();<br />
&nbsp; sortedA.Sort();<br />
&nbsp; sortedB.Sort();<br />
&nbsp; int indexA = 0;<br />
&nbsp; int indexB = 0;<br />
&nbsp; while (indexA &amp;lt; sortedA.Count &amp;amp;&amp;amp; indexB &amp;lt; sortedB.Count)<br />
&nbsp; {<br />
&nbsp; &nbsp; if (sortedA[indexA] &amp;lt; sortedB[indexB])<br />
&nbsp; &nbsp; &nbsp; indexA++;<br />
&nbsp; &nbsp; else if (sortedB[indexB] &amp;lt; sortedA[indexA])<br />
&nbsp; &nbsp; &nbsp; indexB++;<br />
&nbsp; &nbsp; else<br />
&nbsp; &nbsp; {<br />
&nbsp; &nbsp; &nbsp; intersect.Add(sortedA[indexA]);<br />
&nbsp; &nbsp; &nbsp; indexA++;<br />
&nbsp; &nbsp; &nbsp; indexB++;<br />
&nbsp; &nbsp; }<br />
&nbsp; }<br />
&nbsp; return intersect.ToArray();<br />
}</div></div>
<p>This is the type of code that gives the author pride, and the maintainer a headache.  It may be fast, but the intent is not obvious.</p>
<h4>Function 3</h4>
<p>Now let&#8217;s try a query using LINQ.</p>
<div class="codecolorer-container text default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:700px;"><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">int[] LinqQuery(List SetA, List SetB)<br />
{<br />
&nbsp; return (from a in SetA<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; where SetB.Contains(a)<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; select a).Distinct().ToArray();<br />
}</div></div>
<p>Note that this function creates a nested loop.  For each number in set A, we must search for it in set B.</p>
<h4>Function 4</h4>
<p>Fortunately, LINQ already contains a number of basic math operations, including intersect.  For example:</p>
<div class="codecolorer-container text default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:700px;"><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">int[] LinqCall(List SetA, List SetB)<br />
{<br />
&nbsp; return SetA.Intersect(SetB).ToArray();<br />
}</div></div>
<h4>Maintainability</h4>
<p>The LINQ functions appear to be the most maintainble.  However, we need a more systematic approach.  Starting with Visual Studio 2008, the Visual Studio now includes a static code analysis tool, which we can use to compute a maintainability index.  These numbers range from 0 to 100, where 100 is the most maintainable.  I&#8217;ll discuss how this works in a future post.</p>
<p>Using Visual Studio 2010 Ultimate RC1, we get the following results:</p>
<table>
<tbody>
<tr>
<th>Function</th>
<th>Maintainability Index</th>
</tr>
<tr>
<td>1</td>
<td>64</td>
</tr>
<tr>
<td>2</td>
<td>54</td>
</tr>
<tr>
<td>3</td>
<td>73</td>
</tr>
<tr>
<td>3</td>
<td>83</td>
</tr>
</tbody>
</table>
<p>These metrics show that LINQ does produce more maintainable code.  In the next post, we&#8217;ll measure the performance of each algorithm.</p>
]]></content:encoded>
			<wfw:commentRss>http://matthewspivey.com/blog/linq-is-more-maintainable/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>When should we use LINQ?</title>
		<link>http://matthewspivey.com/blog/when-should-we-use-linq/</link>
		<comments>http://matthewspivey.com/blog/when-should-we-use-linq/#comments</comments>
		<pubDate>Mon, 19 Apr 2010 11:27:54 +0000</pubDate>
		<dc:creator>matthew spivey</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://matthewspivey.com/blog/?p=24</guid>
		<description><![CDATA[
Microsoft LINQ integrates queries directly into .NET languages, making it easy to work with collections.  The best part about LINQ is that it allows us to say what we want to do to a set, without telling it how.  This decreases code complexity, without losing any functionality.

For example, say we had the following ...]]></description>
			<content:encoded><![CDATA[<p><a href="http://matthewspivey.com/?attachment_id=290"><img src="http://matthewspivey.com/wp-content/uploads/2010/07/11607r1.jpg" alt="" title="Short &amp; Tall" width="640" height="470" class="aligncenter size-full wp-image-290" /></a></p>
<p>Microsoft LINQ integrates queries directly into .NET languages, making it easy to work with collections.  The best part about LINQ is that it allows us to say what we want to do to a set, without telling it how.  This decreases code complexity, without losing any functionality.<br />
<span id="more-24"></span></p>
<p>For example, say we had the following function:</p>
<div class="codecolorer-container text default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:700px;"><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">IEnumerable GetAboveTwo(int[] numbers)<br />
{<br />
&nbsp; &nbsp; var aboveTwo = new List&amp;lt;int&amp;gt;();<br />
<br />
&nbsp; &nbsp; foreach(int n in numbers)<br />
&nbsp; &nbsp; &nbsp; &nbsp; if (n &amp;gt; 2)<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; aboveTwo.Add(n);<br />
<br />
&nbsp; &nbsp; return aboveTwo;<br />
}</div></div>
<p>We could read this roughly as, &#8220;Create a temporary collection.  For each number, if it is greater than two, add it to a collection to be returned.  Finally, return the temporary collection.&#8221; This isn&#8217;t a bad method, but it could be better.  Using LINQ, we can rewrite it as:</p>
<div class="codecolorer-container text default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:700px;"><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">IEnumerableGetAboveTwo(int[] numbers)<br />
{<br />
&nbsp; &nbsp; return from n in numbers<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;where n &amp;gt; 2<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;select n;<br />
}</div></div>
<p>Now, we have &#8220;return every number greater than two.&#8221;  Note that it states <em>what</em> will be returned, not <em>how</em>.  In the net post, we&#8217;ll actually measure the maintainability of each approach.</p>
<p>What sort of performance cost do we pay for the luxury of LINQ?  When performance matters more than maintainability, we must develop tests to determine the best solution.  In the upcoming posts, we&#8217;ll learn how to quantify LINQ&#8217;s impact on both performance and maintainability.</p>
<blockquote><p>We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.<cite>Donald Knuth</cite></p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://matthewspivey.com/blog/when-should-we-use-linq/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic page generated in 7.673 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2011-12-16 18:37:34 -->

