<?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; Language</title>
	<atom:link href="http://simpleprogrammer.com/category/language/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; Language</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>Add APPLY to Your TSQL Tool Belt</title>
		<link>http://simpleprogrammer.com/2011/09/21/add-apply-to-your-tsql-tool-belt/</link>
		<comments>http://simpleprogrammer.com/2011/09/21/add-apply-to-your-tsql-tool-belt/#comments</comments>
		<pubDate>Wed, 21 Sep 2011 23:56:59 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Language]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/?p=1396</guid>
		<description><![CDATA[Every once in a while I stumble across some SQL keyword that I didn’t really know about, but is extremely useful. The other day I came across APPLY, or rather CROSS APPLY. After reading through documentation on how it works and articles about it, I had a bit of trouble understanding it because I couldn’t [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1396&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Every once in a while I stumble across some SQL keyword that I didn’t really know about, but is extremely useful.</p>
<p>The other day I came across APPLY, or rather CROSS APPLY.</p>
<p>After reading through documentation on how it works and articles about it, I had a bit of trouble understanding it because I couldn’t really find a simple explanation.</p>
<p><a href="http://complextosimple.files.wordpress.com/2011/09/criss-cross_1256682.jpg"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="criss-cross_1256682" src="http://complextosimple.files.wordpress.com/2011/09/criss-cross_1256682_thumb.jpg?w=486&#038;h=678" alt="criss-cross_1256682" width="486" height="678" border="0" /></a></p>
<p>I am going to try to explain it as simply as possible so you can start using it right away.</p>
<h2>How CROSS APPLY works</h2>
<p>The basic idea behind CROSS APPLY is to allow you to join two sets of data together.</p>
<p>If you understand how INNER JOIN works, you already understand CROSS APPLY.</p>
<p>The only difference is CROSS APPLY also allows you to join in a set of data in which that set of data is created or dependent on each row in the first set.</p>
<p>So basically what that means is that for a normal join you would, for example, join two tables that shared a common key.</p>
<p>I could join my customer table to my orders table to see all the orders for a particular customer like so:</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:cd47e942-3bfe-43f5-9c38-4809215fcadd" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: sql; pad-line-numbers: true;">
SELECT *
FROM
 orders o
 JOIN customers c
 	ON o.customerid = c.customerid
WHERE
 c.companyname = 'Around the Horn'
</pre></p>
</div>
<p>Notice how the join is operating on a key that exists independently in each table.</p>
<p>We could rewrite this to be exactly the same using the CROSS APPLY syntax instead like so:</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:fb1fb442-1315-48d7-b276-cbba63836948" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: sql;">
SELECT *
FROM
  orders o
  CROSS APPLY (
    SELECT *  FROM
	   customers c
    WHERE
	   o.customerid = c.customerid) AS c
WHERE
  c.companyname = 'Around the Horn'
</pre></p>
</div>
<p>We can prove these results sets are exactly the same by using EXCEPT to make sure there are no rows in one set that aren’t in the other and then flipping it, like so:</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:28630bf4-dcf0-4411-8a68-7bf8ab42e464" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: sql;">
SELECT *
FROM
    orders o
    CROSS APPLY (SELECT *
                 FROM
                     customers c
                 WHERE
                     o.customerid = c.customerid) AS c
WHERE
    c.companyname = 'Around the Horn'

EXCEPT
SELECT *
FROM
    orders o
    JOIN customers c
        ON o.customerid = c.customerid
WHERE
    c.companyname = 'Around the Horn'
</pre></p>
</div>
<p>Just run this exact query again swapping the SQL above the EXCEPT with the SQL below and make sure it has no results as well.  If both of those queries have no results, then you know the results from each query are the same since EXCEPT will show any results that are in the top query but not in the bottom one.</p>
<h2>So when is CROSS APPLY useful?</h2>
<p>Remember how I said it can do more than a simple join?  Joins are restricted to only joining two sets of data that could be queries independently of each other.</p>
<p>What if I said give me the three most recent orders for each customer?</p>
<p>Take a minute and think about how you would write that query.  Go ahead and try to do it.  I’ll wait.</p>
<p>There are a few ways to do it without using CROSS APPLY, but none of them are really very easy or perform very well.</p>
<p>Using CROSS APPLY it is simple though:</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:16f748f4-45f4-497e-8c9b-d47d601d4635" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: sql;">
SELECT *
FROM
    customers c
    CROSS APPLY (
                 SELECT TOP 3 o.orderdate
                            , o.shipcity
                 FROM
                     orders o
                 WHERE
                     o.customerid = c.customerId
order by o.orderdate desc
) as top3;
</pre></p>
</div>
<p>So CROSS APPLY is useful whenever you have some data that you would want to be able to join against, but are forced to do some kind of sub-query instead because the data you are trying to join is not going to map well against a single key.</p>
<p>The other instance in which CROSS APPLY will be useful is when you are  doing a sub-select that has more than one value you would like to use in your final query.</p>
<p>For example if you were sub-selecting from an Order Details table to match up order ids that had a Quantity greater than 5, that sub-select would need to return exactly one column in order for you to use it in your where clause.  If you wanted to use other columns from the sub-select, you would have to do another sub-select for each of these columns.</p>
<p>If you first try to rewrite the sub-select as a JOIN and find that you can’t, you may be able to write it as a CROSS APPLY.</p>
<h2>How to know when to use CROSS APPLY</h2>
<p>There isn’t a good solid rule you can use to identify when you should use a CROSS APPLY but having the knowledge of CROSS APPLY and how it works can help you when you are trying to tune queries and you are having a difficult time constructing one.  It is another option you can try.</p>
<p>Here are some general guidelines of times when you might want to use CROSS APPLY:</p>
<ul>
<li>A query where the result set you want to JOIN against is in some way related to the data in the first set.  (Example: one column in the first table tells you how many rows in the 2nd table to get)</li>
<li>A query where you are doing a sub-query, but need more than one value from the sub-query</li>
<li>Anywhere you are using a Common Table Expression (CTE) could possibly be rewritten as a CROSS APPLY</li>
<li>A query that has a large set of data it is joining against and then filtering out.  You can change it to a CROSS APPLY that does the filter in the CROSS APPLY statement.</li>
<li>Any time you are trying to join against a table function (this is actually what CROSS APPLY was created for.)</li>
</ul>
<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/1396/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1396/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1396/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1396/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1396/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1396/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1396/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1396/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1396/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1396/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1396/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1396/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1396/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1396/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1396&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2011/09/21/add-apply-to-your-tsql-tool-belt/feed/</wfw:commentRss>
		<slash:comments>6</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/09/criss-cross_1256682_thumb.jpg" medium="image">
			<media:title type="html">criss-cross_1256682</media:title>
		</media:content>
	</item>
		<item>
		<title>Getting up to BAT: Building a True DSL</title>
		<link>http://simpleprogrammer.com/2011/05/14/getting-up-to-bat-building-a-true-dsl/</link>
		<comments>http://simpleprogrammer.com/2011/05/14/getting-up-to-bat-building-a-true-dsl/#comments</comments>
		<pubDate>Sun, 15 May 2011 03:24:52 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Automation]]></category>
		<category><![CDATA[BAT]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[Language]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/2011/05/14/getting-up-to-bat-building-a-true-dsl/</guid>
		<description><![CDATA[If you’ve made it this far with your BAT implementation, you have finally arrived. Not to say that you’ll ever be done expanding your automation framework and building and improving your BATs, but you are at the point of having a mature usable BAT framework and you can be proud of that accomplishment. If you [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1329&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>If you’ve made it this far with your BAT implementation, you have finally arrived.</p>
<p>Not to say that you’ll ever be done expanding your automation framework and building and improving your BATs, but you are at the point of having a mature usable BAT framework and you can be proud of that accomplishment.</p>
<p>If you truly want to see where the rabbit hole goes though… Read on</p>
<h2>Taking it to 11</h2>
<p><a href="http://complextosimple.files.wordpress.com/2011/05/spinal_tap_but_it_goes_to_eleven.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="spinal_tap_but_it_goes_to_eleven" border="0" alt="spinal_tap_but_it_goes_to_eleven" src="http://complextosimple.files.wordpress.com/2011/05/spinal_tap_but_it_goes_to_eleven_thumb.jpg?w=485&#038;h=273" width="485" height="273" /></a></p>
<p>If you have designed a good automation framework for writing your BATs, you will most likely have created an internal domain specific language (DSL).</p>
<p>What is an internal DSL?</p>
<p>Basically it is a set of APIs and rules built in another language that function as their own language.</p>
<p>You might have some code that looks like this:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:08f381ea-bda8-4f72-ab40-6ac923941fc7" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp; pad-line-numbers: true;">
Pages.Login.Goto();
Pages.Login.LoginWithDefaultUser();
Pages.Customers.Goto();
Pages.Customers.AddNewCustomer();
</pre>
</pre>
</div>
<p>&#160;</p>
<p>You can see how this code is really looking like a language itself.&#160; It is hard to tell if this code is even C# or Java.</p>
<p>This is a good example of an internal DSL.</p>
<p>If we were to take this same section of a BAT test and write it as an external DSL, it might look something like this:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:521b3b0f-ee9e-4256-8083-4b36a0085593" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: plain;">
LOGIN WITH DEFAULT-USER
ADD-CUSTOMER WITH DEFAULT-CUSTOMER

</pre>
</pre>
</div>
<p>&#160;</p>
<p>With a true DSL we can simplify even further to get right down to the bare minimum set of commands we need to execute what we want in our application.</p>
<h2>How to implement a DSL?</h2>
<p>There are a number of tools and techniques that can be used to create a DSL.&#160; I’ll hit on some of those a bit later on, but first we need to design the DSL itself.</p>
<p>Designing a DSL can be challenging, but I have found the best approach is to use a similar approach to what we used to <a href="http://simpleprogrammer.com/2011/03/16/getting-up-to-bat-designing-an-automation-framework/">design our automation framework</a>.</p>
<p>It is best to work backwards from the syntax that would make your BAT the easiest to write and the most clear.&#160; Once you have done that you can worry later about implementing the DSL to support the syntax you have come up with.</p>
<p>You should focus on creating a limited vocabulary for your DSL so that it will be easy for someone to learn and know what their options are.</p>
<p>The more restrictions we put into a DSL the easier that DSL becomes for doing a specific purpose.</p>
<p><strong>We want to give the user of a DSL no more options than required for what they want to do and no less.</strong></p>
<p>This isn’t always easy to do.&#160; It often requires some careful thought and refinement.</p>
<p>Your DSL should also use terminology and phrases that are familiar to the business domain of your application.&#160; By doing this you will make it so someone understanding your application will understand BATs written in that DSL.</p>
<p>I also always try to make a BAT DSL read as much as plain English as possible.</p>
<p>Once you have designed the DSL, you will need a way to implement it.&#160; </p>
<p>I’ve written about <a href="http://simpleprogrammer.com/2010/03/10/internal-dsl-becomes-external-dsl/">using ANTLR to create an external DSL</a>.&#160; Also I have written a review on a <a href="http://simpleprogrammer.com/2010/04/16/book-review-the-definitive-antlr-reference-building-domain-specific-languages/">book that I recommend for learning ANTLR</a>.</p>
<p>Microsoft also has a <a href="http://archive.msdn.microsoft.com/vsvmsdk">DSL SDK you can use in VS2010</a>, although I haven’t used it myself.</p>
<p>The basic idea behind implementing a DSL is that you have to take some sort of grammar you design for your DSL, parse it into a syntax tree, then use that tree to generate code that will actually perform the actions.</p>
<p>It is by no means a trivial task, but using a tool like ANTLR, makes it much simpler than trying to completely generate a parser and execution engine yourself.</p>
<h2>Why even bother?</h2>
<p>Creating a DSL for your BATs is completely optional, but there are some significant benefits to doing so.</p>
<p>The biggest one I have found is that you are much more likely to get business people to write BATs if you have a simple DSL they can use to create them.&#160; Once you get everyone using BATs to define behavior and requirements, communication becomes much more simple.</p>
<p>Another great thing about creating a DSL is that you can create a runner that can interpret the DSL BAT scripts which can be run on any machine.&#160; Typically, to run BATs created in Java or C#, you would need a C# or Java compiler and a test runner, etc.&#160; By creating a DSL and a stand alone executor, you can very easily allow anyone to run BATs with little to no setup.</p>
<p>Writing your BATs in a DSL will also make writing the BATs and understanding them much easier.&#160; A good DSL can get rid of all the little language and API nuances that don’t really add information to the specific domain you are working in.&#160; A good DSL strips information down to the minimum amount needed and is able to do so, because it assumes the context is your application’s business domain.</p>
<p>You will also find that you are better able to separate framework from tests when you have a DSL in place.&#160; One issue that many teams face when creating a BAT framework is that some people come along and write lower level code in the higher level BATs.&#160; This creates a problem because it is hard to force someone to use the higher level API when the framework and the BAT code are the same language.</p>
<h2>Wrapping it up</h2>
<p>So that completes my series on Getting up to BAT.</p>
<p>Hopefully you have learned enough to be able to implement your own BAT framework and get BATs running for your application.</p>
<p>I tried to cover most of the important steps here without getting too deep into the details.</p>
<p>If you have any questions or are interested in getting more in depth training or consulting on getting BATs setup for your environment, send me an email or leave a comment.</p>
<p>It can be a little difficult to get started and get a BAT framework up and running, but the rewards are well worth the effort!</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/1329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1329/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1329/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1329/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1329/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1329/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1329/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1329/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1329&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2011/05/14/getting-up-to-bat-building-a-true-dsl/feed/</wfw:commentRss>
		<slash:comments>2</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/05/spinal_tap_but_it_goes_to_eleven_thumb.jpg" medium="image">
			<media:title type="html">spinal_tap_but_it_goes_to_eleven</media:title>
		</media:content>
	</item>
		<item>
		<title>Published My First Course on Pluralsight</title>
		<link>http://simpleprogrammer.com/2011/04/12/published-my-first-course-on-pluralsight/</link>
		<comments>http://simpleprogrammer.com/2011/04/12/published-my-first-course-on-pluralsight/#comments</comments>
		<pubDate>Wed, 13 Apr 2011 04:27:51 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Cool Stuff]]></category>
		<category><![CDATA[Language]]></category>
		<category><![CDATA[Self Improvement]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/?p=1305</guid>
		<description><![CDATA[My number of blog posts in the last couple of months has definitely been a little lower than I like, but I have a pretty good reason. I just got my first course published on Pluralsight! The course is called Android Development for .NET Developers and it covers most of the basic knowledge you would [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1305&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>My number of blog posts in the last couple of months has definitely been a little lower than I like, but I have a pretty good reason.</p>
<p>I just got my first course published on <a href="http://www.pluralsight-training.net/microsoft/">Pluralsight</a>!</p>
<p><a href="http://complextosimple.files.wordpress.com/2011/04/logomedium1.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="logomedium" src="http://complextosimple.files.wordpress.com/2011/04/logomedium_thumb.png?w=233&#038;h=56" border="0" alt="logomedium" width="233" height="56" /></a></p>
<p>The course is called <a href="http://www.pluralsight-training.net/microsoft/OLT/Course/Toc.aspx?n=android-intro">Android Development for .NET Developers</a> and it covers most of the basic knowledge you would need to go from knowing nothing about Android development to being able to create a fairly simple application and publish that application to the Android Market.</p>
<p>If you haven’t checked out <a href="http://www.pluralsight-training.net/microsoft/">Pluralsight</a>, it is a really good site for a wide variety of developer training videos.  They really managed to get some very good content on the site and there are videos on just about every .NET topic you can think of.</p>
<p>I have also really enjoyed working with the guys that run Pluralsight, they are all very friendly and very knowledgeable.  Thanks to <a href="http://twitter.com/elegantcoder">David Starr</a> and <a href="http://twitter.com/fritzonion">Fritz Onion</a> for all their help getting my course ready and published.</p>
<h2>You never really learn something till you teach it</h2>
<p><a href="http://complextosimple.files.wordpress.com/2011/04/teacher-point.gif"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="teacher-point" src="http://complextosimple.files.wordpress.com/2011/04/teacher-point_thumb.gif?w=462&#038;h=425" border="0" alt="teacher-point" width="462" height="425" /></a></p>
<p>This simple truth became more apparent to me than ever during the process of making this course.</p>
<p>I thought I had a pretty good understanding of the Android fundamentals, having published a fairly complex application, <a href="http://simpleprogrammer.com/2011/01/04/introducing-pacemaker-for-android/">PaceMaker</a>.</p>
<p>What I became quickly aware of is that there is a huge difference between having knowledge and having understanding.</p>
<p>I equate knowledge as possessing a formula to be able to do something, but lacking knowing why or how to make modifications to the process.</p>
<p>Cooking provides an excellent example of this.  There are many people in the world who know how to cook a large number of dishes.  But many of these people only have the knowledge of cooking.  They have a large collection of recipes which they can follow to produce the desired result.</p>
<p>A professional chef on the other hand, has a true understanding of cooking.  This person might have knowledge of many recipes, but they also understand why the particular ingredients are used and can make modifications to those ingredients and steps.  They may even create something without preset steps because they understand what they are doing, not just have knowledge about it.</p>
<p>It was great to have the experience of creating these videos because I was able to acquire an in-depth understanding of Android development, not just a knowledge of what to do.</p>
<p>If you ever have the opportunity to teach, I definitely recommend you take that opportunity.  Even if you don’t think you are qualified to teach a subject, by the time you have prepared what you are going to teach, you will be qualified.  Trial by fire perhaps, but well worth the outcome.  Plus you’ll be helping others in the process.</p>
<h2>Much harder than I thought</h2>
<p>I do have to admit though, recording training videos is definitely much harder than I had originally anticipated.</p>
<p>In order to get 40 minutes of video, it might take 6 hours worth of work or even more depending on the prep work involved and how much editing after getting the raw footage.</p>
<p>I really expected that it would take about as much time as it takes to record something to produce that something, but I definitely learned that is not the case.</p>
<p>I often found that I had to draw a line and stop trying to refine a video because you can literally spend an unlimited amount of time editing and tweaking a video.</p>
<p>Another revelation that might be apparent to everyone else, but was quite an epiphany to me was that you can edit “umms” out of video very easily.  You can’t even notice where they are cut out!  My first video, I didn’t even realize I could edit anything, and I ended up taking like 50 cuts until I could get it right.</p>
<h2>Overall though, great experience, lots of fun</h2>
<p>I felt like I&#8217;ve been stretched in a different direction, as I had never done any video or audio recording before and had never really spent much time in a room talking to myself pretending to talk to other people, but it was a good kind of stretching.</p>
<p>I really actually enjoyed the process and I will definitely be doing more of this kind of work in the future.  Probably going to take a bit of a break before I start my next course though.  I want to make sure I take some time to get a good retrospective of the process and sharpen my saw a bit so my next videos can be even better.</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/1305/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1305/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1305/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1305/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1305/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1305/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1305/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1305/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1305/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1305/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1305/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1305/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1305/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1305/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1305&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2011/04/12/published-my-first-course-on-pluralsight/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://complextosimple.files.wordpress.com/2011/04/logomedium_thumb.png" medium="image">
			<media:title type="html">logomedium</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2011/04/teacher-point_thumb.gif" medium="image">
			<media:title type="html">teacher-point</media:title>
		</media:content>
	</item>
		<item>
		<title>Solving Problems, Breaking it Down</title>
		<link>http://simpleprogrammer.com/2011/01/08/solving-problems-breaking-it-down/</link>
		<comments>http://simpleprogrammer.com/2011/01/08/solving-problems-breaking-it-down/#comments</comments>
		<pubDate>Sat, 08 Jan 2011 22:46:43 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Career]]></category>
		<category><![CDATA[Language]]></category>
		<category><![CDATA[Learning]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/2011/01/08/solving-problems-breaking-it-down/</guid>
		<description><![CDATA[Right before the holidays, I said that you had better learn how to solve programming problems. This time I am going to try and give you some good tools to enable you to get good at solving programming problems.&#160; (Really algorithm type problems specifically.) Common mistakes When most programmers are given a programming problem in [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1219&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Right before the holidays, I said that <a href="http://simpleprogrammer.com/2010/12/22/solving-problems-you-better-learn-how/">you had better learn how to solve programming problems</a>.</p>
<p>This time I am going to try and give you some good tools to enable you to get good at solving programming problems.&#160; (Really algorithm type problems specifically.)</p>
<h2>Common mistakes</h2>
<p><a href="http://complextosimple.files.wordpress.com/2011/01/lolcatthink.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="lolcatthink" border="0" alt="lolcatthink" src="http://complextosimple.files.wordpress.com/2011/01/lolcatthink_thumb.jpg?w=469&#038;h=439" width="469" height="439" /></a></p>
<p>When most programmers are given a programming problem in an interview, they make several key mistakes.&#160; The most severe of those is the improper allocation of time.</p>
<p>If you have heard the saying “measure twice and cut once,” then you are probably familiar with the idea of spending upfront time to make sure something is done right, rather than diving right in.</p>
<p>The most common mistake I see when conducting interviews or watching someone try to solve a programming problem is they try to start writing code as soon as possible.</p>
<p><strong>You must resist this urge.</strong></p>
<p>You really want to make sure you take enough time to understand the problem completely before attempting to solve it.</p>
<p>Another big mistake is trying to over solve the solution on the first iteration.&#160; Keep it simple, don’t try to get fancy.</p>
<h2>A simple set of steps</h2>
<p>I am going to give you a simple set of steps to follow which you can use for any algorithm type programming problem.</p>
<ol>
<li>Read the problem completely twice.</li>
<li>Solve the problem manually with 3 sets of sample data.</li>
<li>Optimize the manual steps.</li>
<li>Write the manual steps as comments or pseudo-code.</li>
<li>Replace the comments or pseudo-code with real code.</li>
<li>Optimize the real code.</li>
</ol>
<p><strong>As much as 70% of our time should be spent in steps 1-3.</strong></p>
<p>Let’s look at each step.</p>
<h2>Read the problem completely twice</h2>
<p>This is the single most important step.&#160; You may even want to read the problem 3 or 4 times.</p>
<p>You want to make sure you completely understand the problem.&#160; A good test of this is whether or not you can explain the problem to someone else.</p>
<p><strong>I cannot over-emphasize how important this step is!</strong></p>
<p>If you don’t understand the problem, you cannot solve it.&#160; Do not worry about wasting time here, because the better you understand the problem, the easier it will be to solve it.</p>
<p>If you are given any examples along with the problem, make sure you have worked through the examples and understand why the answers are correct for each one.</p>
<h2>Solve the problem manually</h2>
<p>I am going to tell you perhaps the biggest secret in programming.</p>
<blockquote><p><strong>“Nothing can be automated that cannot be done manually!”</strong></p>
</blockquote>
<p>Programming is automation plain and simple.&#160; You may have the ability to skip the manual steps and jump directly to code, but there is a manual process which is the foundation of any code you write.</p>
<p>It is very important to solve the problem manually first, so that you know what you are going to automate, otherwise you are just slinging code around.&#160; Which while can be fun, will make you look like an idiot in a programming interview and will probably cause you to sweat profusely.</p>
<p>I recommend that you solve the problem with at least three different inputs to make sure you really understand your solution and that it will work for more than one case.</p>
<p>I often use a <a href="http://en.wikipedia.org/wiki/Mathematical_induction">Mathematical Induction</a> approach if possible.&#160; Using this approach I might try and solve for 1 first, then for 2, then for n.</p>
<p>Also don’t forget to look for corner cases and edge cases and do any examples for those kind of cases you can think of.</p>
<p>It’s very important that when you solve a problem manually, you recognize what your brain is actually doing to solve the problem.&#160; You may need to write out all the things you are normally storing in your head.&#160; You want to be aware of each step, it is easy to gloss over them.</p>
<p>Let’s look at a very basic example, reversing a string.</p>
<p>If I give you a string “Zebra”, and ask you to reverse it, most people will do the following manual steps.</p>
<ul>
<li>Write “Zebra” down.</li>
<li>Start a new word, and put “a” as the first letter.&#160; (Why –&gt; because it is the last letter, we want to start here)</li>
<li>Put “r” down as the 2nd letter.&#160; (Why –&gt; because it is the next letter backwards from the last letter we copied)</li>
<li>Put “b” down as the 3rd letter.&#160; (Why –&gt; same as above)</li>
<li>Etc</li>
</ul>
<p>Notice how I write down each little step and why.</p>
<h2></h2>
<h2>Optimize the manual solution</h2>
<p>People often don’t realize how valuable this step is.&#160; It is much easier to rearrange and reconstruct and idea or algorithm in your head than it is in code.</p>
<p>It’s well worth the effort to try and optimize the actual solution or simplify it when it is still in the most easily malleable state.</p>
<p>What you want to do here is figure out if there is another way you can solve the problem easier, or if there are some steps you can cut our or simplify.</p>
<p>Let’s look at our string reversal example and see if we can simplify the steps.</p>
<p>We should be able to immediately recognize that we can use a loop here to reduce the manual steps.&#160; Our duplicate why’s for most of our steps tell us that we are doing the same thing over and over for each step, just with different data.</p>
<ol>
<li>Write “Zebra” down.</li>
<li>Start at the last letter in the word and create a new empty word.</li>
<li>Append the current letter to the new word</li>
<li>If there is a previous letter, make the previous letter the current letter and start back at 3.</li>
</ol>
<p>Look how close we are getting to code at this point.&#160; You should be tempted to actually write the code for this.&#160; That is good, it tells you that you have solved and simplified the problem well.&#160; Writing code should now become very easy.</p>
<h2>Write pseudo-code or comments</h2>
<p>Many times you can skip this step if you have a really good handle on the problem or your previous steps already created a detailed enough description of the solution that coding it is already a 1 to 1 translation.</p>
<p>If you are a beginner or struggle with these kinds of problems, I would go ahead and take the time to do this step anyway though.</p>
<p>What we want to do here is capture all the steps we created and now either put them into our editor as comments or write them as psuedo-code that we can translate to real code.</p>
<p>By doing this, we can know exactly what the structure of the code we are going to write is going to look like which makes the job of filling in the actual code later trivial.</p>
<p>Let’s look at some psudeo-code for reversing a string.</p>
<blockquote><p>// NewWord = “”</p>
<p>// Loop backwards through word to reverse</p>
<p>//&#160;&#160; NewWord += CurrentLetter</p>
<p>// Return NewWord</p>
</blockquote>
<p>Pretty simple, but the key thing we have done here is outlined the structure of the code we will write to solve the problem.</p>
<h2>Replace comments with real code</h2>
<p>This step should be extremely easy at this point.&#160; If you have done all the other steps, this step involves no problem solving at all.</p>
<p>All we do here is take each comment and convert it into a real line of code.</p>
<p>Taking the string reversal, we might end up with something like this.</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:acf0e9a4-4d47-4ca9-9424-d9c7d7b9badb" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp; pad-line-numbers: true;">
String newWord =””
for(int index = oldWord.Length – 1; index &gt;= 0; index—)
   newWord += oldWord[index];
return newWord;

</pre>
</pre>
</div>
<p>&#160;</p>
<p>1 for 1 translation of the comments we created above for real code.</p>
<p>If you struggle here, there are usually two possible reasons:</p>
<ol>
<li>You didn’t break down the problem into small enough steps</li>
<li>You don’t know your programming language well enough to do the conversion</li>
</ol>
<p>If you didn’t break the problem down enough, try going back to the second step and being as meticulous as possible.&#160; Write out each and every single step.&#160; I know it is a pain, but do it, believe me it will be worth the effort.</p>
<p>If you don’t know your programming language well enough to do the translation, you may need to brush up here on some basic constructs.&#160; Any language you expect to be able to solve algorithm type problems in, you should know how to do the following things:</p>
<ul>
<li>Create a list</li>
<li>Sort a list or array</li>
<li>Create a map or dictionary</li>
<li>Loop through a list, or dictionary</li>
<li>Parse strings</li>
<li>Convert from string to int, int to string, etc</li>
</ul>
<p><strong>If you don’t know how to do all of these things.&#160; Stop what you are doing now and learn them. </strong> It’s not a very long list, and the benefits will be profound.</p>
<h2>Optimize the real code</h2>
<p>Sometimes this step isn’t necessary, but it’s worth taking a look at your code and figuring out if you can cut out a few lines or do something simpler.</p>
<p>This is also a good place to make sure all your variables are named with long meaningful names.&#160; I cannot stress enough how important having good names for your variables and methods is for helping the person evaluating your code to understand what you were trying to do.&#160; This is especially important when you make a mistake!</p>
<p>I won’t give an optimization for our trivial example of a string reversal, but a word of advice here is not to get too tricky.&#160; Just try to mainly simplify your code and get rid of duplication.</p>
<h2>A few final tips</h2>
<p>If you follow this template for solving algorithm type problem, you should do very well in programming interviews, but the key to doing so is having confidence in this process.</p>
<p>The only way you are going to have confidence in this process is to practice it.&#160; It takes a good amount of faith to believe that spending 70% of your 30 minutes to solve a problem just thinking about the problem and not writing any code is the right approach, so make sure you have that faith when you need it.</p>
<p>I’ve talked about using <a href="http://simpleprogrammer.com/2010/04/02/so-you-want-to-become-a-better-programmer-topcoder/">TopCoder</a> to become a better programmer before, and I still recommend it.&#160; <a href="http://codility.com/">Codility.com</a> is another great site I have recently been introduced to.</p>
<p>There is one important step I did not include in the outline above, because I didn’t want to make the process any more complicated than it needed to be.</p>
<p>Many times you will find that a problem itself involves multiple large steps or is very complicated.&#160; In those instances, you will want to try and find a way to cut the problem directly in half and then following the process above for each half.</p>
<p>This method of tackling a problem is called “divide and conquer&quot; and is quite effective.&#160; A good way to know where to break a problem in half is to think about what part of the problem if already given to you would make solving the rest easy.</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/1219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1219/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1219&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2011/01/08/solving-problems-breaking-it-down/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/01/lolcatthink_thumb.jpg" medium="image">
			<media:title type="html">lolcatthink</media:title>
		</media:content>
	</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>Back To Basics: Sorting</title>
		<link>http://simpleprogrammer.com/2010/12/07/back-to-basics-sorting/</link>
		<comments>http://simpleprogrammer.com/2010/12/07/back-to-basics-sorting/#comments</comments>
		<pubDate>Wed, 08 Dec 2010 01:33:28 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[Language]]></category>
		<category><![CDATA[Learning]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/2010/12/07/back-to-basics-sorting/</guid>
		<description><![CDATA[Why is sorting so hard? One of the most common misunderstandings and frustrations I see from developers is around sorting. Almost every developer has faced needing to sort a list of things in some manner in their development careers.&#160; Many developers end up fumbling through it, looking for an example from the web and then [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1190&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Why is sorting so hard?</p>
<p>One of the most common misunderstandings and frustrations I see from developers is around sorting.</p>
<p>Almost every developer has faced needing to sort a list of things in some manner in their development careers.&#160; Many developers end up fumbling through it, looking for an example from the web and then copying that example, not really knowing what they did or why it works.</p>
<p>If you fall into that category, or just want to know a little better how sort works, stay tuned, we are going to make it simple.</p>
<p><a href="http://complextosimple.files.wordpress.com/2010/12/harry-potter-sorting-hat.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="harry-potter-sorting-hat" border="0" alt="harry-potter-sorting-hat" src="http://complextosimple.files.wordpress.com/2010/12/harry-potter-sorting-hat_thumb.jpg?w=477&#038;h=310" width="477" height="310" /></a></p>
<h2></h2>
<h2>Sorting algorithms?</h2>
<p>Nope.</p>
<p>Great for computer science.&#160; You should have a basic idea of how they work, but unless you are writing some low level bit twiddling code on an integrated circuit, you don’t need to know about them.</p>
<p>Let’s think of sorting algorithms as a black box.&#160; You don’t need to know what the algorithm is or how it works, you just need to know that if you give the two things it requires it will sort your list for you.</p>
<p><strong>What two things do all sorting algorithms, regardless of implementation need?</strong></p>
<ol>
<li>A list of things to sort</li>
<li>A method to call to tell if object A comes before or after object B, or whether they are the same.</li>
</ol>
<p>That is all you need to know and give to a sorting algorithm implementation and it will do the rest.</p>
<p>Every modern programming language has at least one sorting algorithm and every single one of them has the exact two same inputs I mentioned above, a list to sort, and a comparison method.</p>
<p>It doesn’t matter if you are using C#, Java, Ruby or some other language, they all implement a sorting algorithm and need those two things.&#160; And that is all they need from you.</p>
<p>The burden is off your shoulders.</p>
<h2>Step 1: Find the sorting method</h2>
<p>I’m going to do better than teach you how to sort in each language.&#160; I’m going to show you how to figure out how to sort in a language.</p>
<p>The first step in doing that regardless of the language, is to find the method that sorts things.</p>
<p>A good place to look is the list or collection object itself, since that is the most obvious place to put a sort routine.</p>
<p>When we look up <a href="http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx">List</a> in C#, sure enough we find Sort on there.</p>
<p>Oh noes!&#160; So confusing!&#160; It has 3 sort methods!&#160; Which one do I call?&#160; Agh!</p>
<p>Don’t panic.&#160; Remember what I said above.&#160; Even though you see three signatures for the sort method, sort methods still only need two things.</p>
<p><em>Sort(), Sort(Comparison&lt;T&gt;), and Sort(IComparer&lt;T&gt;)</em> still need just a list and a method to compare two of your objects.</p>
<p>We’ll dive into that more in a bit, now let’s look at Java.</p>
<p>If we look up <em>ArrayList</em> in Java, we don’t find a sort method.&#160; Boo.&#160; What were they thinking.&#160; It’s ok though, googling for “Java sort” turns up <em>Arrays.sort</em> and <em>Collections.sort</em>.</p>
<p>Let’s look at <em>Collections.sort</em>.</p>
<p>This time we see two sort methods,<em> sort(List list),</em> and <em>sort(List list, Comparator c)</em>.</p>
<p>Again, nothing to be afraid of since we know the two things all sorting algorithms require from us.</p>
<h2></h2>
<h2>Step 2: Find the two things</h2>
<p>So if every sorting method needs the same two things from you, then all you need to do is figure out how to give it those two things.</p>
<p>In the C# and Java instances above, the first thing (the list of things to sort) is fairly obvious.&#160; In C# we saw that the sort method was on the list class itself, so we don’t even need to pass it the list of things to sort, it still needs it, but it knows where to find it.</p>
<p>In the Java instance the first parameter to both sort methods is a list.</p>
<p>See how easy we just made things?&#160; We are already 50% there.</p>
<p>So really the only question left is how to provide the method that compares two of our objects.</p>
<p><strong>When we know what we are looking for, it is much easier to find and understand.</strong></p>
<p>Let’s break down each instance and figure this out.</p>
<p>If we look at C#’s <em>Sort()</em> method, without reading the documentation, we can probably guess two things.</p>
<ol>
<li>The list to sort is the list we are calling the sort method on.</li>
<li>The objects in the list provide the comparing method.</li>
</ol>
<p>The first is obvious.&#160; The second one is a little less obvious, but if you think about it, since the method takes no parameters the only possible thing that could be providing the method for comparison is the objects in the list.</p>
<p>If we look at the <a href="http://msdn.microsoft.com/en-us/library/b0zbh7b6.aspx">documentation</a> for Sort(), we find that is true.&#160; The objects in the list have to implement <em>IComparable</em>.&#160; <em>IComparable</em> has one method, <em>CompareTo</em>, which takes one object and compares it to the other.&#160; If you implement this interface on your object, you can sort a list of them.&#160; Simple.</p>
<p>For <em>Sort(Comparison&lt;T&gt;)</em>, we can easily deduce that what is passed in there must be the method to compare two objects, and sure enough it is.&#160; If we want to use this method we just pass in a method of type <em>Comparison&lt;T&gt;</em> where T is the type of object we want to compare.</p>
<p>We can see that <em>Comparison&lt;T&gt;</em> is just a method that takes two of your objects and returns an int to indicate which is greater or if they are equal (1 = greater, 0 = equal, –1 less).</p>
<p>The final C# <em>Sort(IComparer&lt;T&gt;)</em> just takes an object that implements <em>IComparer&lt;T&gt;</em>.&#160; Sure enough, <em>IComparer&lt;T&gt;</em> has one method that must be implemented, Compare.&#160; That method has the same signature as <em>Comparison&lt;T&gt;</em> from above.</p>
<p>Now, let’s look at Java.&#160; You’re going to find it is pretty much the same thing.</p>
<p>For <em>sort(List list)</em>, we can easily see that the list to sort is passed in as a parameter, but once again we have to find where we supply the method to compare two of our objects.</p>
<p>Since it can’t be passed in, it must be… say it with me… on the object.&#160; That is right!</p>
<p>Turns out we just have to have our objects implement <em>Comparable</em> and then they can be sorted.&#160; When we look at the <em>Comparable</em> interface, we see that it just has one method, <em>CompareTo(Object o)</em> and that method just takes another object to compare our object to and returns 1 if ours is greater, 0 if it is the same, or –1 if ours is smaller.</p>
<p>Now let’s look at <em>sort(List list, Comparator c)</em>.&#160; In this case, we can see that the method to compare our two objects is passed in, but since we can’t pass methods in Java, Comparator is just an interface that we can implement that provides the comparison method.</p>
<p>If we look at the <em>Comparator</em> interface, we see it has one method we need to implement <em>compare(Object o1, Object o2)</em>.&#160; I’m sure you can guess what that method should return by now.</p>
<p>So regardless of the language, when you are looking at how to use a sorting algorithm, find the two things that it needs.&#160; The list is usually obvious, but the method to compare is almost always implemented in one of three ways.</p>
<ol>
<li>An interface the objects being compared implement.</li>
<li>A method that is passed in.</li>
<li>An object that is passed in that implements a comparison interface.</li>
</ol>
<h3></h3>
<h2></h2>
<h2>Step 3: Implement the method</h2>
<p>After you have figured out how to pass your list and your comparison method to the sorting algorithm, you need to actually write the comparison method.</p>
<p>If you learn to write a comparison method you can use it for any sorting algorithm, since all comparison methods do the exact same thing.</p>
<p>Fortunately, this is easy as well, because comparison methods always do the exact same thing.&#160; They take two objects and return whether the first one is larger, smaller, or equal to the second.&#160; That is it.</p>
<p>Don’t worry about sorting.&#160; Remember what I told you about the sorting algorithm black box?&#160; Let that sorting algorithm worry about sorting, all you have to do is decide whether 1 given item comes before a 2nd given item or if they are they same, nothing more.</p>
<p>Can you do that?</p>
<p>Sort people on age?&#160; </p>
<p>If person1.Age &gt; person2.Age return 1</p>
<p>Else if person1.Age &lt; person2.Age return –1</p>
<p>Else return 0</p>
<p>Psuedo-code, but pretty simple.</p>
<h2>Wrapping it up</h2>
<p>If you can figure out what method you can use to sort in your language, find how to pass in the list of things to sort and provide the comparison method, and implement the comparison method, then you can sort!</p>
<p><strong>Just remember to not get overwhelmed and think logically about the two things that all sorting methods need from you, and you’ll see how simple the whole sorting thing really is.&#160; </strong></p>
<p>You can be the guy that everyone asks about sorting instead of the guy copying and pasting some sorting code from the internet that you aren’t really sure how it works.</p>
<p>By the way, in C#, I would recommend just using the LINQ extension method OrderBy.</p>
<p>Very nice to do something like:</p>
<p>people.OrderBy(p =&gt; p.Age).OrderBy(p =&gt; p.Name);</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/1190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1190/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1190&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/12/07/back-to-basics-sorting/feed/</wfw:commentRss>
		<slash:comments>5</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/12/harry-potter-sorting-hat_thumb.jpg" medium="image">
			<media:title type="html">harry-potter-sorting-hat</media:title>
		</media:content>
	</item>
		<item>
		<title>Back to Basics: What is an Interface?</title>
		<link>http://simpleprogrammer.com/2010/11/02/back-to-basics-what-is-an-interface/</link>
		<comments>http://simpleprogrammer.com/2010/11/02/back-to-basics-what-is-an-interface/#comments</comments>
		<pubDate>Wed, 03 Nov 2010 03:25:44 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Language]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/?p=1152</guid>
		<description><![CDATA[This is the first part of my Back to Basics series. One of the basics I feel we really need to get back to is the use and understanding of the value of interfaces. In languages like C# and Java, interfaces are extremely common.&#160; They are much more commonly used then they were 5-10 years [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1152&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This is the first part of my <a href="http://simpleprogrammer.com/2010/10/30/getting-back-to-basics-introduction-and-why/">Back to Basics series</a>.</p>
<p>One of the basics I feel we really need to get back to is the use and understanding of the value of interfaces.</p>
<p>In languages like C# and Java, interfaces are extremely common.&#160; They are much more commonly used then they were 5-10 years ago.</p>
<p>But a question we have to ask ourselves is “are we using them correctly?”</p>
<h2>What problem does the interface solve?</h2>
<p>I want you to take a second and clear your head of how you are currently using interfaces.</p>
<p>I want you to pretend for a moment that you don’t know what an interface is.</p>
<p>Ready?</p>
<p><strong>The basic problem an interface is trying to solve is to separate how we use something from how it is implemented.</strong></p>
<p>Why do we want to separate the use from the implementation?</p>
<p>So that we can write code that can work with a variety of different implementations of some set of responsibilities without having to specifically handle each implementation.</p>
<p>To put this simpler, this means that if we have a <em>Driver</em> class it should be able to have a method <em>Drive</em> that can be used to drive any car, boat or other kind of class that implements the <em>IDriveable</em> interface.</p>
<p>The <em>Driver</em> class should not have to have a <em>DriveBoat</em>, <em>DriveCar</em> or <em>DriveX</em> methods for each kind of class that supports the same basic operations that are needed for it to be driven.</p>
<p><a href="http://complextosimple.files.wordpress.com/2010/11/driver-race-car.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="Driver-Race-Car" border="0" alt="Driver-Race-Car" src="http://complextosimple.files.wordpress.com/2010/11/driver-race-car_thumb.jpg?w=487&#038;h=357" width="487" height="357" /></a></p>
<p><strong>Interfaces are trying to solve a very specific problem by allowing us to interact with objects based on what they do, not how they do it.</strong></p>
<h2>Interfaces are contracts</h2>
<p>Interfaces allow us to specify that a particular class meets certain expectations that other classes can rely on.</p>
<p>If we have a class that implements an interface, we can be sure that it will support all the methods that are defined in that interface.</p>
<p>At first glance interfaces seem to be similar to concrete inheritance, but there is a key difference.</p>
<p>Concrete inheritance says <em>Car</em> is an <em>Automobile</em>, while an interface says <em>Car</em> implements the <em>Drivable </em>interface.</p>
<p>When a class implements an interface, it does not mean that class IS that interface.&#160; <strong>For this reason interfaces that completely describe the functionality of a class are usually wrong.</strong></p>
<p>A class can implement multiple interfaces, because each interface only talks about a particular contract that class is able to fulfill.</p>
<h2>Interfaces are always implemented by more than one class</h2>
<p>You might be saying “no they’re not, I have a class here that has an interface that no other class implements.”</p>
<p>To that I say, “you are doing it wrong.”</p>
<p>But, don’t worry, you are not alone.&#160; I am doing it wrong also.&#160; Many of us are not using interfaces correctly anymore, but are using them instead because we are under the impression that we should never use a concrete class directly.</p>
<p>We are afraid of tightly coupling our application, so instead we are creating interfaces for every class whether or not we need an interface.</p>
<p>There are some really good reasons why I say that interfaces are always implemented by more than one class.</p>
<p>Remember how we talked about how interfaces are designed to solve a particular problem?</p>
<p>In my example, I talked about how the <em>Driver </em>class shouldn’t have to have a method of each kind of class it can drive, instead it should depend on an <em>IDriveable</em> interface and can have one generic <em>Drive</em> method that can drive anything that implements <em>IDrivable</em>. </p>
<p>Most of us accept the YAGNI principle which says “You Ain’t Gonna Need It.”&#160; If we only have a <em>Car</em> class, and we don’t have any other classes that need to be driven by the <em>Driver</em> class, we don’t need an interface.&#160; YAGNI!</p>
<p>At some point we may later add a <em>Boat </em>class.&#160; Only at that point in time do we actually have a problem that the interface will solve.&#160; Up until that point adding the interface is anticipating a future problem to solve.</p>
<p>If you think you are good at anticipating when you will need an interface, I want you to do a little exercise.&#160; Go into your codebase and count all the interfaces you have.&#160; Then count all the classes that implement those interfaces.&#160; I bet the ratio is pretty close to 1 to 1.</p>
<h2>But how will I test?&#160; How will I use dependency injection?</h2>
<p>These two reasons are probably the most justified causes for incorrectly using interfaces.</p>
<p>I am guilty of justifying the creation of an interface so that I can have something to mock, and I am guilty of creating an interface just for my dependency injection framework, but it doesn’t make it right.</p>
<p>I can’t give you an easy answer here and say that I can solve your unit testing or dependency injection problems without an interface, but I can talk about why we shouldn’t be bending the source code to fit the tool or methodology.</p>
<p>I talked about <a href="http://simpleprogrammer.com/2010/10/15/the-purpose-of-unit-testing/">the purpose of unit testing</a> before, and one of the key benefits being that unit tests help guide your design.&#160; Unit tests help us to decouple our application and consolidate our classes to single responsibilities by making it really painful to try and unit test classes with multiple dependencies.</p>
<p><strong>Interfaces are kind of a shortcut that allows us to get rid of having lots of dependencies in a class.</strong></p>
<p>When we turn a reference to a concrete class into an interface reference, we are cheating the system.&#160; We are making it easier to write a unit test by pretending that our class is decoupled because it references an interface instead of a concrete class.&#160; <strong>In reality it is not decoupled it is actually more coupled because our class is coupled to an interface which is coupled to a class.</strong>&#160; All we did was add a level of indirection.</p>
<p>Dependency injection promotes the same problem of interface abuse.&#160; At least it does in the way it is used in C# and Java today.&#160; Creating an interface solely for the purpose of being able to inject the only implementation of that interface into a class creates an unnecessary level of indirection and needlessly slows down the performance of our application.</p>
<p>Don’t get me wrong.&#160; Dependency injection is good.&#160; I’ll save the details for another post, but I believe dependency injection’s real benefit is when it is used to control which implementation of an interface is used, not when there is only one implementation of an interface.</p>
<p>Ultimately, I can’t give you a good answer of how do you unit test or use dependency injection without abusing interfaces.&#160; I think you can reduce the abuse by choosing to split apart classes and actually reduce dependencies rather than simply creating an interface and injecting it into the class, but you are still going to have the problem that a <em>Car</em> has an <em>Engine </em>and if you want to unit test the car, you are either going to have to use the real engine or find a way to mock it.</p>
<p>The key problem here is that interfaces are part of the language, but unit testing and dependency injection are not.&#160; We are trying to make them fit in with the language by using a trick.&#160; The trick is we create an interface to provide a seam between classes.&#160; The problem is that we dilute the potency of an interface by doing so.&#160; What we really need is a language supported seam to allow us to easily replace implementations of concrete classes at runtime.</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/1152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1152/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1152/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1152/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1152/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1152/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1152/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1152/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1152&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/11/02/back-to-basics-what-is-an-interface/feed/</wfw:commentRss>
		<slash:comments>20</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/11/driver-race-car_thumb.jpg" medium="image">
			<media:title type="html">Driver-Race-Car</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>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>
	</channel>
</rss>
