<?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:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Making the Complex Simple &#187; C#</title>
	<atom:link href="http://simpleprogrammer.com/category/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://simpleprogrammer.com</link>
	<description>Software Development from John Sonmez&#039;s Perspective</description>
	<lastBuildDate>Tue, 07 Feb 2012 17:47:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='simpleprogrammer.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Making the Complex Simple &#187; C#</title>
		<link>http://simpleprogrammer.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://simpleprogrammer.com/osd.xml" title="Making the Complex Simple" />
	<atom:link rel='hub' href='http://simpleprogrammer.com/?pushpress=hub'/>
		<item>
		<title>MonoTouch</title>
		<link>http://simpleprogrammer.com/2011/10/30/monotouch/</link>
		<comments>http://simpleprogrammer.com/2011/10/30/monotouch/#comments</comments>
		<pubDate>Mon, 31 Oct 2011 02:33:24 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[iPad]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Mobile]]></category>
		<category><![CDATA[MonoTouch]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/?p=1408</guid>
		<description><![CDATA[I’ve been so busy lately that I have neglected to write about a great platform for developing iOS applications called “MonoTouch.” I recently released a new course on MonoTouch at Pluralsight. I wanted to take a bit of time here to talk about MonoTouch and to tell you why you should be using it instead [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1408&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I’ve been so busy lately that I have neglected to write about a great platform for developing iOS applications called “<a href="http://xamarin.com/monotouch">MonoTouch</a>.”</p>
<p>I recently released a <a href="http://www.pluralsight-training.net/microsoft/courses/TableOfContents?courseName=mono-touch">new course on MonoTouch</a> at Pluralsight.</p>
<p>I wanted to take a bit of time here to talk about MonoTouch and to tell you why you should be using it instead of developing iOS applications in Objective-C</p>
<p><a href="http://complextosimple.files.wordpress.com/2011/10/text-monotouch.png"><img style="background-image:none;padding-left:0;padding-right:0;display:block;float:none;margin-left:auto;margin-right:auto;padding-top:0;border-width:0;" title="text-monotouch" src="http://complextosimple.files.wordpress.com/2011/10/text-monotouch_thumb.png?w=175&#038;h=55" alt="text-monotouch" width="175" height="55" border="0" /></a></p>
<h2></h2>
<h2>Flipping directions</h2>
<h2><a href="http://complextosimple.files.wordpress.com/2011/10/gophoto_0197_scanned-image-00363.jpg"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="GoPhoto_0197_Scanned-Image-00363" src="http://complextosimple.files.wordpress.com/2011/10/gophoto_0197_scanned-image-00363_thumb.jpg?w=506&#038;h=334" alt="GoPhoto_0197_Scanned-Image-00363" width="506" height="334" border="0" /></a></h2>
<p>When I first started developing with iOS, I firmly believed that the job should be done using the tools that Apple provided.</p>
<p>I still think it is a very good idea to learn Objective-C and how to develop an iOS application using Objective-C and XCode.</p>
<p>But I am convinced now that overall MonoTouch is the way to go.</p>
<p>Objective-C is a decent language, but it has a fairly steep learning curve for a C# or Java developer.  XCode, the IDE for developing iOS applications, is a decent IDE, but it is not nearly as powerful as MonoDevelop or Visual Studio.</p>
<p>The reality of the situation is that Apple’s development platform is still back in 1990.  Even though there have been some changes and growth, I firmly believe now that Objective-C and the underlying technology cannot ever catch up to .NET or Java.</p>
<p>I don’t say this lightly.  As I said, before I developed a fairly large application in Objective-C.  I authored a <a href="http://www.pluralsight-training.net/microsoft/Courses/TableOfContents?courseName=ios-intro">Pluralsight course on iOS</a> development with Objective-C.  I was pretty convinced this was the way to go until I gave MonoTouch a try.</p>
<h2></h2>
<h2>An unfair test</h2>
<p>I really gave MonoTouch an unfair test, but it passed anyway.  I set out to learn, configure, build a MonoTouch application, and deploy it to the Apple App Store in 1 weekend.</p>
<p>I figured if MonoTouch could pass this test then I would immediately save more than the $400 cost for the software since the next application I was going to build was going to probably take at least a week worth of time to build in Objective-C.</p>
<p>MonoTouch easily passed my test and really exceeded my expectations.</p>
<h2>The main advantage</h2>
<p>By and far the main advantage in using MonoTouch is the language.</p>
<p>C#’s ability to wire up events through event handlers and delegates makes working with iOS so much easier.</p>
<p>There are many situations in iOS where you have to create a special class to act as a delegate for providing behavior for various iOS controls and classes.  In C#, many of these delegate classes can be replaced by a C# delegate or lambda expression.</p>
<p>Another really painful situation in Objective-C is memory management.  If you aren’t used to tracking memory usage it takes a bit to get adjusted to it in Objective-C.  Sure, it really isn’t that hard, but once I started working with C# to build my iOS application, I realized how much faster I could fly through the code without having to even think about it.  (The newer version of Objective-C has somewhat built in memory management, but it is not a true garbage collection implementation.)</p>
<p>Along with C#, you get the full power of the .NET framework.  Almost all of the base class libraries from .NET are available in MonoTouch.  (You basically have the silverlight .NET profile.)</p>
<p>This really comes in handy in 3 main areas:</p>
<ul>
<li>Working with XML</li>
<li>Working with databases</li>
<li>Calling web services</li>
</ul>
<p>If you try to do these things in Objective-C, it is possible, but it will hurt like hell.</p>
<h2>Give it a shot</h2>
<p>If you are interested in developing iOS applications and you haven’t tried MonoTouch, go give it a try.  Trust me, it is worth the effort.  One of the big factors that had me developing Android applications and shying away from iOS was the hurdle of trying to learn and work with Objective-C.</p>
<p>MonoTouch lets you reuse your C# skills without any extra overhead, since the application is compiled down to native ARM assembly code.</p>
<p>If you don’t know where to get started or want to learn a little bit more about MonoTouch, feel free to check out <a href="http://www.pluralsight-training.net/microsoft/courses/TableOfContents?courseName=mono-touch">my course on Pluralsight</a>.</p>
<p>Kudos to the <a href="http://xamarin.com/">Xamarin</a> team for building such a great product!</p>
<p><em>(BTW, that photo is me flipping.  Actually it is a thing I used to call “throwing myself at the ground for dramatic effect.”)</em></p>
<h6>As always, you can subscribe to this <a href="http://feeds.feedburner.com/MakingTheComplexSimple">RSS feed</a> to follow my posts on Making the Complex Simple.  Feel free to check out <a href="http://elegantcode.com/">ElegantCode.com</a> where I post about the topic of writing elegant code about once a week.  Also, you can follow me on twitter <a href="http://twitter.com/jsonmez">here</a>.</h6>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/1408/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1408/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1408/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1408/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1408/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1408/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1408/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1408/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1408/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1408/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1408/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1408/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1408/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1408/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1408&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2011/10/30/monotouch/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2011/10/text-monotouch_thumb.png" medium="image">
			<media:title type="html">text-monotouch</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2011/10/gophoto_0197_scanned-image-00363_thumb.jpg" medium="image">
			<media:title type="html">GoPhoto_0197_Scanned-Image-00363</media:title>
		</media:content>
	</item>
		<item>
		<title>Making Switch Refactorings Better &#8211; Defaultable Dictionary</title>
		<link>http://simpleprogrammer.com/2011/08/14/making-switch-refactorings-better-defaultable-dictionary/</link>
		<comments>http://simpleprogrammer.com/2011/08/14/making-switch-refactorings-better-defaultable-dictionary/#comments</comments>
		<pubDate>Mon, 15 Aug 2011 04:25:52 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[GitHub]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/?p=1379</guid>
		<description><![CDATA[I’ve written before on the idea of refactoring a switch to a Map or Dictionary. There is one major problem that I have been running into though.  Switch statements and dictionaries are not functionally equivalent for one major reason… Switches allow for default I kept struggling with this when I would implement a dictionary to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1379&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I’ve written before on the idea of <a href="http://simpleprogrammer.com/2010/08/17/pulling-out-the-switch-its-time-for-a-whooping/">refactoring a switch</a> to a Map or Dictionary.</p>
<p><img src="http://downloadsoftwarestore.com/software_images/75/63/00046375/English_Dictionary_Toolbar-screenshot.jpg" alt="" width="485" height="364" /></p>
<p>There is one major problem that I have been running into though.  Switch statements and dictionaries are not functionally equivalent for one major reason…</p>
<h2>Switches allow for default</h2>
<p>I kept struggling with this when I would implement a dictionary to replace a switch.  How can I deal with the default case?</p>
<p>There are of course many ways to deal with the default case in a dictionary or map, but I didn’t really like any of the solutions because they either required me to remember to check to see if my entry was in the dictionary before looking it up, or to rely on catching an exception.</p>
<p>Let me give you an example:</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:e177ff43-8154-4138-8f72-5911df394c74" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp; pad-line-numbers: true;">
switch(vegetables)
{
	case Vegetables.Carrot:
		DoCarrotStuff();
		break;

	case Vegetables.Spinach:
		EatIt();
		break;

	case Vegetables.Peas:
		FeedToDog();
		break;

	default:
		Butter();
		Salt();
		SprinkleCheese();
		Eat();
}
</pre></p>
</div>
<p>Converting this to a dictionary we get something like:</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:fc164edc-458d-4cbb-82b7-5fa532b513cf" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
var vegetableActionMap = new Dictionary&lt;Vegetable, Action&gt;
{
	{ Vegetable.Carrot, () =&gt; DoCarrotStuff() },
	{ Vegetable.Spinach, () =&gt; EatIt() },
	{ Vegetable.Peas, () =&gt; FeedToDog() }
}

Action result;
if(!vegetableActionMap.TryGetValue(vegetable, out result)
{
     Butter();
	  Salt();
     SprinkleCheese();
     Eat();
}
else
   result();
</pre></p>
</div>
<p>So clunky, just to handle the default case.</p>
<p>Would be much better do something like this:</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:1e8f4a47-088d-492e-bcea-c864b91b0c7a" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
var vegetableActionMap = new Dictionary&lt;Vegetable, Action&gt;
{
	{ Vegetable.Carrot, () =&gt; DoCarrotStuff() },
	{ Vegetable.Spinach, () =&gt; EatIt() },
	{ Vegetable.Peas, () =&gt; FeedToDog() }
}.WithDefaultValue( () =&gt; { Butter(); Salt(); SprinkleCheese(); Eat(); });

vegetableActionMap[vegetable]();

</pre></p>
</div>
<p>Well now you can!</p>
<p>Enter <a href="https://github.com/jsonmez/Defaultable-Dictionary">DefaultableDictionary</a>!</p>
<p>Also the first thing I ever put on GitHub!</p>
<p>The idea is pretty simple, I am just creating a decorator for IDictionary.</p>
<p>The DefaultableDictionary has a constructor that takes an IDictionary and a default value.</p>
<p>It then delegates all of the methods to the passed in IDictionary reference.  For the methods that look up a value, it handles returning the default if the key doesn’t exist in the dictionary.</p>
<p>I created an extension method that lets you just put a .WithDefaultValue() on the end of your dictionary declaration in order to auto-magically give you a DefaultableDictionary back with that default value.</p>
<h2></h2>
<h2></h2>
<h2>Sleep well my friend</h2>
<p>Knowing that you can not create a dictionary that has a default value which is returned instead of throwing an exception if the key passed in is not found.</p>
<p>I have no doubt that in 3rd world countries children are still starving, but in 1st world countries children with VS Express hacking away at iPhone applications using MonoTouch will not have to catch exceptions from dictionaries that do not know how to just return a default value.</p>
<p><img src="http://www.buzzinn.net/img/bizarre-and-odd/unusual-begging-methods/unusual-begging-methods19.jpg" alt="" width="499" height="375" /></p>
<p>So now there is no excuse!  Refactor those switches!</p>
<h6>As always, you can subscribe to this <a href="http://feeds.feedburner.com/MakingTheComplexSimple">RSS feed</a> to follow my posts on Making the Complex Simple.  Feel free to check out <a href="http://elegantcode.com/">ElegantCode.com</a> where I post about the topic of writing elegant code about once a week.  Also, you can follow me on twitter <a href="http://twitter.com/jsonmez">here</a>.</h6>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/1379/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1379/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1379/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1379/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1379/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1379/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1379/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1379/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1379/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1379/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1379/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1379/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1379/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1379/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1379&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2011/08/14/making-switch-refactorings-better-defaultable-dictionary/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>

		<media:content url="http://downloadsoftwarestore.com/software_images/75/63/00046375/English_Dictionary_Toolbar-screenshot.jpg" medium="image" />

		<media:content url="http://www.buzzinn.net/img/bizarre-and-odd/unusual-begging-methods/unusual-begging-methods19.jpg" medium="image" />
	</item>
		<item>
		<title>Using Var + As, a Neat Little Trick</title>
		<link>http://simpleprogrammer.com/2010/12/16/using-var-as-a-neat-little-trick/</link>
		<comments>http://simpleprogrammer.com/2010/12/16/using-var-as-a-neat-little-trick/#comments</comments>
		<pubDate>Fri, 17 Dec 2010 03:30:18 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Cool Stuff]]></category>
		<category><![CDATA[Language]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/2010/12/16/using-var-as-a-neat-little-trick/</guid>
		<description><![CDATA[Perhaps this is something everyone already knew about, but I recently came across this little C# combo that solves one of my major outstanding issues with the var keyword. I consider var to actually be quite a useful language feature to reduce repetition and make your code slightly more flexible for refactoring, but I’ve always [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1199&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Perhaps this is something everyone already knew about, but I recently came across this little C# combo that solves one of my major outstanding issues with the <em>var</em> keyword.</p>
<p>I consider <em>var</em> to actually be <a href="http://simpleprogrammer.com/2010/05/05/do-you-have-a-case-of-var-guilt/">quite a useful language feature</a> to reduce repetition and make your code slightly more flexible for refactoring, but I’ve always had one little problem with it.</p>
<h2>What if I want a base class type or interface?</h2>
<p>I most often run into this problem when I am working with lists.</p>
<p>Have you ever written some code like this?</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:2be1658f-6da3-40e8-a163-bb81d2e549da" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp; pad-line-numbers: true;">
var myList = new List&lt;int&gt;();
</pre>
</pre>
</div>
<p>&#160;</p>
<p>The problem with this code is that we are stuck with the concrete <em>List</em> implementation for our variable <em>myList</em>, because we don’t have a way of specifying that we actually want an <em>IEnumerable</em> to be our reference type.</p>
<p>The solution is so simple that I am a bit surprised I didn’t think of it earlier.</p>
<p>I had always assumed that I just couldn’t use <em>var</em> there and would have to declare the type like so:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:1f27219b-7100-45b5-ba1c-e6d63af31551" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp;">
IEnumerable&lt;int&gt; myList = new List&lt;int&gt;();
</pre>
</pre>
</div>
<p>&#160;</p>
<p>But we can actually just use <em>as</em> to keep our <em>var</em> in place if we want to.</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:eb2c46c5-7822-4728-8f43-197216f5946a" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp;">
var myList = new List&lt;int&gt; as IEnumerable&lt;int&gt;
</pre>
</pre>
</div>
<p>&#160;</p>
<p>So it’s actually a little more verbose, but I think it is a bit more clear, and it is more consistent if you are using <em>var</em> everywhere else.</p>
<h2>There has to be a better use</h2>
<p>I’ve been racking my brain trying to come up with more useful ways to use this little combo, but I can’t really seem to come up with anything.</p>
<p>It seems like there has to be something else you could use this combo for.</p>
<p>What do you think?&#160; Any ideas?</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/1199/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1199/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1199/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1199/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1199/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1199/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1199/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1199/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1199/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1199/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1199/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1199/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1199/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1199/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1199&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/12/16/using-var-as-a-neat-little-trick/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>
	</item>
		<item>
		<title>Refactoring Switches Advanced</title>
		<link>http://simpleprogrammer.com/2010/10/19/refactoring-switches-advanced/</link>
		<comments>http://simpleprogrammer.com/2010/10/19/refactoring-switches-advanced/#comments</comments>
		<pubDate>Tue, 19 Oct 2010 22:33:50 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[Language]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/2010/10/19/refactoring-switches-advanced/</guid>
		<description><![CDATA[KevDog posted a question in response to my post Pulling out the Switch: It’s Time for a Whooping and I thought it would be good to go ahead and answer it as a post since it is a pretty interesting real world example of a somewhat difficult switch statement to get rid of. Here is [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1142&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>KevDog posted a question in response to my post <a href="http://simpleprogrammer.com/2010/08/17/pulling-out-the-switch-its-time-for-a-whooping">Pulling out the Switch: It’s Time for a Whooping</a> and I thought it would be good to go ahead and answer it as a post since it is a pretty interesting real world example of a somewhat difficult switch statement to get rid of.</p>
<p>Here is the original code.</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:bddab72b-b060-4dab-81da-eb6fd2306400" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp; pad-line-numbers: true;">
public static DataFileParser GetParser(DataFile dataFile)
{
    switch ((FileType)dataFile.ValidationFormat.FileType)
    {
        case FileType.PDF:
            return new PdfParser(dataFile);
        case FileType.Image:
            return new ImageParser(dataFile);
        case FileType.CsvWithHeaderRow:
            return new CsvParser(dataFile, true);
        case FileType.Csv:
            return new CsvParser(dataFile, false);
        default:
            throw new NotImplementedException(&quot;There is no parser for &quot; + 
dataFile.ValidationFormat.FileType.ToString());
    }
}
</pre>
</pre>
</div>
<h2>&#160;</h2>
<h2>Surprisingly simple solution</h2>
<p>Try and say that 3 times fast.</p>
<p>I thought about this a bit and at first was having a hard time coming up with a solution.&#160; Then I typed the code into an editor and realized how easy it is.</p>
<p>The trick here is that it looks like something other than the simple case of data mapping to logic, but it isn’t.</p>
<ul>
<li>The logic in this case is the creation of the Parser.&#160; </li>
<li>The data is the file type. </li>
</ul>
<p>Once you think of it in those terms you can easily solve it using the pattern I mention in my <a href="http://simpleprogrammer.com/2010/08/17/pulling-out-the-switch-its-time-for-a-whooping">previous post on the subject</a>.&#160; </p>
<h2>Switch be gone!</h2>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:300a086f-fb2c-4860-9e51-31c38712f9a7" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp;">
private static Dictionary&lt;FileType, Func&lt;DataFile, DataFileParser&gt;&gt; DataFileTypeToParserCreatorMap = 
    new Dictionary&lt;FileType, Func&lt;DataFile, DataFileParser&gt;&gt;()                                                                                            
{ 
    {FileType.PDF, file =&gt; new PdfParser(file)},
    {FileType.Image, file =&gt; new ImageParser(file)},
    {FileType.CsvWithHeaderRow, file =&gt; new CsvParser(file, true)},
    {FileType.Csv, file =&gt; new CsvParser(file, false)}
};

public static DataFileParser GetParserRefactored(DataFile dataFile)
{
    Func&lt;DataFile, DataFileParser&gt; parserCreator;
    if(!DataFileTypeToParserCreatorMap.TryGetValue(
                             dataFile.ValidationFormat.FileType, 
                             out parserCreator))
        throw new NotImplementedException(&quot;There is no parser for &quot; +
            dataFile.ValidationFormat.FileType.ToString());

    return parserCreator(dataFile);
}
</pre>
</pre>
</div>
<p>&#160;</p>
<p>That is the quickest solution that preserves the existing code as much as possible.</p>
<h2></h2>
<h2>Another solution</h2>
<p>With the first solution we pushed the object creation into the map.</p>
<p>If we can make the constructor for all the parsers the same, we can use reflection to dynamically create our instances by looking up the type in the dictionary.</p>
<p>In this example, I assume that we have refactored CsvParser to have a constructor that only takes one parameter and internally sets a value of usesHeader to false, and we have created a CsvWithHeaderParser that inherits from the CsvParser and sets usesHeader to true.</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:cb9a8fda-0d68-4354-b3a0-8da579bd671e" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp;">
private static Dictionary&lt;FileType, Type&gt; DataFileTypeToParserTypeMap = new Dictionary&lt;FileType, Type&gt;()
{
    { FileType.PDF, typeof(PdfParser)},
    { FileType.Image, typeof(ImageParser)},
    { FileType.CsvWithHeaderRow, typeof(CsvWithHeaderParser)},
    { FileType.Csv, typeof(CsvParser)}                 
};

public static DataFileParser GetParser(DataFile dataFile)
{
    Type parserType;
    if(!DataFileTypeToParserTypeMap.TryGetValue(
            dataFile.ValidationFormat.FileType, 
            out parserType))
        throw new NotImplementedException(&quot;There is no parser for &quot; +
                    dataFile.ValidationFormat.FileType.ToString());

    return (DataFileParser) Activator.CreateInstance(parserType, dataFile);
}

</pre>
</pre>
</div>
<p>&#160;</p>
<p>Pretty similar solution.&#160; I prefer the first though for several reasons:</p>
<ul>
<li>The refactor is localized, where the second solution has to touch other classes. </li>
<li>Reflection makes you lose compile time safety. </li>
<li>You may create a new parser that you want to have more parameters for the constructor.&#160; With the second solution, you will have a hard time doing that. </li>
<li>The first solution gives you ultimate flexibility in setting up the constructor of the parser.&#160; If you wanted to do 5 steps for a particular parser, you could. </li>
</ul>
<p>Anyway, next time you run into a switch statement that is hard to figure out how to refactor, try to break it into a mapping between data and logic.&#160; There is always a solution.</p>
<h6>As always, you can subscribe to this <a href="http://feeds.feedburner.com/MakingTheComplexSimple">RSS feed</a> to follow my posts on Making the Complex Simple.&#160; Feel free to check out <a href="http://elegantcode.com/">ElegantCode.com</a> where I post about the topic of writing elegant code about once a week.&#160; Also, you can follow me on twitter <a href="http://twitter.com/jsonmez">here</a>.</h6>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/1142/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1142/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1142/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1142/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1142/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1142/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1142/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1142/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1142/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1142/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1142/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1142/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1142/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1142/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1142&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/10/19/refactoring-switches-advanced/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>
	</item>
		<item>
		<title>A Simple Wrapper To Make Things More Fluent</title>
		<link>http://simpleprogrammer.com/2010/10/12/a-simple-wrapper-to-make-things-more-fluent/</link>
		<comments>http://simpleprogrammer.com/2010/10/12/a-simple-wrapper-to-make-things-more-fluent/#comments</comments>
		<pubDate>Tue, 12 Oct 2010 15:52:35 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Cool Stuff]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Refactoring]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/2010/10/12/a-simple-wrapper-to-make-things-more-fluent/</guid>
		<description><![CDATA[This post is really a continuation from my last post on using a method that takes an Action to address cross cutting concerns, like logging, without having to go to a full blown AOP implementation. Someone mentioned in the comments that it wasn’t very clear exactly what was going on with the final code.&#160; I [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1135&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This post is really a continuation from my <a href="http://simpleprogrammer.com/2010/10/09/aspect-oriented-programming-with-action/">last post</a> on using a method that takes an <em>Action</em> to address cross cutting concerns, like logging, without having to go to a full blown AOP implementation.</p>
<p>Someone mentioned in the comments that it wasn’t very clear exactly what was going on with the final code.&#160; I tend to agree that this:</p>
<p><strong>LogOnError(_riceCooker.Cook);</strong></p>
<p>… is not very clear.</p>
<p>Really, there are two problems with this code that I can see.</p>
<ol>
<li>It is not clear what this is going to do or whether or not <em>LogOnError</em> or <em>Cook</em> is the method we are concerned about.</li>
<li>It’s not very self-discoverable at all.&#160; If we had a library of useful wrapper methods like these, we wouldn’t have a good intellisense way to know what they are.</li>
</ol>
<p>I can solve both of those issues, but doing so starts to move us into a weird zone where I am not quite sure I feel comfortable.&#160; But, nevertheless, in the name of science…</p>
<p><a href="http://complextosimple.files.wordpress.com/2010/10/wrapped.jpg"><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="wrapped" border="0" alt="wrapped" src="http://complextosimple.files.wordpress.com/2010/10/wrapped_thumb.jpg?w=478&#038;h=327" width="478" height="327" /></a></p>
<h2>Let’s start backwards</h2>
<p>Liking fluent interfaces, here is the kind of syntax that I would prefer to be able to use:</p>
<p><strong>Wrapper.Wrap(_riceCooker.Cook).With.LogOnError();</strong></p>
<p>It is a little bit longer syntax, but I like it for a few reasons:</p>
<ol>
<li>It clearly indicates what is going on here.&#160; We are wrapping a method call using a wrapper.&#160; We are wrapping with a method called <em>LogOnError</em>.</li>
<li>You get intellisense all the way.&#160; The correct implementation of this, should let me Type <em>With</em> + ‘.’ and then see a list of all the possible wrapping methods I have implemented.&#160; This makes the wrapping set of methods self-discoverable.</li>
</ol>
<p>I really like the idea of being able to easily change the functionality of the wrapping just by changing the last part of the line.&#160; For example, if we had implemented a wrapping method that was <em>LogAndAbortOnError(),</em> we could change our code to use that pretty easily.</p>
<p><strong>Wrapper.Wrap(_riceCooker.Cook).With.LogAndAbortOnError();</strong></p>
<p>If we implement this correctly, intellisense will give us our options.</p>
<h2>Making it so</h2>
<p>Creating a fluent syntax in C# can often involve quite a bit of magic and voodoo.&#160; I always like to gather my reagents before embarking on such a journey.</p>
<p>So grab a live chicken, a stapler, and a sharp knife and let’s go!</p>
<p>First step, let’s simplify this.&#160; The <em>With</em> is nice, but it is just for flow, we don’t really need it.&#160; So let’s figure out how to implement our syntax without the <em>With</em> and add it in afterwards.</p>
<p><strong>Wrapper.Wrap(_riceCooker.Cook).LogOnError();</strong></p>
<p>First the easy way.</p>
<ol>
<li>Create a static <em>Wrapper</em> class with a <em>Wrap</em> method that takes an <em>Action</em> and returns an <em>Action</em>.&#160; (We’ll use this to convert whatever we pass in to an <em>Action</em>, so that we can use a Lambda expression or any method call there.)</li>
<li>Create a static extension method that operates on an <em>Action</em>.&#160; Call it <em>LogOnError</em>.</li>
</ol>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:c1efd5ff-3981-41d4-ac9f-e6cba38cbda6" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp; pad-line-numbers: true;">
public static class Wrapper
{
    public static Action Wrap(Action action)
    {
        return action;
    }
        
    public static void LogOnError(this Action action)
    {
        try
        {
            action();
        }
        catch (Exception exception)
        {
            // Log the exception here
        }
    }
}
</pre>
</pre>
</div>
<p>&#160;</p>
<p>Not too bad.&#160; Not a large amount of magic going on here.&#160; Just using an extension method.</p>
<p>But, we already have a problem.&#160; Using a plain old <em>Action</em> is going to give us too many choices in the intellisense drop down.&#160; It could make it hard to know what our real options are and when we try and add the <em>With</em> syntax later, we will need to use a property off of an object we return from the <em>Wrap</em> method.</p>
<h2></h2>
<h2></h2>
<h2></h2>
<h2>Making it better</h2>
<p>We can fix this by actually wrapping the <em>Action</em> with a custom type that we can add our methods to.</p>
<p>Instead of <em>Wrap</em> returning an <em>Action</em>, it will return a <em>WrappedAction</em>.</p>
<p><div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:bb8046ee-1e26-44d7-88bd-a474ed8d1273" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp;">
public static class Wrapper
{
    public static WrappedAction Wrap(Action action)
    {
        return new WrappedAction() {Action = action};
    }
        
    public static void LogOnError(this WrappedAction wrappedAction)
    {
        try
        {
            wrappedAction.Action();
        }
        catch (Exception exception)
        {
            // Log the exception here
        }
    }

    public class WrappedAction
    {
        public Action Action { get; set; }
    }
}
</pre>
</pre>
</div>
<p>Looking better.&#160; Now when we put a ‘.’ at the end of our <em>Wrap</em> call we only see <em>LogOnError</em> as an option.</p>
<p>We can be sure now that if we create an extension method for a <em>WrappedAction</em>, we will make sure that method is self-discoverable.&#160; Before, the generic <em>Action</em> extension&#160; method could make our method show up places that we don’t want it to and can get lost in the other methods on <em>Action</em>.</p>
<h2></h2>
<h2>Making it done</h2>
<p>The last thing we need to do is add the <em>With</em>.</p>
<p>Ideally, when we hit the ‘.’ on the end of the <em>Wrap</em> method, we want to see <em>With</em> as an option.&#160; When we hit the ‘.’ on the end of the <em>With</em> property, we want to see <em>LogOnError</em> as an option.</p>
<p>In order to accomplish this we need to:</p>
<ol>
<li>Add a <em>With</em> property to the <em>WrappedAction</em>.</li>
<li>Have the <em>With</em> property be of a new type (<em>WrappedActionTarget</em>) so that we can add our extension methods for that new type.</li>
<li>Change the extension method to operate on the new type.</li>
</ol>
<p>Here is what we end up with:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:2c3a8ddf-389d-40bb-bc75-56c4aeb0ed07" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp;">
public static class Wrapper
{
    public static WrappedAction Wrap(Action action)
    {
        return new WrappedAction() { Action = action };
    }

    public static void LogOnError(this WrapperMethodTarget target)
    {
        try
        {
            target.WrappedAction.Action();
        }
        catch (Exception)
        {
            Console.Write(&quot;Logging this error&quot;);
        }
    }
}

public class WrapperMethodTarget
{
    public WrappedAction WrappedAction { get; set; }
}

public class WrappedAction
{
    public Action Action { get; set; }

    public WrapperMethodTarget With
    {
        get
        {
            return new WrapperMethodTarget() { WrappedAction = this };
        }
    }
}
</pre>
</pre>
</div>
<p>&#160;</p>
<p>Now we can use the syntax of:</p>
<p><strong>Wrapper.Wrap(_riceCooker.Cook).With.LogOnError();</strong></p>
<p>We can move that <em>LogOnError</em> method out to another class, or create new extension methods somewhere else.&#160; I just put it in there to avoid creating another class.</p>
<h2>Is this really practical?</h2>
<p>I don’t know.&#160; To be honest, I was playing around with creating extension methods that work on Actions and I came up with this way to use them.</p>
<p>I could see making a wrapping library that had different kinds of ways you would wrap method calls built into it.&#160; It could allow you to specify how you log in a configuration and then you would get all of this common stuff automatically.</p>
<p>Even if it is not practical, it’s pretty fun, and it demonstrates the power of <em>Action</em>, or rather functional programming in general.</p>
<h6><strong>As always, you can subscribe to this </strong><a href="http://feeds.feedburner.com/MakingTheComplexSimple"><strong>RSS feed</strong></a><strong> to follow my posts on Making the Complex Simple.&#160; Feel free to check out </strong><a href="http://elegantcode.com/"><strong>ElegantCode.com</strong></a><strong> where I post about the topic of writing elegant code about once a week.&#160; Also, you can follow me on twitter </strong><a href="http://twitter.com/jsonmez"><strong>here</strong></a><strong>.</strong></h6>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/1135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1135/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1135&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/10/12/a-simple-wrapper-to-make-things-more-fluent/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2010/10/wrapped_thumb.jpg" medium="image">
			<media:title type="html">wrapped</media:title>
		</media:content>
	</item>
		<item>
		<title>Aspect Oriented Programming with Action&lt;&gt;</title>
		<link>http://simpleprogrammer.com/2010/10/09/aspect-oriented-programming-with-action/</link>
		<comments>http://simpleprogrammer.com/2010/10/09/aspect-oriented-programming-with-action/#comments</comments>
		<pubDate>Sat, 09 Oct 2010 19:42:06 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Cool Stuff]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[Language]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/2010/10/09/aspect-oriented-programming-with-action/</guid>
		<description><![CDATA[Aspect Oriented Programming (AOP) is a pretty great concept. It is a little difficult to implement though. To be honest, I don’t think I’ve ever really seen it successfully implemented.  I mean sure, I’ve seen examples of how you could use it for “cross-cutting” concerns like logging. The problem is it is usually pretty difficult [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1131&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming">Aspect Oriented Programming</a> (AOP) is a pretty great concept.</p>
<p>It is a little difficult to implement though.</p>
<p>To be honest, I don’t think I’ve ever really seen it successfully implemented.  I mean sure, I’ve seen examples of how you could use it for “cross-cutting” concerns like logging.</p>
<p><a href="http://complextosimple.files.wordpress.com/2010/10/mad_scientist.gif"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="Mad_scientist" src="http://complextosimple.files.wordpress.com/2010/10/mad_scientist_thumb.gif?w=464&#038;h=617" border="0" alt="Mad_scientist" width="464" height="617" /></a></p>
<p>The problem is it is usually pretty difficult to use, and the only real practical application I can ever come up with is logging.  I know, it is probably just my lack of knowledge in the area, but if you bear with me I’ll show you a neat little trick you can use to address cross-cutting concerns by doing something similar to what AOP does using Action&lt;&gt;.</p>
<h2>Putting it all in one place</h2>
<p>The main problem AOP tries to solve is taking aspects of your software that exist in many different places and condensing them into one place for you to maintain.</p>
<p>Exception handling and logging tend to be the most infamous of these cross-cutting concerns.  Many places in your code you no doubt have many instances where you catch an exception and the only thing you can really do is log it.</p>
<p>I’m going to show you a little easy way to do that using Action&lt;&gt;.</p>
<p>Giving credit where credit is due, I got this idea from some code that a coworker of mine, Subha Tarafdar, wrote.  (He is a genius.)</p>
<p>He wrote some code to basically do what I am going to show you, but with retrying database queries.  He was able to reduce many places in the code base where we had repeated logic to retry executing database queries when getting a deadlock or timeout.</p>
<h2>Does this code belong to you?</h2>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:f2d7eb61-812a-4fd5-8561-9629ccd7d142" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp; pad-line-numbers: true;">
public void MakeRice()
{
    try
    {
        _riceCooker.Cook();
    }
    catch (Exception exception)
    {
        // Don't care if this fails,
        // there is nothing we can do about it.
        Logger.Log(exception.Message);
    }
}
</pre></p>
</div>
<p>&nbsp;</p>
<p>Ignore that I am catching a general exception here.  It is a bad practice, but sometimes all you are going to do is log whatever bad thing happens and move on.</p>
<p>It’s pretty common to do something in a try block and catch an exception only to log it.</p>
<p>Think about how many times this code or something similar to it might be sprinkled throughout your code base.</p>
<h2>Action&lt;&gt; to the rescue</h2>
<p>If you’re not familiar with Action&lt;&gt; take a look at <a href="http://simpleprogrammer.com/2010/09/24/explaining-what-action-and-func-are/">this post</a> I did that gives a very simple explanation for how it works.</p>
<p>We can take the logic of the try, catch, and log exceptions and put it into a method that only varies by what action we do.</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:a2364bb0-20c6-4565-9562-ea07d996bc33" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
public static void LogOnFailure(Action action)
{
    try
    {
        action();
    }
    catch (Exception exception)
    {
        Logger.Log(exception.Message);
    }
}
</pre></p>
</div>
<p>&nbsp;</p>
<p><a href="http://simpleprogrammer.com/2010/01/29/static-methods-will-shock-you/">I’m not a big fan</a> of static methods but in certain cases they make sense.  The alternative is to have all of this code sprinkled throughout your code base.</p>
<p>Now that we have this method, we can do anything we want and know that if there is an error it will be logged.</p>
<p>Check this out:</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:75210c50-8eaa-4d5b-805c-8e172cc97c60" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
LogOnFailure(_riceCooker.Cook);
LogOnFailure(KickACat);
LogOnFailure(() =&gt;
                    {
                        Wakeup();
                        SmellTheRoses();
                    }
            );
</pre></p>
</div>
<p>&nbsp;</p>
<p>And if you decide you want to change how you log the error or what you do on it, you can change it all in one place.</p>
<h2>Not just for logging</h2>
<p>You can apply this kind of solution in many places where you have cross cutting concerns in your code base.</p>
<p>Here are a few suggestions for places you might consider this kind of a solution:</p>
<ul>
<li>Retrying on failure logic</li>
<li>Using an alternative service for a failure (web service “A” failed, but we can use web service “B”)</li>
<li>Database connection and connection closing logic.  (Open connection, do something, close connection.)</li>
</ul>
<h6><strong>As always, you can subscribe to this </strong><a href="http://feeds.feedburner.com/MakingTheComplexSimple"><strong>RSS feed</strong></a><strong> to follow my posts on Making the Complex Simple.  Feel free to check out </strong><a href="http://elegantcode.com/"><strong>ElegantCode.com</strong></a><strong> where I post about the topic of writing elegant code about once a week.  Also, you can follow me on twitter </strong><a href="http://twitter.com/jsonmez"><strong>here</strong></a><strong>.</strong></h6>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/1131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1131/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1131&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/10/09/aspect-oriented-programming-with-action/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2010/10/mad_scientist_thumb.gif" medium="image">
			<media:title type="html">Mad_scientist</media:title>
		</media:content>
	</item>
		<item>
		<title>Explaining What Action&lt;&gt; And Func&lt;&gt; Are</title>
		<link>http://simpleprogrammer.com/2010/09/24/explaining-what-action-and-func-are/</link>
		<comments>http://simpleprogrammer.com/2010/09/24/explaining-what-action-and-func-are/#comments</comments>
		<pubDate>Fri, 24 Sep 2010 13:45:45 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Language]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Refactoring]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/2010/09/24/explaining-what-action-and-func-are/</guid>
		<description><![CDATA[In C#, Action&#60;&#62; and Func&#60;&#62; are extremely useful tools for reducing duplication in code and decreasing coupling. It is a shame that many developers shy away from them, because they don’t really understand them. Adding Action&#60;&#62; and Func&#60;&#62; to your toolbox is a very important step in improving your C# code. It’s not really that [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1112&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In C#, Action&lt;&gt; and Func&lt;&gt; are extremely useful tools for reducing duplication in code and decreasing coupling.</p>
<p>It is a shame that many developers shy away from them, because they don’t really understand them.</p>
<p>Adding Action&lt;&gt; and Func&lt;&gt; to your toolbox is a very important step in improving your C# code.</p>
<p>It’s not really that hard to understand what they do and how to use them, it just takes a little patience…</p>
<h2>A simple way of thinking about Action&lt;&gt;</h2>
<p>Most of us are pretty familiar with finding sections of repeated code, pulling that code out into a method and making that method take parameters to represent the differences.</p>
<p>Here is a small example, which should look pretty familiar:</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:dc621ea8-01bd-4a78-8379-89aa2f04ea59" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp; pad-line-numbers: true;">
public void SteamGreenBeans()
{
    var greenBeans = new GreenBeans();
    Clean(greenBeans);
    Steam(greenBeans, Minutes.Is(10));
    Serve(greenBeans);
}

public void SteamCorn()
{
    var corn = new Corn();
    Clean(corn);
    Steam(corn, Minutes.Is(15));
    Serve(corn);
}

public void SteamSpinach()
{
    var spinach = new Spinach();
    Clean(spinach);
    SteamVegetable(spinach, Minutes.Is(8));
    Serve(spinach);
}
</pre></p>
</div>
<p>Each one of these methods pretty much does the same thing.  The only difference here is the type of vegetable and the time to steam it.</p>
<p>It is a simple and common refactor to refactor that code to:</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:a97e2819-4bc8-4119-ba7e-b7d93cf43313" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
public void SteamGreenBeans()
{
   SteamVegetable(new GreenBeans(), 10);
}

public void SteamCorn()
{
    SteamVegetable(new Corn(), 15);
}

public void SteamSpinach()
{
    SteamVegetable(new Spinach(), 8);
}

public void SteamVegetable(Vegetable vegetable, int timeInMinutes)
{
    Clean(vegetable);
    Steam(vegetable, Minutes.Is(timeInMinutes));
    Serve(vegetable);
}
</pre></p>
</div>
<p>Much better, now we aren’t repeating the “actions” in 3 different methods.</p>
<p>Now let&#8217;s imagine we want to do something more than steam.  We need to be able to fry or bake the vegetables.  How can we do that?</p>
<p>Probably we will have to add some new methods for doing that.  So we will end up with something like this:</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:11493288-4249-4d19-bd59-2f776ec9d129" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
public void SteamVegetable(Vegetable vegetable, int timeInMinutes)
{
    Clean(vegetable);
    Steam(vegetable, Minutes.Is(timeInMinutes));
    Serve(vegetable);
}

public void FryVegetable(Vegetable vegetable, int timeInMinutes)
{
    Clean(vegetable);
    Fry(vegetable, Minutes.Is(timeInMinutes));
    Serve(vegetable);
}

public void BakeVegetable(Vegetable vegetable, int timeInMinutes)
{
   Clean(vegetable);
   Bake(vegetable, Minutes.Is(timeInMinutes));
   Serve(vegetable);
}
</pre></p>
</div>
<p>Hmm, lots of duplication again.  No problem.  Lets just do what we did to the first set of methods and make a <em>CookVegetable</em> method.  Since we always clean, then cook, then serve, we should be able to just pass in the method of cooking we will use.</p>
<p>Oh wait, how do we do that?  We can’t just extract out <em>Bake</em> or <em>Fry</em> or <em>Steam</em>, because the <em>Bake</em>, <em>Fry</em> and <em>Steam</em> methods are logic and not data.</p>
<p>Unless… unless we can make them data.  Can we do that?</p>
<p>We sure can, check this out:</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:cefaa6c5-6401-4a74-aa1c-f44e3f0a72d3" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
public void SteamVegetable(Vegetable vegetable, int timeInMinutes)
{
    CookVegetable(vegetable, Steam, timeInMinutes);
}

public void FryVegetable(Vegetable vegetable, int timeInMinutes)
{
    CookVegetable(vegetable, Fry, timeInMinutes);
}

public void BakeVegetable(Vegetable vegetable, int timeInMinutes)
{
    CookVegetable(vegetable, Bake, timeInMinutes);
}

public void CookVegetable(Vegetable vegetable,
   Action&lt;Vegetable, CookingTime&gt; cookingAction,
   int timeInMinutes)
{
    Clean(vegetable);
    cookingAction(vegetable, Minutes.Is(timeInMinutes));
    Serve(vegetable);
}
</pre></p>
</div>
<p>We got rid of the duplicated code the same way we did when we did our first refactor, except this time we parameterized method calls instead of data.</p>
<p>If you understood this, you understand Action&lt;&gt;.  <strong>Action&lt;&gt; is just a way of treating methods like they are data.</strong> Now you can extract all of the common logic into a method and pass in data that changes as well as actions that change.</p>
<p><strong>Congratulations, you are doing the strategy pattern without having to create an abstract base class and a huge inheritance tree!</strong></p>
<p>So when you see Action&lt;&gt;, just think “ah, that means I am passing a method as data.”</p>
<p>It really is as simple as that.</p>
<p>Action&lt;Vegetable, CookingTime&gt; translated to English is: “A method that takes a Vegetable and a CookingTime as parameters and returns void.”</p>
<h2>What about Func&lt;&gt;?</h2>
<p>If you understand Action&lt;&gt;, you understand Func&lt;&gt;.</p>
<p>Func&lt;X, Y, Z&gt; translated to English is: “A method that takes an X, and a Y as parameters and returns a Z&#8221;.”</p>
<p>The only difference between Action&lt;&gt; and Func&lt;&gt; is that Func&lt;&gt;’s last template parameter is the return type.  Func&lt;&gt;s have non-void return values.</p>
<p><strong>Bonus:</strong> Predicate&lt;&gt; is a Func&lt;&gt; that always returns a boolean.</p>
<p>That’s all there is to it.  There really isn’t a need to know much more than that to make sure of Action&lt;&gt; and Func&lt;&gt; in order to start using them.</p>
<p>If you are interested in some other ways to apply Action&lt;&gt; and Func&lt;&gt;, here are some posts I have written which focus on them.</p>
<ul>
<li><a href="http://simpleprogrammer.com/2010/08/17/pulling-out-the-switch-its-time-for-a-whooping/">Pulling out the Switch: It’s Time for a Whooping</a></li>
<li><a href="http://simpleprogrammer.com/2010/06/30/parsing-columns-like-a-ninja/">Parsing Columns Like a Ninja</a></li>
<li><a href="http://simpleprogrammer.com/2010/06/18/the-power-of-func/">The Power of Func&lt;&gt;</a></li>
<li><a href="http://simpleprogrammer.com/2010/02/25/super-combo-map-function-pointer/">Super Combo: Map + Function Pointer</a></li>
</ul>
<h6><strong>As always, you can subscribe to this </strong><a href="http://feeds.feedburner.com/MakingTheComplexSimple"><strong>RSS feed</strong></a><strong> to follow my posts on Making the Complex Simple.  Feel free to check out </strong><a href="http://elegantcode.com/"><strong>ElegantCode.com</strong></a><strong> where I post about the topic of writing elegant code about once a week.  Also, you can follow me on twitter </strong><a href="http://twitter.com/jsonmez"><strong>here</strong></a><strong>.</strong></h6>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/1112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1112/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1112&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/09/24/explaining-what-action-and-func-are/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>
	</item>
		<item>
		<title>Refactoring Step-Wise vs Wrapping and Delegating</title>
		<link>http://simpleprogrammer.com/2010/09/17/refactoring-step-wise-vs-wrapping-and-delegating/</link>
		<comments>http://simpleprogrammer.com/2010/09/17/refactoring-step-wise-vs-wrapping-and-delegating/#comments</comments>
		<pubDate>Fri, 17 Sep 2010 16:03:49 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Legacy Code]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/?p=1104</guid>
		<description><![CDATA[In working with legacy code, I often come across the problem of having to refactor classes that contain static methods, or are entirely static methods. I talked about refactoring helper classes before, but this is slightly different. In this case I want to talk about refactoring classes that you want to keep around, but have [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1104&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In working with legacy code, I often come across the problem of having to refactor classes that contain static methods, or are entirely static methods.</p>
<p>I talked about <a href="http://simpleprogrammer.com/2010/04/14/how-to-refactor-the-helper-class/">refactoring helper classes</a> before, but this is slightly different.</p>
<p>In this case I want to talk about refactoring classes that you want to keep around, but have all or many static members.&#160; A good example of this is some kind of service class that returns data from the database.</p>
<p>It’s not always very clear whether that kind of class really is some sort of helper class.&#160; It is a bit of a judgment call.&#160; If you do find a helper class though, <a href="http://simpleprogrammer.com/2010/04/12/should-i-leave-that-helper-class/">don’t just leave it there</a>.</p>
<p>So, basically if you have determined the class you are working with is going to stay, but it does have static methods and you need to get rid of them, because you are doing dependency injection or mocking, read on.</p>
<h2>Defining the two approaches</h2>
<p>What do I mean by step-wise refactoring?</p>
<p>Here is the basic outline of the first approach:</p>
<ol>
<li>Make the method you need to be non-static, non static. </li>
<li>Add an interface with just that one method in it. </li>
<li>Implement the interface. </li>
<li>Change the references to that method to use the interface instead. </li>
</ol>
<p>Let’s take a look at an example:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:3e715816-2010-49ac-9b88-b8170d8761c3" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp; pad-line-numbers: true;">
public static class LostOrderService
{
    public static IEnumerable&lt;Orders&gt; GetLostOrders(int customerId)
    {        
    }

    public static IEnumerable&lt;Customer&gt; GetCustomerWithLostOrders()
    {
    }
}
</pre>
</pre>
</div>
<p>&#160;</p>
<p>If we are interested in the <em>GetLostOrders</em> method, we can apply steps 1-3 to get:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:1163a834-9009-49e6-a720-ea143c8c47f4" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp;">
public interface ILostOrderService
{
    IEnumerable&lt;Orders&gt; GetLostOrders(int customerId);
}
    
public class LostOrderService : ILostOrderService
{
    public IEnumerable&lt;Orders&gt; GetLostOrders(int customerId)
    {        
    }

    [Obsolete(&quot;If you touch this refactor to make it not static. 
                      Be a man, do the right thing.&quot;)] 
    public static IEnumerable&lt;Customer&gt; GetCustomerWithLostOrders()
    {
    }
}
</pre>
</pre>
</div>
<p>&#160;</p>
<p>Now we can go in and change references in our code for just that one method.</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:6c7852f0-f108-4ff1-a4f1-b53078cf3db6" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp;">
public void ProcessLostOrders()
{
    var orders = LostOrderService.GetLostOrders(_customerId);
    foreach(var order on orders)
    {
        ReprocessOrder();
    }

}

// Refactored becomes:

public void ProcessLostOrders(ILostOrderService lostOrderService)
{
    var orders = lostOrderService.GetLostOrders(_customerId);
    foreach(var order on orders)
    {
        ReprocessOrder();
    }

}
</pre>
</pre>
</div>
<p>&#160;</p>
<p>Now let’s look at the 2nd technique, wrapping and delegating.&#160; Here is the outline of the wrapping and delegating approach:</p>
<ol>
<li>Create a wrapper class that’s going to be used to wrap the static classes calls.</li>
<li>Implement all the methods in the static class as non-static methods in the wrapper class.&#160; Each method just delegates to the static method in the static class.</li>
<li>Create an interface which contains all the methods.</li>
<li>Have the wrapper class implement the interface.</li>
</ol>
<p>Here is an example of doing it this way, given the same original code as the first example:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:6e093146-d38a-4fe8-9954-5870f5cb1f60" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp;">
public interface ILostOrderService
{
    IEnumerable&lt;Orders&gt; GetLostOrders(int customerId);
    IEnumerable&lt;Customer&gt; GetCustomerWithLostOrders()
}

public class LostOrderServiceWrapper : ILostOrderService
{
    public IEnumerable&lt;Orders&gt; GetLostOrders(int customerId)
    {      
        LostOrderService.GetLostOrders(customerId);
    }

    public IEnumerable&lt;Customer&gt; GetCustomerWithLostOrders()
    {
        LostOrderService.GetCustomerWithLostOrders();
    }
}
</pre>
</pre>
</div>
<p>&#160;</p>
<p>The references to the <em>LostOrderService</em> will be refactored exactly the same as in the first example, so I won’t include it here.</p>
<p>You can see in this example, we didn’t touch <em>LostOrderService</em> itself.&#160; Except, you probably want to put an Obsolete attribute on the class to tell users to not use this, but use the wrapper class instead.</p>
<h2>Which is more bettah?</h2>
<p>I’ve tended to use the wrapping and delegating approach in the past, but I am starting to think the step-wise approach is better for a few reasons.</p>
<ul>
<li>The step-wise approach is a bit more obvious to someone later using the class.&#160; When you wrap and delegate, someone has to know there is a wrapper class.&#160; With the step-wise approach, there is no choice.</li>
<li>With the step-wise approach, you are actually getting rid of the <a href="http://simpleprogrammer.com/2010/01/29/static-methods-will-shock-you/">bad and evil static methods</a>.&#160; When you wrap and delegate, you are still leaving them there, just hiding them behind a wrapper.</li>
</ul>
<p>To me, the wrapping approach feels more like I am working around things rather than cleaning them up.&#160; I also feel like someone can see what I started and pick it up from there step-by-step.&#160; Where with the wrapping approach, the mess may never get cleaned up, because there is a workaround.</p>
<h2>Where wrap and delegate shines</h2>
<p>There is a place that wrap and delegate wins hands down though.</p>
<p>If you don’t have control over the source code of the static class or static calls, you cannot do the step-wise approach.</p>
<p>The wrap and delegate approach can be a lifesaver when you are dealing with static references in your code to an external library that you can not change.&#160; You can simply wrap the external library calls and instead reference the wrapper in your code.&#160; Now you can actually unit test that code.</p>
<p>Anytime you are using an external library, you should consider putting some kind of protective wrapper around it.&#160; You never know when you may want to replace it or upgrade the library.&#160; You don’t want to go hunting through all your code looking for references.</p>
<p>So, while either way will work, I prefer to use the step-wise method if I have access to the source code of the static class.</p>
<p>What do you think?&#160; Do you have any other solutions?</p>
<h6>As always, you can subscribe to this <a href="http://feeds.feedburner.com/MakingTheComplexSimple">RSS feed</a> to follow my posts on Making the Complex Simple.&#160; Feel free to check out <a href="http://elegantcode.com/">ElegantCode.com</a> where I post about the topic of writing elegant code about once a week.&#160; Also, you can follow me on twitter <a href="http://twitter.com/jsonmez">here</a>.</h6>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/1104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1104/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1104&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/09/17/refactoring-step-wise-vs-wrapping-and-delegating/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>
	</item>
		<item>
		<title>Pulling out the Switch: It&#8217;s Time for a Whooping</title>
		<link>http://simpleprogrammer.com/2010/08/17/pulling-out-the-switch-its-time-for-a-whooping/</link>
		<comments>http://simpleprogrammer.com/2010/08/17/pulling-out-the-switch-its-time-for-a-whooping/#comments</comments>
		<pubDate>Tue, 17 Aug 2010 16:35:33 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[Learning]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/?p=1050</guid>
		<description><![CDATA[In my previous post I talked about how if-else and switch statements are very similar in that they both ignore the problem of combining data with code. Today I am going to show you how to refactor the switch statements to alleviate that problem. There are some varied opinions on refactoring switch statements which I [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1050&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://simpleprogrammer.com/2010/08/12/switch-is-just-a-fancy-if-else/">previous post</a> I talked about how if-else and switch statements are very similar in that they both ignore the problem of combining data with code.</p>
<p>Today I am going to show you how to refactor the switch statements to alleviate that problem.</p>
<p>There are some varied opinions on refactoring switch statements which I believe derive from trying to treat all switch statements as the same.  I want to look at the kinds of switch statements that exist and why I recommend to refactor each one in a particular way.</p>
<h2>Data to data</h2>
<p>The first most obvious kind of switch statement is one that maps one form of data to another form of data.</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:13096a49-58f2-480c-a676-3c639cc67e98" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
switch (state)
{
    case &quot;Florida&quot;: return &quot;Tallahassee&quot;;
    case &quot;Idaho&quot;: return &quot;Boise&quot;;
    case &quot;Arizona&quot;: return &quot;Phoenix&quot;;
    case &quot;South Carolina&quot;: return &quot;Columbia&quot;;
}
</pre></p>
</div>
<p>This example is clearly mapping one piece of data to another.  The best refactor for this situation is to use a map.  In C# it is a dictionary, in Java a map.</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:054c7c1a-4669-4048-a581-42b7a31a0283" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
var stateToCapitolMap = new Dictionary&lt;string, string&gt;()
{
    {&quot;Florida&quot;, &quot;Tallahassee&quot;},
    {&quot;Idaho&quot;, &quot;Boise&quot;},
    {&quot;Arizona&quot;, &quot;Phoenix&quot;},
    {&quot;South Carolina&quot;, &quot;Columbia&quot;}
};

return stateToCapitolMap[state];
</pre></p>
</div>
<p>I cannot believe how many people argue against this refactoring.  It doesn’t look like much, but we have greatly separated logic from data and increased the maintainability of the code.</p>
<p>Before our refactoring, consider, how you would be able to read all the states and capitols from a file and insert them into the switch statement?  The only possible way would be through code generation.  Clearly this indicates a coupling of code and data.  The switch statement is formatted in such a way that it almost looks like data, but don’t let that fool you, it is code.</p>
<p>Consider the refactored example.  If we want to read the values from a file, it is simple.  So simple, that I’ll even show the code right here.</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:8038cc54-a5be-439f-a919-2c215521fae2" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
var stateToCapitolMap = new Dictionary&lt;string, string&gt;();
foreach (string line in File.ReadAllLines(&quot;StatesAndCapitols.txt&quot;))
{
    string[] stateCapitol = line.Split(',');
    stateToCapitolMap.Add(stateCapitol[0], stateCapitol[1]);
}
return stateToCapitolMap[state];
</pre></p>
</div>
<h2>Data to action</h2>
<p>This kind of switch statement appears different than data to data, but it is actually very similar.  In this case we are mapping some data to a direct action that should be performed given that data.</p>
<p>Often this form of logic can be disguised by multiple actions happening in a case statement.</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:3d0cf63a-7e3d-4d9b-8b9f-0226d85b39c5" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
switch (move)
{
    case &quot;Up&quot;: MoveUp();
        break;
    case &quot;Down&quot;: MoveDown();
        break;
    case &quot;Left&quot;: MoveLeft();
        break;
    case &quot;Right&quot;: MoveRight();
        break;
    case &quot;Combo&quot;:
        MoveUp();
        MoveUp();
        MoveDown();
        MoveDown();
        break;
}
</pre></p>
</div>
<p>We can take the same approach here because really this is a form of mapping data to data.  The second data item is essentially the name of a method to call to perform an action.  We can illustrate this intent easily in C#.  (In Java, you will need to wrap the action into a set of classes with a common interface.)</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:5001517b-9296-44b7-bdd6-d9ff68b8b919" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
var moveMap = new Dictionary&lt;string, Action&gt;()
{
    {&quot;Up&quot;, MoveUp},
    {&quot;Down&quot;, MoveDown},
    {&quot;Left&quot;, MoveLeft},
    {&quot;Right&quot;, MoveRight},
    {&quot;Combo&quot;, () =&gt; { MoveUp(); MoveUp(); MoveDown(); MoveDown(); }}
};

moveMap[move]();
</pre></p>
</div>
<p>What we are essentially doing now is a dynamic look-up of the method to call based on the data.  We could even make this example data driven from a text file that specified how to map a move to a method name or list of method names, but that is far beyond on the scope of this post, and I don’t think I would recommend it unless you have a really good reason.</p>
<h2>Data to multiple actions</h2>
<p>If you are familiar with the techniques of refactoring switch statements, you make be shaking your head by now saying “that guy is wrong, he needs to use a factory.”  Okay, well now we are going to do it.</p>
<p>In the data-to-action refactoring, I opted for the simplest solution that can work, instead of trying to over solve the problem by adding complexity in the form of a factory.</p>
<p>But, what happens when you have multiple switch statements in your code that operate on the same set of data?</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:6dd32826-1880-44f0-86a5-cfb9d5de8bd3" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
switch (move)
{
    case &quot;Up&quot;: MoveUp();
        break;
    case &quot;Down&quot;: MoveDown();
        break;
    case &quot;Left&quot;: MoveLeft();
        break;
    case &quot;Right&quot;: MoveRight();
        break;
    case &quot;Combo&quot;:
        MoveUp();
        MoveUp();
        MoveDown();
        MoveDown();
        break;
}

// ... somewhere else

switch (move)
{
    case &quot;Up&quot;:
        moveName = &quot;Basic Up Move&quot;;
        break;
    case &quot;Down&quot;:
        moveName = &quot;Basic Down Move&quot;;
        break;
    case &quot;Left&quot;:
        moveName = &quot;Basic Left Move&quot;;
        break;
    case &quot;Right&quot;:
        moveName = &quot;Basic Right Move&quot;;
        break;
    case &quot;Combo&quot;:
        moveName = &quot;Up Up Down Down Combo Move&quot;;
        break;
}
</pre></p>
</div>
<p>Sure, we could refactor these both into maps or dictionaries.  But what will happen when we try and add a new move?  We’ll have to remember to add logic in both places or we’ll have a problem.  In the prior example we recognized that data was being mapped to an action, so we represented that as succinctly in code as possible.</p>
<p>In this example, the same data is being mapped to some data that describes a move and actions to perform.  We need some way to house these attributes that belong to the data we are switching on together, and we would like to have this all in one place, so we don’t have to change the code in multiple places.</p>
<p>Our best solution here is to use a factory that gives us the right kind of object that implements the behavior that should be tied to the data we are currently switching on.</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:6f0fe63a-d0cf-4793-8703-b755840c3d78" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
public interface IMove
{
    void DoMove();
    string GetFriendlyName();
}

public class UpMove : IMove
{
    public void DoMove()
    {
        // Do the move
    }

    public string GetFriendlyName()
    {
        return &quot;Basic Up Move&quot;;
    }
}

public static class MoveFactory
{
    private static Dictionary&lt;string, Func&lt;IMove&gt;&gt; moveMap = new Dictionary&lt;string, Func&lt;IMove&gt;&gt;()
    {
        {&quot;Up&quot;, () =&gt; { return new UpMove(); }},
        {&quot;Down&quot;, () =&gt; { return new DownMove(); }},
        {&quot;Left&quot;, () =&gt; { return new LeftMove(); }}
        // ...
    };

    public static IMove CreateMoveFromName(string name)
    {
        return moveMap[name]();
    }
}
</pre></p>
</div>
<p>You can see here that we are creating a factory which contains a dictionary which maps a move name to what kind of object to create.  Each move implements a common IMove interface.  (I only show some of the implementation here.)</p>
<p>Now in our code we can replace those switch statements with polymorphic behavior from our object returned from the factory.</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:927babdb-c0ef-4d42-b7fe-7c5bf99cb31a" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
IMove move = MoveFactory.CreateMoveFromName(name);
move.DoMove();
String friendlyName = move.GetFriendlyName();
</pre></p>
</div>
<p>The nice thing about this implementation is that if we try to add a new move the IMove interface will require us to implement all the proper methods.  We make a change in one place and the compiler reminds us what we need to do.</p>
<h2>Don’t jump straight to the factory</h2>
<p>You may have heard the argument between using a factory or a dictionary for refactoring switch statements before.  What I am trying to show in this blog post is that it depends on your situation.</p>
<p>The simplest solution is a dictionary or map.  Once you have a second place you are mapping the same data, you should move to a factory.  The factory then contains the mapping between a piece of data and a class.</p>
<p>I also wanted to note here that I didn’t use <a href="http://simpleprogrammer.com/2010/02/25/super-combo-map-function-pointer/">enumerations</a>.  In real code you should.  I avoided them here to prevent adding one more layer of abstraction so that my example would not require as much explanation.</p>
<h6>As always, you can subscribe to this <a href="http://feeds.feedburner.com/MakingTheComplexSimple">RSS feed</a> to follow my posts on Making the Complex Simple.  Feel free to check out <a href="http://elegantcode.com/">ElegantCode.com</a> where I post about the topic of writing elegant code about once a week.  Also, you can follow me on twitter <a href="http://twitter.com/jsonmez">here</a>.</h6>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/1050/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1050/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1050/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1050/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1050/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1050/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1050/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1050/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1050/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1050/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1050/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1050/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1050/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1050/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1050&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/08/17/pulling-out-the-switch-its-time-for-a-whooping/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>
	</item>
		<item>
		<title>Parsing Columns Like A Ninja</title>
		<link>http://simpleprogrammer.com/2010/06/30/parsing-columns-like-a-ninja/</link>
		<comments>http://simpleprogrammer.com/2010/06/30/parsing-columns-like-a-ninja/#comments</comments>
		<pubDate>Wed, 30 Jun 2010 14:58:17 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Design]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/?p=975</guid>
		<description><![CDATA[How many times have you written this code? : Or some code like it.  It is pretty common to parse a line and then take each column and store it in your object as data. One of the annoying problems is that if you have optional columns you have to check to see if they [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=975&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>How many times have you written this code? :</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:c825b008-c502-408c-a841-f8487ab26076" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp; pad-line-numbers: true;">
public void CreateFromLine(string line)
{
    var columns = line.split(',');

    this.Name = StripQuotes(columns[0]);
    this.Description = StripQuotes(columns[1]);
    this.Category = StripQuotes(columns[2]);
    this.Stuff = StripQuotes(columns[3]);
    this.MoreStuff = StripQuotes(columns[4]);
    if (columns.Count &gt; 5)
        this.EvenMoreStuff = StripQuotes(columns[5]);
}
</pre></p>
</div>
<p>Or some code like it.  It is pretty common to parse a line and then take each column and store it in your object as data.</p>
<p>One of the annoying problems is that if you have optional columns you have to check to see if they are there before you can parse them.</p>
<p>You’re also repeating your code to strip the quotes off, or whatever other preprocessing you are doing, all over the place.</p>
<p>I know you can use a data driven approach to specify column to property mappings, but I wanted a really low tech, simple solution.</p>
<p>I finally came up with one using one of my favorite C# constructs.</p>
<h2>Action&lt;&gt; is superb for solving these kinds of problems</h2>
<p>See if this code makes you feel any better:</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:caa076af-a3dd-444d-a5ca-934a35961566" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
var propertySetters = new List&lt;Action&lt;string&gt;&gt;
{
    value =&gt; this.Name = value,
    value =&gt; this.Description = value,
    value =&gt; this.Category = value,
    value =&gt; this.Stuff = value,
    value =&gt; this.MoreStuff = value,
    value =&gt; this.EvenMoreStuff = value
};

var columns = line.split(',');

foreach (int columnNumber = 0; columnNumber &lt; columns.Count; columnNumber++)
{
    var propertySetter = propertySetters[columnNumber];
    propertySetter(StripQuotes(columns[columnNumber]);
}
</pre></p>
</div>
<p>It may not seem like much.  It is not really a reduction in code, but we have done a few important things here.</p>
<ul>
<li>Removed the explicit handling of optional columns, since we are now only populating columns that exist.  (Adding a new optional column is as easy as adding one more line to the list.)</li>
<li>Removed the responsibility from the code of explicitly tracking the column numbers.  Column number mapping now is implicit by the order of the columns in the list.</li>
<li>Removed the hidden code duplication of having calls to StripQuotes repeated for each column.</li>
<li>Separated the mapping of properties to columns from the assignment of them.</li>
</ul>
<p>That last point deserves a little more explanation.  Why do we care if we have separated the mapping of properties to columns from the assignment?</p>
<p>The answer is not obvious until you try and use this same code to handle a different set of columns, or columns in a different order.</p>
<p>By separating out the mapping, we can pass the assignment code a different set of mappings, and it will still work.</p>
<p>This allows us to reuse the logic we have in the assignment of the columns to properties instead of rewriting it for other column to property mappings or orderings.</p>
<p><strong>As always, you can subscribe to this </strong><a href="http://feeds.feedburner.com/MakingTheComplexSimple"><strong>RSS feed</strong></a><strong> to follow my posts on Making the Complex Simple.  Feel free to check out </strong><a href="http://elegantcode.com/"><strong>ElegantCode.com</strong></a><strong> where I post about the topic of writing elegant code about once a week.  Also, you can follow me on twitter </strong><a href="http://twitter.com/jsonmez"><strong>here</strong></a><strong>.</strong></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/975/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/975/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/975/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/975/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/975/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/975/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/975/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/975/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/975/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/975/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/975/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/975/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/975/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/975/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=975&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/06/30/parsing-columns-like-a-ninja/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>
	</item>
	</channel>
</rss>
