<?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; Learning</title>
	<atom:link href="http://simpleprogrammer.com/category/learning/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; Learning</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>PaceMaker for iPhone Released</title>
		<link>http://simpleprogrammer.com/2011/06/09/pacemaker-for-iphone-released/</link>
		<comments>http://simpleprogrammer.com/2011/06/09/pacemaker-for-iphone-released/#comments</comments>
		<pubDate>Fri, 10 Jun 2011 03:47:52 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Mobile]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/2011/06/09/pacemaker-for-iphone-released/</guid>
		<description><![CDATA[Earlier this year I announced the release of an app I had been working on for Android called PaceMaker. Finally, I have succeeded in porting the application over to iPhone and it was definitely much harder than I had anticipated. But I am glad to announce that as of today you can find PaceMaker for [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1349&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Earlier this year <a href="http://simpleprogrammer.com/2011/01/04/introducing-pacemaker-for-android/">I announced the release of an app I had been working on for Android called PaceMaker</a>.</p>
<p>Finally, I have succeeded in porting the application over to iPhone and it was definitely much harder than I had anticipated.</p>
<p>But I am glad to announce that as of today you can find <a href="http://itunes.apple.com/us/app/pacemaker-running/id441825091?mt=8&amp;ls=1">PaceMaker for iPhone in the Apple App Store</a>.</p>
<p>If you don’t know what PaceMaker is, you can read about it in my original post above or in the description in the app store, but to sum it up briefly, it helps you run at a desired pace by telling you to speed up or slow down when you are running too fast or too slow.</p>
<p align="center"><a href="http://complextosimple.files.wordpress.com/2011/06/default2x.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="Default@2x" border="0" alt="Default@2x" src="http://complextosimple.files.wordpress.com/2011/06/default2x_thumb.png?w=324&#038;h=485" width="324" height="485" /></a></p>
<h2></h2>
<h2>A unique perspective</h2>
<p>Having originally written the application and then porting it over to iPhone gives me a kind of unique perspective on mobile development platforms.</p>
<p>Although it was a bit painful at times to basically recreate the same thing I already spent so much time and energy creating, I was able to very realistically contrast the two development platforms in many areas.</p>
<p>One of the major pain points I experienced was in documentation.&#160; Google’s documentation on the Android platform is sometimes lacking, but is much more complete and descriptive than Apple’s iOS documentation.</p>
<p>I am still quite a bit torn on which platform I like more and which platform I think will win out in the end.&#160; I do believe that if Apple improved their developer tools and moved to a new, more modern development language, that they would have a distinct advantage.</p>
<p>It seems to me though that whoever integrates the best across multiple devices and gets the highest quality applications built for their platform will be the winner.&#160; iCloud could be a huge step in that direction for Apple.</p>
<h2>Sharing the knowledge</h2>
<p>I’ve just talked with my curriculum director at <a href="http://www.pluralsight-training.net/microsoft/">Pluralsight</a> and I will be doing a beginning iPhone development for .NET developers course just like the <a href="http://www.pluralsight-training.net/microsoft/OLT/Course/Toc.aspx?n=android-intro">Android Development for .NET Developers</a> course I did earlier this year.</p>
<p>I’m pretty excited to do this because I am going to try and draw some major parallels between the two platforms and also from the .NET perspective.</p>
<p>I hope to create the course just like the Android one, where we will step by step create an application from scratch and then publish it to the Apple App Store.</p>
<p>Look for that in the next few months on Pluralsight.net.</p>
<h2>Dailymile.com integration</h2>
<p>Also included with this release for iPhone and Android is Dailymile.com integration.&#160; I think this feature is pretty cool!&#160; So I am really excited about it!</p>
<p>Dailymile.com is basically a social site for runners and cyclists.&#160; It is basically a Facebook for runners.</p>
<p>I have added a feature to the Android and iPhone versions of PaceMaker to allow you to post your run details, including the GPX map of your run, up to the Dailymile.com server on your wall.</p>
<p>So when you go for a run you can capture all the information from your run and see it on Dailymile.com.</p>
<p>This was quite a pain to implement as I had to implement OAuth2 authentication in both platforms and integrate with a REST API.&#160; But what a great learning experience!</p>
<p>Anyway, if you are a runner out there and you get PaceMaker, feel free to send me an email or drop me a comment.&#160; I am always looking for feedback so I can improve the app.</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/1349/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1349/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1349/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1349/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1349/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1349/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1349/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1349/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1349/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1349/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1349/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1349/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1349/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1349/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1349&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2011/06/09/pacemaker-for-iphone-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2011/06/default2x_thumb.png" medium="image">
			<media:title type="html">Default@2x</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>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: Cohesion and Coupling Part 1</title>
		<link>http://simpleprogrammer.com/2010/11/04/back-to-basics-cohesion-and-coupling-part-1/</link>
		<comments>http://simpleprogrammer.com/2010/11/04/back-to-basics-cohesion-and-coupling-part-1/#comments</comments>
		<pubDate>Fri, 05 Nov 2010 05:23:17 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Learning]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/?p=1157</guid>
		<description><![CDATA[Cohesion and coupling are very misunderstood topics. We have all heard that our code should be designed in such a way to increase cohesion and be loosely coupled. Is this correct? Is it even possible to achieve both? Let&#8217;s look a little at what cohesion and coupling are in order to better understand their relationship [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1157&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Cohesion and coupling are very misunderstood topics.</p>
<p>We have all heard that our code should be designed in such a way to increase cohesion and be loosely coupled. Is this correct? Is it even possible to achieve both?</p>
<p>Let&#8217;s look a little at what cohesion and coupling are in order to better understand their relationship to our code.</p>
<h2>What is cohesion?</h2>
<p>Cohesion is simply quality of a thing being stuck together well.</p>
<p>We would say that something is highly cohesive if it has a clear boundary and all of it is contained in one place.</p>
<p>For example, a baseball is very cohesive.  Everything that makes up a baseball is in one little round orb.</p>
<p><a href="http://complextosimple.files.wordpress.com/2010/11/baseball.jpg"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="baseball" src="http://complextosimple.files.wordpress.com/2010/11/baseball_thumb.jpg?w=240&#038;h=241" border="0" alt="baseball" width="240" height="241" /></a></p>
<p>The internet is not cohesive.  It is hard to define and it is scattered all over the place.</p>
<p>When looking at software, we consider a class or module to be highly cohesive if it has a clear responsibility and all of the implementation of that responsibility is close together or in one place.</p>
<p>A good example in software would be putting all of our logic to write to a database in one class or several classes in a module, instead of letting every part of our application that needs to write to the database implement that logic in its own class.</p>
<p>We consider cohesion to be a good thing because it makes software easier to understand, reduces the effects a change on one part of the system has on the rest of the system, and it allows us to reuse code within our application.</p>
<h2>What is decoupling?</h2>
<p>Decoupling is the quality of a thing not relying on other things.</p>
<p>We would say that something is decoupled if it does not depend on anything but itself.  Something would be highly coupled if it had many different dependencies.</p>
<p>Consider an iPod.  It is highly decoupled.  It is a very self-contained piece of hardware.  It has its own battery and can be transported around without depending on anything else for it to do its job.</p>
<p>Now consider the motherboard in your computer.  It is not decoupled.  It contains specific slots for RAM, for a CPU, for video cards, etc.  If those components change in their shape or kind, they may not work with the motherboard.</p>
<p><a href="http://complextosimple.files.wordpress.com/2010/11/motherboard-callouts.jpg"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="motherboard-callouts" src="http://complextosimple.files.wordpress.com/2010/11/motherboard-callouts_thumb.jpg?w=480&#038;h=400" border="0" alt="motherboard-callouts" width="480" height="400" /></a></p>
<p>Looking at software we can consider a module or class to be decoupled if it does not have many dependencies on other classes or modules.</p>
<p>Consider implementing a class for a linked list data structure.  Chances are that class will be pretty decoupled, because it really shouldn’t depend on anything else.  (Unless you of course change the granularity of what you consider a thing to be, more on that later.)</p>
<p>We like loosely coupled software because it reduces the impact across other modules of a change in one module.  Loosely coupled software is also easier to reuse, because it doesn’t have many other dependencies to be included.</p>
<h2>Sounds like they are trying to achieve very similar goals</h2>
<p>And they are.  For the most part high cohesion and loose coupling go together.</p>
<p>If your classes have clearly defined responsibilities with the implementation of those responsibilities located in that class, chances are it we be fairly decoupled from the rest of the system.</p>
<p>In the very general sense, as you decrease coupling, you increase cohesion and vice versa.</p>
<p>The benefits are very much the same also.</p>
<p>But now I’m going to get into some muddy water here and question what we mean by a “thing” or a “module.”</p>
<p>In my <a href="http://simpleprogrammer.com/2010/11/09/back-to-basics-cohesion-and-coupling-part-2/">next post</a>, I am going to delve much deeper into this topic and look at how granularity affects cohesion and coupling as well as talk about how they can actually be inversely related.</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.  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/1157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1157/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1157/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1157/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1157/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1157/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1157/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1157/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1157&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/11/04/back-to-basics-cohesion-and-coupling-part-1/feed/</wfw:commentRss>
		<slash:comments>3</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/baseball_thumb.jpg" medium="image">
			<media:title type="html">baseball</media:title>
		</media:content>

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

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

		<guid isPermaLink="false">https://complextosimple.wordpress.com/?p=1085</guid>
		<description><![CDATA[I recently completed reading Pro Android 2. It is a pretty large book, so it took me awhile, but I finally got through it. I hadn&#8217;t really read any other Android books, so I don&#8217;t know how it compares. The book goes through creating an Android application using Eclipse. It contains many source code examples [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1085&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I recently completed reading <a href="http://www.amazon.com/gp/product/1430226595?ie=UTF8&amp;tag=makithecompsi-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=1430226595">Pro Android 2</a>. It is a pretty large book, so it took me awhile, but I finally got through it. I hadn&#8217;t really read any other Android books, so I don&#8217;t know how it compares.</p>
<p><a href="http://complextosimple.files.wordpress.com/2010/09/proandroid2.jpg"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="proandroid2" src="http://complextosimple.files.wordpress.com/2010/09/proandroid2_thumb.jpg?w=471&#038;h=471" border="0" alt="proandroid2" width="471" height="471" /></a></p>
<p>The book goes through creating an Android application using Eclipse. It contains many source code examples that are very complete. The book really seems to be focused more on getting going vs going in-depth with the APIs.</p>
<p><strong>The good:</strong></p>
<ul>
<li>Great jump start diving right into Android development without wasting much time.</li>
<li>Very complete examples that can get you going and can be modified for your own application.</li>
<li>Balances basic examples with more complex architectural constructs well. There is a good mix of examples that build on basic concepts and show how to implement more of an MVP style of development.</li>
<li>Covers a pretty wide breadth of the Android platform, which makes it easy to know what exactly is capable.</li>
</ul>
<p><strong>The bad:</strong></p>
<ul>
<li>Although the beginning of the book was very interesting and informative, some of the chapters seemed to drag on.</li>
<li>A whole huge chapter devoted to search.  Search is not something that most applications would need to make use of.</li>
<li>A whole huge chapter on 3d application development.  Not something I felt should have been in the book.  Pretty boring and actually really scary.  I don’t think I’ll ever develop a 3d application for Android.</li>
</ul>
<p><strong>What I learned:</strong></p>
<p>I had already started building my Android application before reading this book, so not very much of it was completely new to me, but I definitely learned some things from the book.</p>
<p>I was really surprised to see how easy 2D animation is with Android.  The book does a good job of explaining it and providing examples.  I feel like I could very easily implement 2D animation after reading this book.</p>
<p>I learned about  to create and use content providers.  This aspect of Android development is a bit tricky, but I felt like Pro Android 2 did a good job of explaining it and providing examples that I would be able to use.</p>
<p>I also learned to create a home screen widget.  The examples in the book were really good and provided a complete usable implementation that could be easily used as a base for creating your own.</p>
<p>Towards the end of the book, <a href="http://www.appcelerator.com/">Titanium Mobile</a> is mentioned.  Titanium Mobile is a WebKit-based native application development framework which allows developers to write applications that target multiple platforms.  It looks really cool, and I kind of wish that was the first chapter in the book, so that I could have explored that before getting so far into actual Android development.</p>
<p>Overall, I would definitely recommend the book.  I feel pretty confident that someone with no Android experience should be able to pick up that book and get going with their first application.  I definitely learned some things the hard way, before I read the book.</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/1085/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1085/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1085/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1085/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1085/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1085/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1085/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1085/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1085/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1085/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1085/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1085/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1085/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1085/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1085&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/09/07/book-review-pro-android-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2010/09/proandroid2_thumb.jpg" medium="image">
			<media:title type="html">proandroid2</media:title>
		</media:content>
	</item>
		<item>
		<title>Pulling out the Switch: It&#8217;s Time for a Whooping</title>
		<link>http://simpleprogrammer.com/2010/08/17/pulling-out-the-switch-its-time-for-a-whooping/</link>
		<comments>http://simpleprogrammer.com/2010/08/17/pulling-out-the-switch-its-time-for-a-whooping/#comments</comments>
		<pubDate>Tue, 17 Aug 2010 16:35:33 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[Learning]]></category>

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

		<guid isPermaLink="false">https://complextosimple.wordpress.com/?p=1042</guid>
		<description><![CDATA[I recently completed reading The Pragmatic Programmer by Andrew Hunt and David Thomas. I wish I could take a time machine back to the year 2000 and read it then. So much of the information in the book seems to be concepts that many software developers understand and take for granted as general knowledge now, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1042&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I recently completed reading <a href="http://www.amazon.com/gp/product/020161622X?ie=UTF8&amp;tag=makithecompsi-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=020161622X">The Pragmatic Programmer</a> by Andrew Hunt and David Thomas.</p>
<p><a href="http://complextosimple.files.wordpress.com/2010/08/pragmatic.jpg"><img style="display:inline;border:0;" title="pragmatic" src="http://complextosimple.files.wordpress.com/2010/08/pragmatic_thumb.jpg?w=382&#038;h=382" border="0" alt="pragmatic" width="382" height="382" /></a></p>
<p>I wish I could take a time machine back to the year 2000 and read it then.</p>
<p>So much of the information in the book seems to be concepts that many software developers understand and take for granted as general knowledge now, that wasn’t at the time of its writing.</p>
<p>The book is very much a collection of knowledge from years of practical experience writing code.  It is very specific in stating what kind of specific coding practices should be carried out and which ones should be avoided.</p>
<p>The content of the book lays somewhere between the low level software construction in a book like <a href="http://www.amazon.com/gp/product/1556154844?ie=UTF8&amp;tag=makithecompsi-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=1556154844">Code Complete</a> and a book targeting a higher level methodology or project management.</p>
<p><strong>Good:</strong></p>
<ul>
<li>Years of experience packed into a small package.</li>
<li>Most of the advice in this book is timeless.</li>
<li>Practical real world truth instead of theoretical talk.</li>
<li>Excellent focus on automation for everything you can automate.</li>
<li>Technology independent advice.</li>
</ul>
<p><strong>Bad:</strong></p>
<ul>
<li>There were definitely some dated pieces of advice that I wouldn’t recommend following today.</li>
<li>If you are already familiar with many of the software craftsmanship or general agile principles, much of this book will echo what you already know.  (Can’t fault the authors for that since this book is probably the origin of much of that information getting out, yet if you haven’t read the book, you should know what to expect.)</li>
</ul>
<p><strong>What I learned:</strong></p>
<p>I really liked the section of the book that talked about using “tracer bullets” in software development.  Basically the idea is that you can either prototype the software or build what you know and then adjust your aim to reach the user’s real requirements instead of trying to specify up front.</p>
<p>I think many times in development we get hung up on knowing all the details, but sometimes we need to fire “tracer bullets” first to see if we are hitting the target.</p>
<p>I also realized that I am guilty often of programming by coincidence.  Sometimes I will have put a magic incantation into the code and not really understood why it worked.  It is very important to understand why something works, not just make it work.</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/1042/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1042/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1042/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1042/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1042/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1042/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1042/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1042/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1042/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1042/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1042/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1042/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1042/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1042/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1042&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/08/10/book-review-the-pragmatic-programmer/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/2010/08/pragmatic_thumb.jpg" medium="image">
			<media:title type="html">pragmatic</media:title>
		</media:content>
	</item>
		<item>
		<title>Late to the JQuery Party</title>
		<link>http://simpleprogrammer.com/2010/07/14/late-to-the-jquery-party/</link>
		<comments>http://simpleprogrammer.com/2010/07/14/late-to-the-jquery-party/#comments</comments>
		<pubDate>Thu, 15 Jul 2010 00:24:24 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/2010/07/14/late-to-the-jquery-party/</guid>
		<description><![CDATA[You may be wondering what happened to my usual Monday post. Well, I was having my head rearranged by JQuery.&#160; I have to admit, I am pretty late to the party.&#160; I haven’t really been using JQuery at all the past few years. I missed a lot. Goodbye type safety This part scares me a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=999&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>You may be wondering what happened to my usual Monday post.</p>
<p>Well, I was having my head rearranged by <a href="http://jquery.com/">JQuery</a>.&#160; I have to admit, I am pretty late to the party.&#160; I haven’t really been using JQuery at all the past few years.</p>
<p>I missed a lot.</p>
<p><a href="http://complextosimple.files.wordpress.com/2010/07/jquerylogo_png.png"><img style="display:inline;border-width:0;" title="jquery-logo_png" border="0" alt="jquery-logo_png" src="http://complextosimple.files.wordpress.com/2010/07/jquerylogo_png_thumb.png?w=302&#038;h=302" width="302" height="302" /></a> </p>
<h2></h2>
<h2>Goodbye type safety</h2>
<p>This part scares me a little bit.&#160; I already made a few typos that were pretty hard to detect.</p>
<p>Debugging javascript is not much fun considering that data and methods are both first class citizens.</p>
<p>But, the trade-off just might be worth it.</p>
<p>What we are losing in type safety, we are making up for in productivity and speed.&#160; It is really fast to manipulate a page using JQuery and to hook up events.</p>
<p>I still wish there was some way to have some sort of type safety when using JQuery or Javascript in general, but it really hurts my brain to try and think about how that would be possible.</p>
<p>Perhaps some kind of <a href="http://projects.nikhilk.net/ScriptSharp">Script#</a> / JQuery bastard child?</p>
<p>I know some people are doing Javascript unit testing.&#160; That would certainly make me feel safer not having type safety.</p>
<h2></h2>
<h2>Functional thinking</h2>
<p>I like the functional thinking paradigm.&#160; One of my <a href="http://trycatchfail.com/blog/">co-workers</a> was saying that he likes JQuery because it helps him to write Lamba expressions and LINQ queries.&#160; I tend to agree with him.</p>
<p>I’ve said it before, but I believe the next high abstraction of programming is thinking functionally.</p>
<p>So many pieces of code that I would have used code generation to produce in the past, I can now produce with Lambda expressions.</p>
<h2>It’s not all roses</h2>
<p>I do have some major issues with JQuery and Javascript in general.&#160; One of the big problems is that JQuery is not a language, and it’s not a library.&#160; It is a DSL built on top of a language.</p>
<p><strong>Bleeding all the way through the stack</strong></p>
<p>The downfall of this is that it is a very leaky abstraction.&#160; Abstractions are good because they allow us to think at a higher level.</p>
<p>Leaky abstractions are bad because they force us to context switch from a higher level of thinking down to a lower level.</p>
<p>In order to understand JQuery you must understand Javascript, the DOM and CSS to some extent.</p>
<p>Think for a second about all the “languages” or technologies you have to know to develop an ASP.NET web page using JQuery and MVC.</p>
<ul>
<li>ASP.NET MVC </li>
<li>HTML </li>
<li>C# or Visual Basic </li>
<li>JSON </li>
<li>Javascript </li>
<li>JQuery </li>
<li>CSS </li>
<li>Web Services / Rest </li>
<li>HTTP (You need to be able to debug all the coolness you are flinging back and forth.) </li>
</ul>
<p>When you have it all working, it is pretty slick.&#160; Very slick indeed, but it is not a sustainable model.&#160; It is complex and sprinkled with errors and gotchas.</p>
<p><strong>Debugging / readability</strong></p>
<p>When I am writing JQuery, although I feel like it is magical and cool, I also feel a little bit dirty.</p>
<p>Why?</p>
<p>Well, as clean as you try to write JQuery code, it can be pretty nasty.&#160; There is a lot of magic going on, and it is not very easily understandable.</p>
<p>Perhaps I’ll get better at expressing my intent clearly in JQuery code, but I am pretty sure it has to due in part with the leakiness of the abstraction layer, and that can’t really be cleaned up easily.</p>
<p>Debugging is also hell.&#160; I tried debugging through the validation library to see why my error messages weren’t showing up, and it was no picnic.</p>
<p>Javascript itself is notoriously difficult to debug, because objects can have methods dynamically added to them, and all the other little tricks, make it hard to look at a watch window and get anything useful out of an object.</p>
<h2>View logic</h2>
<p>One of the things I really enjoyed while writing JQuery code was putting the view logic where it really belongs.&#160; It is nice to have a language and a server separating the view logic from the model and presentation.</p>
<p>JQuery really allows you to put all the code that manipulates the view in one place, and on the client side, where it really belongs.</p>
<p>JQuery will make your HTML code so much cleaner and helps to actually plug the leaks in the HTML abstraction layer.&#160; (Although it isn’t perfect, especially when working with ASP.NET Web Forms.)</p>
<h2></h2>
<h2>Better late then never at all</h2>
<p>So I know I’m really late to the JQuery party, but I’m here now, and I am liking it.</p>
<p>Overall, I’d recommend taking a look at JQuery if you are like me and hadn’t really used it until now.&#160; It definitely is a valuable skill to develop and is growing at an <a href="http://trends.builtwith.com/javascript/JQuery">extremely rapid pace</a>.</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/999/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/999/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/999/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/999/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/999/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/999/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/999/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/999/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/999/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/999/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/999/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/999/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/999/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/999/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=999&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/07/14/late-to-the-jquery-party/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/2010/07/jquerylogo_png_thumb.png" medium="image">
			<media:title type="html">jquery-logo_png</media:title>
		</media:content>
	</item>
	</channel>
</rss>
