<?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"
	>

<channel>
	<title>John Miller</title>
	<atom:link href="http://www.johnlmiller.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.johnlmiller.com</link>
	<description>"Risks weren’t that scary once you took them."</description>
	<pubDate>Sun, 08 Aug 2010 14:51:57 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.6.3</generator>
	<language>en</language>
			<item>
		<title>2009 Goals Update and Challenges For 2010</title>
		<link>http://www.johnlmiller.com/archives/2010/01/03/2009-goals-update-and-challenges-for-2010/</link>
		<comments>http://www.johnlmiller.com/archives/2010/01/03/2009-goals-update-and-challenges-for-2010/#comments</comments>
		<pubDate>Sun, 03 Jan 2010 14:24:48 +0000</pubDate>
		<dc:creator>John Miller</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[inspiration]]></category>

		<category><![CDATA[Personal]]></category>

		<guid isPermaLink="false">http://www.johnlmiller.com/?p=241</guid>
		<description><![CDATA[Like many others are doing, it&#8217;s time to reflect on 2009 and set the bar for the new year!
Last Year
Last year started strong, but work took over a lot of my free time during the second half of the year. I knew some of the goals were gonna be more than I could handle but [...]]]></description>
			<content:encoded><![CDATA[<p>Like many others are doing, it&#8217;s time to <a href="http://darrell.mozingo.net/2010/01/02/2009-goals-year-end-update/" target="_blank">reflect on 2009</a> and <a href="http://joshreedschramm.com/2009/12/my-2010-challenge-list/" target="_blank">set the bar</a> for the new year!</p>
<h3>Last Year</h3>
<p>Last year started strong, but work took over a lot of my free time during the second half of the year. I knew some of the goals were gonna be more than I could handle but wanted to keep the bar high!<br />
<strong>Technical Goals</strong><br />
<strong>Read the following books:</strong><br />
Read 1 out of 6&#8230;.pitiful. To be fair, I did do a good amount of technical reading this year, just not these specific books.</p>
<ul>
<li><a href="http://www.amazon.com/Enterprise-Application-Architecture-Addison-Wesley-Signature/dp/0321127420/ref=pd_bbs_sr_1?ie=UTF8&amp;s=books&amp;qid=1229896370&amp;sr=8-1" target="_blank"><span style="text-decoration: line-through;">Patterns of Enterprise Application Architecture</span></a><span style="text-decoration: line-through;"> – Fowler</span> <em>– Finished!</em></li>
<li><a href="http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1229896453&amp;sr=1-1" target="_blank">Domain Driven Design</a> – Evans</li>
<li><a href="http://www.amazon.com/Applying-Domain-Driven-Design-Patterns-Examples/dp/0321268202/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1229896587&amp;sr=1-1" target="_blank">Applying Domain-Driven Design and Patterns</a> – Nilsson</li>
<li><a href="http://www.amazon.com/Working-Effectively-Legacy-Robert-Martin/dp/0131177052/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1229896657&amp;sr=1-1" target="_blank">Working Effectively with Legacy Code</a> – Feathers</li>
<li><a href="http://www.amazon.com/Refactoring-Improving-Existing-Addison-Wesley-Technology/dp/0201485672" target="_blank">Refactoring</a> – Fowler</li>
<li><a href="http://www.amazon.com/Principles-Patterns-Practices-Robert-Martin/dp/0131857258/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1229896765&amp;sr=1-1" target="_blank">Agile Principles, Patterns, and Practices in C#</a> - Martin</li>
</ul>
<p><strong>Become proficient with the following tools &amp; technologies:</strong></p>
<ul>
<li><a href="http://www.asp.net/mvc/" target="_blank">ASP.Net MVC</a> – <em>No progress, this will certainly be on the 2010 goal list.</em></li>
<li><a href="http://www.hibernate.org/343.html" target="_blank"><span style="text-decoration: line-through;">NHibernate</span></a> – <em>Finished!</em></li>
<li><a href="http://www.castleproject.org/" target="_blank"><span style="text-decoration: line-through;">The Castle Stack</span></a> – <em>Finished (not familiar with the entire stack, only the parts I was interested in)!</em></li>
<li><a href="http://www.jetbrains.com/teamcity/" target="_blank"><span style="text-decoration: line-through;">Team City</span></a> – <em>Finished!</em></li>
<li><a href="http://www.ruby-lang.org/en/" target="_blank"><span style="text-decoration: line-through;">Ruby</span></a><span style="text-decoration: line-through;"> (the basics at a minimum)</span> – <em>Finished!</em></li>
<li><a href="http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx" target="_blank">Powershell</a> – <em>No progress here.</em></li>
</ul>
<p><strong>Get involved:</strong></p>
<ul>
<li>Two blog posts per month – <em>Was surprised at how hard it was to keep up with this. Did awesome the first 2/3 of the year but pretty much stopped blogging in September. Hoping to change that this year.</em></li>
<li>Two technical presentations for coworkers to push agile methodologies at my current company. – <em>Our company has gone through some changes and I don’t see after hours presentations like this happening in the near future, so I’m gonna scratch this one for now.</em></li>
</ul>
<p><strong>Certifications:</strong></p>
<ul>
<li>Upgrade MCPD certification from 2.0 to 3.5 – <em>No progress here.</em></li>
</ul>
<p><strong>Personal Goals</strong><br />
<strong>Family Time</strong></p>
<ul>
<li>Take 2 one week long trips – <em>Considering this one met.</em></li>
<li>Take 6 weekend getaways – <em>Took a couple weekend trips, but didn&#8217;t do all 6.</em></li>
<li>By the end of the year, work from home regularly two times per week – <em>This is a tough one with my current job, the ability to do this is completely dependant on the project\client and hasn’t been an option lately.</em></li>
</ul>
<p><strong>Belief System</strong></p>
<ul>
<li>Read the Bible completely through – <em>Finished with a day to spare!</em></li>
</ul>
<p><strong>Financial</strong></p>
<ul>
<li>Reduce debt by two-thirds – <em>Made it within a few hundred dollars of our goal!</em></li>
<li>Become familiar with some of the ins and outs of day trading, as well as how currency trading works – <em>Started learning and lost interest, don&#8217;t think day trading is for me :).</em></li>
</ul>
<p><strong>Side Projects</strong></p>
<ul>
<li>Finish the project I’ve been working on for the last year! – <em>Finished!</em></li>
<li>Start a new venture and grow it to produce $500 per month of automated income by the end of the year. – <em><a href="http://joshreedschramm.com/" target="_blank">Josh</a> and I are in the middle of a project that we hoped to have finished by CodeMash (although we have a lot of work to do this week if we&#8217;re going to hit that goal. Will more than likely launch end of Feb or early March.</em></li>
</ul>
<p></p>
<h3>2010 Challenges</h3>
<p><strong>Technical Goals</strong></p>
<ul>
<li>Read 6 technical books - Taking a different approach this year. Instead selecting 6 books at the start of the year, I&#8217;m going to pick as I go.</li>
<li>Learn ASP.Net MVC - No excuses this year!</li>
<li>Become more fluent with Ruby\Rails\RSpec\etc. - Last year I started picking up Ruby but never really hit the point where I was more than just hacking away at things. This year I want to learn to do things the *right* way.</li>
<li>Learn Ninject - This one has been on my radar for a long time, just haven&#8217;t taken the time to pick up and go with it.</li>
<li>One blog article per month - I know, you&#8217;re not supposed to lower the bar year-to-year, but I want to keep more of my free time open for other things this year.</li>
<li>Upgrade MCPD certification from 2.0 to 3.5 – <em>&#8230;and then 4.0</em></li>
<li>Two technical presentations for coworkers to push agile methodologies at my current company.</li>
</ul>
<p><strong>Personal Goals</strong></p>
<ul>
<li>Launch two side projects - Stole this goal from <a href="http://joshreedschramm.com/" target="_blank">Josh</a>. We&#8217;re hoping to launch both EventCasts and a new project by the end of the year.</li>
<li>Read 6 non-technical books</li>
<li>Become debt-free (not counting mortgage &#038; car loans)</li>
</ul>
<p>While this isn&#8217;t everything I want to accomplish this year, I decided to keep it much shorter than last year. We&#8217;ve got a lot of (good) things happening at the moment and don&#8217;t want to burn myself out by adding too many things to the list!</p>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=John%20Miller&amp;siteurl=http%3A%2F%2Fwww.johnlmiller.com%2F&amp;linkname=2009%20Goals%20Update%20and%20Challenges%20For%202010&amp;linkurl=http%3A%2F%2Fwww.johnlmiller.com%2Farchives%2F2010%2F01%2F03%2F2009-goals-update-and-challenges-for-2010%2F"><img src="http://www.johnlmiller.com/wp-content/plugins/add-to-any/share_save_171_16.gif" width="171" height="16" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://www.johnlmiller.com/archives/2010/01/03/2009-goals-update-and-challenges-for-2010/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Turning Off Regions in ReSharper</title>
		<link>http://www.johnlmiller.com/archives/2009/11/10/turning-off-regions-in-resharper/</link>
		<comments>http://www.johnlmiller.com/archives/2009/11/10/turning-off-regions-in-resharper/#comments</comments>
		<pubDate>Tue, 10 Nov 2009 16:35:45 +0000</pubDate>
		<dc:creator>John Miller</dc:creator>
		
		<category><![CDATA[.Net]]></category>

		<category><![CDATA[ReSharper]]></category>

		<guid isPermaLink="false">http://www.johnlmiller.com/?p=238</guid>
		<description><![CDATA[I’m not a fan of seeing regions in my code and, by default, ReSharper is configured to group members (methods, interface implementations, etc) with regions when running the Code Cleanup utility. I’ve turned this off a couple of times but it usually takes some poking around until I remember what to do again.
From within Visual [...]]]></description>
			<content:encoded><![CDATA[<p>I’m not a fan of seeing regions in my code and, by default, ReSharper is configured to group members (methods, interface implementations, etc) with regions when running the Code Cleanup utility. I’ve turned this off a couple of times but it usually takes some poking around until I remember what to do again.</p>
<p>From within Visual Studio, open ReSharper –&gt; Options.</p>
<p>Then, under Languages –&gt; C#, select “Type Members Layout”</p>
<p><a href="http://www.johnlmiller.com/wp-content/uploads/2009/11/typememberslayout.jpg"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="TypeMembersLayout" src="http://www.johnlmiller.com/wp-content/uploads/2009/11/typememberslayout-thumb.jpg" border="0" alt="TypeMembersLayout" width="523" height="519" /></a></p>
<p>Uncheck the “Use Default Patterns” checkbox</p>
<p><a href="http://www.johnlmiller.com/wp-content/uploads/2009/11/usedefault.jpg"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="UseDefault" src="http://www.johnlmiller.com/wp-content/uploads/2009/11/usedefault-thumb.jpg" border="0" alt="UseDefault" width="520" height="514" /></a></p>
<p>Throughout the XML configuration document, you’ll notice various “Group” nodes which are used to create regions for specific element types. Deleting all these nodes will keep ReSharper from adding regions when running Code Cleanup.</p>
<p><a href="http://www.johnlmiller.com/wp-content/uploads/2009/11/groups.jpg"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Groups" src="http://www.johnlmiller.com/wp-content/uploads/2009/11/groups-thumb.jpg" border="0" alt="Groups" width="251" height="467" /></a></p>
<p>If you really dislike regions, you can also configure ReSharper to remove all existing regions as well. Find the default pattern node…</p>
<p><a href="http://www.johnlmiller.com/wp-content/uploads/2009/11/defaultbefore.jpg"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="DefaultBefore" src="http://www.johnlmiller.com/wp-content/uploads/2009/11/defaultbefore-thumb.jpg" border="0" alt="DefaultBefore" width="224" height="68" /></a></p>
<p>…and add a flag to remove all regions.</p>
<p><a href="http://www.johnlmiller.com/wp-content/uploads/2009/11/defaultafter.jpg"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="DefaultAfter" src="http://www.johnlmiller.com/wp-content/uploads/2009/11/defaultafter-thumb.jpg" border="0" alt="DefaultAfter" width="244" height="70" /></a></p>
<p>Much better!</p>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=John%20Miller&amp;siteurl=http%3A%2F%2Fwww.johnlmiller.com%2F&amp;linkname=Turning%20Off%20Regions%20in%20ReSharper&amp;linkurl=http%3A%2F%2Fwww.johnlmiller.com%2Farchives%2F2009%2F11%2F10%2Fturning-off-regions-in-resharper%2F"><img src="http://www.johnlmiller.com/wp-content/plugins/add-to-any/share_save_171_16.gif" width="171" height="16" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://www.johnlmiller.com/archives/2009/11/10/turning-off-regions-in-resharper/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Review: Brownfield Application Development in .Net</title>
		<link>http://www.johnlmiller.com/archives/2009/08/29/review-brownfield-application-development-in-net/</link>
		<comments>http://www.johnlmiller.com/archives/2009/08/29/review-brownfield-application-development-in-net/#comments</comments>
		<pubDate>Sat, 29 Aug 2009 21:56:42 +0000</pubDate>
		<dc:creator>John Miller</dc:creator>
		
		<category><![CDATA[.Net]]></category>

		<category><![CDATA[Book Review]]></category>

		<guid isPermaLink="false">http://www.johnlmiller.com/?p=219</guid>
		<description><![CDATA[I just finished reading Brownfield Application Development in .Net by Kyle Baley and Donald Belcham and thought I’d put together a quick review some of the strengths and weaknesses the book has to offer. 
It’s broken up into two sections with the first half of the book describing how to create a healthy ecosystem for [...]]]></description>
			<content:encoded><![CDATA[<p>I just finished reading <a href="http://www.manning.com/baley/" target="_blank">Brownfield Application Development in .Net</a> by Kyle Baley and Donald Belcham and thought I’d put together a quick review some of the strengths and weaknesses the book has to offer. </p>
<p>It’s broken up into two sections with the first half of the book describing how to create a healthy ecosystem for you code to grow in. This gets into areas such as project structure, automated testing, automated builds, continuous integration, etc. They even get into some of the various personas you may run into when working on a Brownfield application (such as the “Ivory Tower Architect” and “The Hero Developer”) and how to effectively work with those personalities. The second half of the book discusses how to make the code itself flexible and maintainable. This includes everything from design patterns to explaining how to create an anti-corruption layer in your code to minimize the impact changes will make on your software in the future.</p>
<p>One of my personal favorite sections included in the book was the awesome explanation of the differences between MVP and MVC patterns. Very clear and concise. I had struggled in the past really understanding the finer points of how the two differed, but the author did a great job comparing the two (as well as their variations). </p>
<p>There are lot of good book available on agile development techniques and software design principles, but this has to be the best I’ve read yet that explains the nuts and bolts of how to apply these ideals to .Net development. There are a lot of great tidbits in there that can be applied to development in any language (although the book is really geared towards tools that are readily available to .Net developers). </p>
<p>And now for a little constructive criticism. The first few chapters, while very informative, seemed to be longer than they should have been. Those could have been reduced by about 25-30% without losing any value. I also felt a little short-changed by it’s explanation of AOP in chapter 8. It started discussing AOP and even gave a code example, but didn’t go deep enough to really explain it clearly. And to be fair, as the book stated, explaining AOP was well beyond the scope of the book, which I fully agree with. But I think that it would have been better to scale back the attempted explanation if it wasn’t going to give a thorough explanation. </p>
<p>All in all though, this is (by far) my favorite .Net specific development book (and I’ve read quite a few!). It offers a lot of practical advice that you <strike>can</strike> should start applying right away. It hasn’t been released yet, but is available from Manning via their <a href="http://www.manning.com/baley/" target="_blank">Early Access program</a>. If you’re a .Net developer, regardless of whether or not you’re working on Brownfield applications, I’d highly recommend it!</p>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=John%20Miller&amp;siteurl=http%3A%2F%2Fwww.johnlmiller.com%2F&amp;linkname=Review%3A%20Brownfield%20Application%20Development%20in%20.Net&amp;linkurl=http%3A%2F%2Fwww.johnlmiller.com%2Farchives%2F2009%2F08%2F29%2Freview-brownfield-application-development-in-net%2F"><img src="http://www.johnlmiller.com/wp-content/plugins/add-to-any/share_save_171_16.gif" width="171" height="16" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://www.johnlmiller.com/archives/2009/08/29/review-brownfield-application-development-in-net/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Comparing Design Patterns in Ruby and C#: The Command Pattern (with Robots!)</title>
		<link>http://www.johnlmiller.com/archives/2009/08/28/comparing-design-patterns-in-ruby-and-c-the-command-pattern-with-robots/</link>
		<comments>http://www.johnlmiller.com/archives/2009/08/28/comparing-design-patterns-in-ruby-and-c-the-command-pattern-with-robots/#comments</comments>
		<pubDate>Fri, 28 Aug 2009 21:18:34 +0000</pubDate>
		<dc:creator>John Miller</dc:creator>
		
		<category><![CDATA[.Net]]></category>

		<category><![CDATA[Ruby]]></category>

		<category><![CDATA[C#]]></category>

		<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://www.johnlmiller.com/?p=213</guid>
		<description><![CDATA[The command pattern is another one of those patterns that we all (whether we realize it or not) see almost every day. It’s commonly used in UI development but it’s a pattern that can be applied in many situations. In rails, ActiveRecord migrations are a perfect example of a command implementation, including “up” and “down” [...]]]></description>
			<content:encoded><![CDATA[<p>The command pattern is another one of those patterns that we all (whether we realize it or not) see almost every day. It’s commonly used in UI development but it’s a pattern that can be applied in many situations. In rails, ActiveRecord migrations are a perfect example of a command implementation, including “up” and “down” methods for applying and rolling back a migration respectively.</p>
<p>The beauty of the command pattern is it’s ability to encapsulate complicated logic into an easy to use interface. This usually includes:</p>
<ol>
<li>An ICommand interface or base class that defines the command structure</li>
<li>Concrete command implementations</li>
<li>A receiver that is fed commands to execute. When these commands are actually executed is completely independent of when the receiver is given the commands. It may choose to execute them right away, but it may just as well decide to hold on to them for later use.</li>
</ol>
<h3>Source Code</h3>
<p>All of the code in this example is available to download:</p>
<p><a href="http://www.johnlmiller.com/downloads/CommandPattern.zip">Download the Source</a></p>
<p>Or, you can pull the source directly from github using the below clone url:</p>
<p>git://github.com/johnmiller/CommandPattern.git</p>
<h3>Example Overview</h3>
<p>The example below involves a robot that moves around on a XY plane similar to:</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="XYPlane" src="http://www.johnlmiller.com/wp-content/uploads/2009/08/xyplane.png" border="0" alt="XYPlane" /></p>
<p>The robot is given starting coordinates and moves from there. However, it can only perform certain actions:</p>
<ol>
<li>Move forward</li>
<li>Turn left</li>
<li>Turn right</li>
<li>Reset</li>
</ol>
<p>As it is given commands, it stores them in an internal collection. If reset is called, it “undo’s” all the commands executed to that point.</p>
<h3>C# Example</h3>
<p>The ICommand is pretty simple and only includes two method declarations: Execute() and Undo(). All of our concrete commands will need to implement this interface.</p>
<pre class="brush: csharp; ">

public interface ICommand
{
void Execute();
void Undo();
}
</pre>
<p>Before we create any concrete command classes, let’s take a look at our Robot class. When a new robot is created, we give it a starting location and direction. Notice that when a user calls ExecuteCommand() it immediately performs the instructions given and then stores the command in an internal list. If Reset() is called it iterates through the list in reverse order and calls Undo() on each.</p>
<pre class="brush: csharp; ">

public class Robot
{
public Location Position { get; set; }
public string Direction { get; set; }
private IList&lt;ICommand&gt; _commandsExecuted = new List&lt;ICommand&gt;();

public Robot(Location position, string direction)
{
Position = position;
Direction = direction;
}

public void ExecuteInstruction(ICommand command)
{
command.Execute();
_commandsExecuted.Add(command);
}

public void Reset()
{
foreach (var command in _commandsExecuted.Reverse())
command.Undo();
}
}
</pre>
<p>The Robot.Position property is of type Location which is a simple class holding the X and Y coordinates.</p>
<pre class="brush: csharp; ">

public class Location
{
public int X { get; set; }
public int Y { get; set; }

public Location(int x, int y)
{
X = x;
Y = y;
}
}
</pre>
<p>The first command we’ll look at is the MoveForwardCommand which…moves the robot forward one space. But we need to be sure that the robot is moving forward in the direction that it is facing. Internally it contains a list of algorithms for moving the robot depending on the based on it’s current direction. It can also go backwards if Undo() is called.</p>
<pre class="brush: csharp; ">

public class MoveForwardCommand : ICommand
{
private Robot _robot;
private IDictionary&lt;string, Action&lt;Robot&gt;&gt; _moveActions;

public MoveForwardCommand(Robot robot)
{
_robot = robot;
_moveActions = new Dictionary&lt;string, Action&lt;Robot&gt;&gt;
{
{&quot;N&quot;, r =&gt; r.Position.Y += 1 },
{&quot;E&quot;, r =&gt; r.Position.X += 1 },
{&quot;S&quot;, r =&gt; r.Position.Y -= 1 },
{&quot;W&quot;, r =&gt; r.Position.X -= 1 }
};
}

public void Execute()
{
_moveActions[_robot.Direction](_robot);
}

public void Undo()
{
var oppositeDirection = Compass.GetOppositeDirection(_robot.Direction);
_moveActions[oppositeDirection](_robot);
}
}
</pre>
<p>The Undo() method uses a class called Compass to find the backwards direction. This is a simple utility class to aid in finding left, right, and opposite directions. To find the direction to the right or left, we find the current direction&#8217;s place in the list and move accordingly. Although we need to ensure that when asked to turn right when facing west, it moves to the start of the list to get north (the opposite holds true when turning left when facing north).</p>
<pre class="brush: csharp; ">

public class Compass
{
private static IList&lt;string&gt; _directions = new List&lt;string&gt;{&quot;N&quot;, &quot;E&quot;, &quot;S&quot;, &quot;W&quot;};

public static string GetRightTurnDirection(string direction)
{
if (direction == _directions[3]) return _directions[0];

return _directions[_directions.IndexOf(direction) + 1];
}

public static string GetLeftTurnDirection(string direction)
{
if (direction == _directions[0]) return _directions[3];

return _directions[_directions.IndexOf(direction) - 1];
}

public static string GetOppositeDirection(string direction)
{
var directionToTheRight = GetRightTurnDirection(direction);
return GetRightTurnDirection(directionToTheRight);
}
}
</pre>
<p>The next set of commands we’ll create will allow the robot to turn left and right. This doesn’t change the space the robot is on, only the direction that it is looking.</p>
<pre class="brush: csharp; ">

public class TurnLeftCommand : ICommand
{
private Robot _robot;

public TurnLeftCommand(Robot robot)
{
_robot = robot;
}

public void Execute()
{
_robot.Direction = Compass.GetLeftTurnDirection(_robot.Direction);
}

public void Undo()
{
_robot.Direction = Compass.GetRightTurnDirection(_robot.Direction);
}
}

public class TurnRightCommand : ICommand
{
private Robot _robot;

public TurnRightCommand(Robot robot)
{
_robot = robot;
}

public void Execute()
{
_robot.Direction = Compass.GetRightTurnDirection(_robot.Direction);
}

public void Undo()
{
_robot.Direction = Compass.GetLeftTurnDirection(_robot.Direction);
}
}
</pre>
<p>Last, let’s take a look at a unit test that puts the robot to work (the source code linked to earlier in the post includes a lot more unit tests if you’re interested in seeing more!).</p>
<pre class="brush: csharp; ">

[TestFixture]
public class When_a_robot_is_given_multiple_commands
{
private Robot _robot;

[SetUp]
public void EstablishContext()
{
_robot = new Robot(new Location(5, 5), &quot;W&quot;);
_robot.ExecuteInstruction(new TurnLeftCommand(_robot));
_robot.ExecuteInstruction(new TurnLeftCommand(_robot));
_robot.ExecuteInstruction(new MoveForwardCommand(_robot));
_robot.ExecuteInstruction(new TurnRightCommand(_robot));
_robot.ExecuteInstruction(new MoveForwardCommand(_robot));
_robot.ExecuteInstruction(new TurnRightCommand(_robot));
_robot.ExecuteInstruction(new MoveForwardCommand(_robot));
_robot.ExecuteInstruction(new MoveForwardCommand(_robot));
_robot.ExecuteInstruction(new TurnRightCommand(_robot));
}

[Test]
public void Should_end_up_at_the_expected_location()
{
Assert.That(_robot.Position.X, Is.EqualTo(4));
Assert.That(_robot.Position.Y, Is.EqualTo(4)); ;
}

[Test]
public void Should_be_facing_the_expected_direction()
{
Assert.That(_robot.Direction, Is.EqualTo(&quot;N&quot;));
}

[Test]
public void Should_be_able_to_undo_the_command()
{
_robot.Reset();
Assert.That(_robot.Position.X, Is.EqualTo(5));
Assert.That(_robot.Position.Y, Is.EqualTo(5));
Assert.That(_robot.Direction, Is.EqualTo(&quot;W&quot;));
}
}
</pre>
<h3>Ruby Example</h3>
<p>With ruby we won’t need to create an abstraction for our command objects, so we’ll jump right into creating our Robot object. Besides basic syntax differences, this is very similar to our C# implementation.</p>
<pre class="brush: ruby; ">

class Robot
attr_accessor :position, :direction

def initialize(position, direction)
@position = position
@direction = direction
@commands_executed = []
end

def execute_instruction(command)
command.execute
@commands_executed &lt;&lt; command
end

def reset
@commands_executed.reverse_each{|x| x.undo}
end
end
</pre>
<p>It also uses a custom Location class to store X and Y coordinates.</p>
<pre class="brush: ruby; ">

class Location
attr_accessor :x, :y

def initialize(x, y)
@x = x
@y = y
end
end
</pre>
<p>Next up is the MoveForwardCommand. The @move_action variable contains a hash of Proc objects which contain the logic for moving the robot. Note that we use the “call” method to run the proc.</p>
<pre class="brush: ruby; ">

class MoveForwardCommand
def initialize(robot)
@robot = robot
@move_actions = {:N =&gt; Proc.new{|r| r.position.y += 1},
:E =&gt; Proc.new{|r| r.position.x += 1},
:S =&gt; Proc.new{|r| r.position.y -= 1},
:W =&gt; Proc.new{|r| r.position.x -= 1}}
end

def execute
@move_actions[@robot.direction].call @robot
end

def undo
opposite_direction = Compass.get_opposite_direction @robot.direction
@move_actions[opposite_direction].call @robot
end
end
</pre>
<p>Like our C# example, we make use of a custom Compass class to help find our directions. I really like the explicit “first” and “last” properties that come with the array object, seems to make the code a little easier to read.</p>
<pre class="brush: ruby; ">

class Compass
@directions = [:N, :E, :S, :W]

def self.get_right_turn_direction(direction)
return @directions.first if direction == @directions.last
@directions[@directions.index(direction) + 1]
end

def self.get_left_turn_direction(direction)
return @directions.last if direction == @directions.first
@directions[@directions.index(direction) - 1]
end

def self.get_opposite_direction(direction)
direction_to_the_right = get_right_turn_direction direction
get_right_turn_direction direction_to_the_right
end
end
</pre>
<p>And our commands to allow the robot to turn left and right.</p>
<pre class="brush: ruby; ">

class TurnLeftCommand
def initialize(robot)
@robot = robot
end

def execute
@robot.direction = Compass.get_left_turn_direction @robot.direction
end

def undo
@robot.direction = Compass.get_right_turn_direction @robot.direction
end
end

class TurnRightCommand
def initialize(robot)
@robot = robot
end

def execute
@robot.direction = Compass.get_right_turn_direction @robot.direction
end

def undo
@robot.direction = Compass.get_left_turn_direction @robot.direction
end
end
</pre>
<p>Last we’ll take a look at a unit test to that puts the robot through it’s paces. (There are also many more tests in the source code download if you’d like see more examples).</p>
<pre class="brush: ruby; ">

describe &quot;When asked to perform multiple commands&quot; do
before(:each) do
@robot = Robot.new Location.new(5,5), :W
@robot.execute_instruction TurnLeftCommand.new(@robot)
@robot.execute_instruction TurnLeftCommand.new(@robot)
@robot.execute_instruction MoveForwardCommand.new(@robot)
@robot.execute_instruction TurnRightCommand.new(@robot)
@robot.execute_instruction MoveForwardCommand.new(@robot)
@robot.execute_instruction TurnRightCommand.new(@robot)
@robot.execute_instruction MoveForwardCommand.new(@robot)
@robot.execute_instruction MoveForwardCommand.new(@robot)
@robot.execute_instruction TurnRightCommand.new(@robot)
end

it &quot;should end up at the expected location&quot; do
@robot.position.x.should == 4
@robot.position.y.should == 4
end

it &quot;should be facing the expected direction&quot; do
@robot.direction.should == :N
end

it &quot;should be able to undo all of the commands&quot; do
@robot.reset
@robot.position.x.should == 5
@robot.position.y.should == 5
@robot.direction.should == :W
end
end
</pre>
<p>In our next post we’ll take a look at how we can solve the same problem using the State pattern!</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.johnlmiller.com%2farchives%2f2009%2f08%2f28%2fcomparing-design-patterns-in-ruby-and-c-the-command-pattern-with-robots%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.johnlmiller.com%2farchives%2f2009%2f08%2f28%2fcomparing-design-patterns-in-ruby-and-c-the-command-pattern-with-robots%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=John%20Miller&amp;siteurl=http%3A%2F%2Fwww.johnlmiller.com%2F&amp;linkname=Comparing%20Design%20Patterns%20in%20Ruby%20and%20C%23%3A%20The%20Command%20Pattern%20%28with%20Robots%21%29&amp;linkurl=http%3A%2F%2Fwww.johnlmiller.com%2Farchives%2F2009%2F08%2F28%2Fcomparing-design-patterns-in-ruby-and-c-the-command-pattern-with-robots%2F"><img src="http://www.johnlmiller.com/wp-content/plugins/add-to-any/share_save_171_16.gif" width="171" height="16" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://www.johnlmiller.com/archives/2009/08/28/comparing-design-patterns-in-ruby-and-c-the-command-pattern-with-robots/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Comparing Design Patterns in Ruby and C#: The Iterator Pattern</title>
		<link>http://www.johnlmiller.com/archives/2009/08/05/comparing-design-patterns-in-ruby-and-c-the-iterator-pattern/</link>
		<comments>http://www.johnlmiller.com/archives/2009/08/05/comparing-design-patterns-in-ruby-and-c-the-iterator-pattern/#comments</comments>
		<pubDate>Wed, 05 Aug 2009 18:01:54 +0000</pubDate>
		<dc:creator>John Miller</dc:creator>
		
		<category><![CDATA[.Net]]></category>

		<category><![CDATA[Ruby]]></category>

		<category><![CDATA[C#]]></category>

		<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://www.johnlmiller.com/?p=201</guid>
		<description><![CDATA[Continuing our exploration of design patterns in Ruby and C#, we’re going to dive into the Iterator pattern. Like most design patterns, if you google (or bing) for an example you will run into several different implementations because there are many ways to iterate a collection of objects. In it’s classic (well, classing in the [...]]]></description>
			<content:encoded><![CDATA[<p>Continuing our exploration of design patterns in Ruby and C#, we’re going to dive into the Iterator pattern. Like most design patterns, if you google (or bing) for an example you will run into several different implementations because there are many ways to iterate a collection of objects. In it’s classic (well, classing in the .Net\Java sense) form, the pattern is made of:</p>
<ol>
<li>An interface defining the iterator. This typically involves two methods: HasNext() and MoveNext().</li>
<li>An concrete iterator implementation</li>
<li>An interface defining an enumerable collection. The only method really needed here would be GetIterator() which will return the iterator object.</li>
<li>A concrete enumerable implementation.</li>
</ol>
<p>The book <a href="http://www.amazon.com/Design-Patterns-Ruby-Addison-Wesley-Professional/dp/0321490452" target="_blank">Design Patterns in Ruby</a> actually defines that type of implementation as an external iterator. This form gives you a type of hook into the collection that allows you to pull out an object one at a time and work with it externally, away from the insides of the collection. The other type of implementation that it describes is an internal iterator. This form involves a method that passes logic (think anonymous method in C# or code block in Ruby) into a method on the collection. The collection then internally iterates through it’s items and applies the logic on each item. This is a very common way of working with collections in Ruby and is slowly building adoption in C#. As we work through the examples below, we’ll take a look at both external and internal implementations.</p>
<p>The following examples will consist of a used car sales lot which will consist of a collection of vehicles.</p>
<h3>C# Example - External Iterator From Scratch</h3>
<p>First off, let&#8217;s create a basic Vehicle object.</p>
<pre class="brush: csharp; ">

public class Vehicle
{
    public string Name { get; set; }

    public Vehicle(string name)
    {
        Name = name;
    }
}
</pre>
<p>Our next step is to create an ISimpleIterator interface which we&#8217;re going to make generic so we aren&#8217;t tied to a specific type of object. It really only needs two methods, HasNext() which will let us know if we&#8217;ve reached the end of the collection, and MoveNext() which will return the item in the next position.</p>
<pre class="brush: csharp; ">

public interface ISimpleIterator&lt;T&gt;
{
    bool HasNext();
    T MoveNext();
}
</pre>
<p>And now we&#8217;ll create a concrete implementation of the iterator.</p>
<pre class="brush: csharp; ">

public class SimpleIterator&lt;T&gt; : ISimpleIterator&lt;T&gt;
{
    private int _position = 0;
    private T[] _items;

    public SimpleIterator(T[] items)
    {
        _items = items;
    }

    public bool HasNext()
    {
        return _position &lt; _items.Length;
    }

    public T MoveNext()
    {
        var item = _items[_position];
        _position++;
        return item;
    }
}
</pre>
<p>Next, let&#8217;s create our ISimpleEnumerable interface. We&#8217;ll keep this one generic as well since there&#8217;s no reason to lock it into only Vehicle objects. Note that it only needs one method that will return a generic ISimpleIterator.</p>
<pre class="brush: csharp; ">

public interface ISimpleEnumerable&lt;T&gt;
{
    ISimpleIterator&lt;T&gt; GetIterator();
}
</pre>
<p>And our enumerable object will be a SalesLot entity. The GetIterator() method will return a strongly typed vehicle iterator.</p>
<pre class="brush: csharp; ">

public class SalesLot : ISimpleEnumerable&lt;Vehicle&gt;
{
    private Vehicle[] _vehicles = {
                                     new Vehicle(&quot;Toyota Camry&quot;),
                                     new Vehicle(&quot;Jeep Grand Cherokee&quot;),
                                     new Vehicle(&quot;Honda CRV&quot;)
                                 };

    public ISimpleIterator&lt;Vehicle&gt; GetIterator()
    {
        return new SimpleIterator&lt;Vehicle&gt;(_vehicles);
    }
}
</pre>
<p>Let&#8217;s see what this code would actually look like if we tried to run it. All we have to do is grab the iterator and wrap it in a while loop.</p>
<pre class="brush: csharp; ">

var salesLot = new SalesLot();
var vehiclesIterator = salesLot.GetIterator();

while (vehiclesIterator.HasNext())
    Console.WriteLine(vehiclesIterator.MoveNext().Name);
</pre>
<p><strong>Output:</strong><br />
<em><br />
Toyota Camry<br />
Jeep Grand Cherokee<br />
Honda CRV<br />
</em></p>
<h3>C# Example - External Iterator Using Built-In IEnumerable<T> Interface</h3>
<p>Our design can be hugely simplified by using the IEnumerable<T> interface from the base class library. In the below code sample, our SalesLot object no longer returns an ISimpleIterator<T>, instead it&#8217;s passes back a IEnumerator<T> which is also built in the .Net framework. The two GetEnumerator() methods are all that&#8217;s needed to fulfill the IEnumerable interface contract. And since all built-in collections implement this interface, we can easily pass that call to the inner list.</p>
<pre class="brush: csharp; ">

public class SalesLot : IEnumerable&lt;Vehicle&gt;
{
    private IEnumerable&lt;Vehicle&gt; _vehicles = new List&lt;Vehicle&gt; {
                                     new Vehicle(&quot;Toyota Camry&quot;),
                                     new Vehicle(&quot;Jeep Grand Cherokee&quot;),
                                     new Vehicle(&quot;Honda CRV&quot;)
                                 };

    public IEnumerator&lt;Vehicle&gt; GetEnumerator()
    {
        return _vehicles.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}
</pre>
<p>And using it is just as easy as our earlier example.</p>
<pre class="brush: csharp; ">

var salesLot = new SalesLot();
var enumerator = salesLot.GetEnumerator();

while (enumerator.MoveNext())
    Console.WriteLine(enumerator.Current.Name);
</pre>
<p>And any class that implements the IEnumerable interface is also able to be iterated over using the foreach construct.</p>
<pre class="brush: csharp; ">

var salesLot = new SalesLot();

foreach (var vehicle in salesLot)
    Console.WriteLine(vehicle.Name); 
</pre>
<h3>C# Example - Adding an Internal Iterator to the SalesLot Class</h3>
<p>The previous examples all used external iterators to navigate the collection of cars. But we could have easily used an internal iterator as well. To do this, we need to add a method to the SalesLot object that will allow us to pass in an anonymous method or lambda expression to apply to each vehicle in the collection.</p>
<pre class="brush: csharp; ">

public class SalesLot
{
    private IEnumerable&lt;Vehicle&gt; _vehicles = new List&lt;Vehicle&gt; {
                                     new Vehicle(&quot;Toyota Camry&quot;),
                                     new Vehicle(&quot;Jeep Grand Cherokee&quot;),
                                     new Vehicle(&quot;Honda CRV&quot;)
                                 };

    public void ForEach(Action&lt;Vehicle&gt; action)
    {
        foreach (var vehicle in _vehicles)
            action(vehicle);
    }
}
</pre>
<p>And using it becomes just a couple lines of code.</p>
<pre class="brush: csharp; ">

var salesLot = new SalesLot();
salesLot.ForEach(vehicle =&gt; Console.WriteLine(vehicle.Name));
</pre>
<h3>C# Example - Internal Iterator Using the Built-In ForEach List<T> Extension Method</h3>
<p>With the addition of Linq, we were given a ForEach extension method on generic lists. Using it is exactly the same as our hand-rolled example.</p>
<pre class="brush: csharp; ">

var salesLot = new List&lt;Vehicle&gt; {
                             new Vehicle(&quot;Toyota Camry&quot;),
                             new Vehicle(&quot;Jeep Grand Cherokee&quot;),
                             new Vehicle(&quot;Honda CRV&quot;)
                         };

salesLot.ForEach(vehicle =&gt; Console.WriteLine(vehicle.Name));
</pre>
<h3>Ruby Example - External Iterator From Scratch</h3>
<p>To get started with our Ruby examples, we&#8217;ll create our Vehicle object.</p>
<pre class="brush: ruby; ">

class Vehicle
  attr_accessor :name

  def initialize(name)
    @name = name
  end
end
</pre>
<p>And since Ruby suports duck-typing, we don&#8217;t need to create an abstract class or interface to define our iterator. We just need to make sure it has the appropriate methods. Notice that our functions that return a value (such as has_next or move_next) do not need to include the &#8220;return&#8221; keyword. In Ruby the last line of a mehod is the return value.</p>
<pre class="brush: ruby; ">

class SimpleIterator
  def initialize(items)
    @items = items
    @position = 0
  end

  def has_next
    @position &lt; @items.length
  end

  def move_next
    item = @items[@position]
    @position += 1
    item
  end
end
</pre>
<p>We are also free to go ahead with creating the SalesLot class without defining an Enumerable abstraction as long as we include a get_iterator method that returns a SimpleIterator.</p>
<pre class="brush: ruby; ">

class SalesLot
  def initialize
    @vehicles = [Vehicle.new(&quot;Toyota Camry&quot;), Vehicle.new(&quot;Jeep Grand Cherokee&quot;), Vehicle.new(&quot;Honda CRV&quot;)]
  end

  def get_iterator
    SimpleIterator.new(@vehicles)
  end
end
</pre>
<p>Actually using the class is very similiar to the C# example.</p>
<pre class="brush: ruby; ">

sales_lot = SalesLot.new
vehicle_iterator = sales_lot.get_iterator

while vehicle_iterator.has_next
  puts vehicle_iterator.move_next.name
end
</pre>
<p><strong>Output:</strong><br />
<em><br />
Toyota Camry<br />
Jeep Grand Cherokee<br />
Honda CRV<br />
</em></p>
<h3>Ruby Example - Creating an Internal Iterator Using the Enumerable Module</h3>
<p>While external iterators have their place, Rubyists tend to favor using internal iterators when working with collections. We could easily tack on our own for_each method to the SalesLot object (as we did in the C# example) but instead let&#8217;s jump straight into some of the cool things we can leverage in the library. Ruby ships with a handy module called Enumerable that we can include on our SalesLot object which will give us a lot of functionality for free. To use it, we just need to include the Enumerator module and add an &#8220;each&#8221; method that accepts a code block.</p>
<pre class="brush: ruby; ">

class SalesLot
  include Enumerable

  def initialize
    @vehicles = [Vehicle.new(&quot;Toyota Camry&quot;), Vehicle.new(&quot;Jeep Grand Cherokee&quot;), Vehicle.new(&quot;Honda CRV&quot;)]
  end

  def each(&amp;amp;amp;amp;amp;amp;block)
    @vehicles.each(&amp;amp;amp;amp;amp;amp;block)
  end
end
</pre>
<p>To be able to take advantage of the features given to us from the Enumerable module, our Vehicle needs to add a method defining the &#8220;<=>&#8221; comparison operator. This method accepts another Vehicle record to compare to and will return -1, 0, or 1 depending on whether the receiver is less than, equal to, or greater than the vehicle being passed in as an argument. For those of you familiar with the IComparable<T> interface in .Net, this works exactly the same way.</p>
<pre class="brush: ruby; ">

class Vehicle
  attr_accessor :name

  def initialize(name)
    @name = name
  end

  def &lt;=&gt;(other)
    @name &lt;=&gt; other.name
  end
end
</pre>
<p>And now we can iterate through our collection in just a couple of lines.</p>
<pre class="brush: ruby; ">

sales_lot = SalesLot.new
sales_lot.each {|vehicle| puts vehicle.name}
</pre>
<p>But that&#8217;s just the tip of the iceberg. We are given a lot of added functionality that allows us to search and sort vehicles in the sales lot.</p>
<pre class="brush: ruby; ">

sales_lot.include? &quot;Ford Escape&quot;
sales_lot.find_all {|vehicle| vehicle.name.length &gt; 12}
sales_lot.sort
</pre>
<p>And this functionality is available when working with arrays which allows us to do a lot of work with our collections without having to write much code.</p>
<pre class="brush: ruby; ">

vehicles = [Vehicle.new(&quot;Toyota Camry&quot;), Vehicle.new(&quot;Jeep Grand Cherokee&quot;), Vehicle.new(&quot;Honda CRV&quot;)]
vehicles.each {|vehicle| puts vehicle.name}
</pre>
<p>While the iterator pattern may look complex in it&#8217;s natural form, both Ruby and C# give us a lot of capabilities out of the box. Neither need much (if any) customization to do advanced work with collections. </p>
<p>Next time, we&#8217;ll check out the Command pattern!</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.johnlmiller.com%2farchives%2f2009%2f08%2f05%2fcomparing-design-patterns-in-ruby-and-c-the-iterator-pattern%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.johnlmiller.com%2farchives%2f2009%2f08%2f05%2fcomparing-design-patterns-in-ruby-and-c-the-iterator-pattern%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=John%20Miller&amp;siteurl=http%3A%2F%2Fwww.johnlmiller.com%2F&amp;linkname=Comparing%20Design%20Patterns%20in%20Ruby%20and%20C%23%3A%20The%20Iterator%20Pattern&amp;linkurl=http%3A%2F%2Fwww.johnlmiller.com%2Farchives%2F2009%2F08%2F05%2Fcomparing-design-patterns-in-ruby-and-c-the-iterator-pattern%2F"><img src="http://www.johnlmiller.com/wp-content/plugins/add-to-any/share_save_171_16.gif" width="171" height="16" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://www.johnlmiller.com/archives/2009/08/05/comparing-design-patterns-in-ruby-and-c-the-iterator-pattern/feed/</wfw:commentRss>
		</item>
		<item>
		<title>We Don&#8217;t Need Another Hero</title>
		<link>http://www.johnlmiller.com/archives/2009/07/28/we-dont-need-another-hero/</link>
		<comments>http://www.johnlmiller.com/archives/2009/07/28/we-dont-need-another-hero/#comments</comments>
		<pubDate>Tue, 28 Jul 2009 15:45:25 +0000</pubDate>
		<dc:creator>John Miller</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[inspiration]]></category>

		<guid isPermaLink="false">http://www.johnlmiller.com/?p=198</guid>
		<description><![CDATA[I just began reading Brownfield Application Development in .Net and came across a statement that I found very interesting. 
&#34;We Don&#8217;t Need Another Hero&#34; 
The book does an awesome job describing something called the &#34;Hero Programmer Syndrome&#34;. This is defined as someone who will do whatever it takes to meet ridiculous deadlines. They may come [...]]]></description>
			<content:encoded><![CDATA[<p>I just began reading <a href="http://www.amazon.com/Brownfield-Application-Development-Donald-Belcham/dp/1933988711/ref=sr_1_1?ie=UTF8&amp;qid=1248795812&amp;sr=8-1" target="_blank">Brownfield Application Development in .Net</a> and came across a statement that I found very interesting. </p>
<p><em>&quot;We Don&#8217;t Need Another Hero&quot; </em></p>
<p>The book does an awesome job describing something called the &quot;Hero Programmer Syndrome&quot;. This is defined as someone who will do whatever it takes to meet ridiculous deadlines. They may come in early, stay late, trade family time for work time, etc. They are usually the only person on the team with working knowledge of how the many parts of an system work together. They make sure stuff gets done. And when they produce super-human results, they (not the team) are rewarded by management. </p>
<p>A team will actually run more efficiently if the responsibilities (and resulting glories) are spread out across the entire team. This creates a feeling of collective-ownership which empowers all team members to take pride in the application being developed as well as get them to learn about the entire application stack instead of just focusing on their own little piece of the pie. It also makes adapting to change much easier if management can depend on any member of the team to get a task done instead of just the &quot;hero developer&quot;. </p>
<p>I&#8217;m only in the first chapter, but so far this book has been a great read!</p>
<div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"><a href="http://www.dotnetkicks.com/kick/?url=http://www.johnlmiller.com/?p=198"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://www.johnlmiller.com/?p=198&amp;bgcolor=0080C0&amp;fgcolor=FFFFFF&amp;border=000000&amp;cbgcolor=D4E1ED&amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"></a></div>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=John%20Miller&amp;siteurl=http%3A%2F%2Fwww.johnlmiller.com%2F&amp;linkname=We%20Don%26rsquo%3Bt%20Need%20Another%20Hero&amp;linkurl=http%3A%2F%2Fwww.johnlmiller.com%2Farchives%2F2009%2F07%2F28%2Fwe-dont-need-another-hero%2F"><img src="http://www.johnlmiller.com/wp-content/plugins/add-to-any/share_save_171_16.gif" width="171" height="16" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://www.johnlmiller.com/archives/2009/07/28/we-dont-need-another-hero/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Comparing Design Patterns in Ruby and C#: The Composite Pattern</title>
		<link>http://www.johnlmiller.com/archives/2009/07/22/comparing-design-patterns-in-ruby-and-c-the-composite-pattern/</link>
		<comments>http://www.johnlmiller.com/archives/2009/07/22/comparing-design-patterns-in-ruby-and-c-the-composite-pattern/#comments</comments>
		<pubDate>Wed, 22 Jul 2009 13:17:45 +0000</pubDate>
		<dc:creator>John Miller</dc:creator>
		
		<category><![CDATA[.Net]]></category>

		<category><![CDATA[Ruby]]></category>

		<category><![CDATA[C#]]></category>

		<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://www.johnlmiller.com/?p=181</guid>
		<description><![CDATA[In the last post of the series, we took a look at the Observer pattern. This time we&#8217;re going to explore the Composite pattern. The Composite pattern gives us the ability to take a complex procedure that may involve many steps and turn it into something that is simple for consumers to use. 
The classic [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://www.johnlmiller.com/archives/2009/07/15/compare-design-patterns-in-ruby-and-c-the-observer-pattern/">last post</a> of the series, we took a look at the Observer pattern. This time we&#8217;re going to explore the Composite pattern. The Composite pattern gives us the ability to take a complex procedure that may involve many steps and turn it into something that is simple for consumers to use. </p>
<p>The classic definition of the Composite pattern involves three pieces: Component, Leaf, and Composite Component. The component defines the interface that the units (leaves and\or composite components) must implement. A leaf is an implementation of a component that performs work. The composite component also implements the component interface but that’s where the similarities end. Under the covers, it contains a collection of components which could be leaves on nested composites. When an interface method is called, it delegates the call to it’s child components. This may sound more complicated than it actually is. Let’s take a look at an example to see how this could work.</p>
<h3>C# Example</h3>
<p>In this example, we&#8217;re going to take the process of changing a car&#8217;s oil and break it down to a group of independent tasks. Following our definition above, let&#8217;s define an IComponent interface. Per the contract of this interface, all of our &#8220;task&#8221; objects will need to include a PerformTask() method.</p>
<pre class="brush: csharp; ">

public interface IComponent
{
    void PerformTask();
}
</pre>
<p>Next, we&#8217;re going to create a base class for the tasks that are made up of a collection of child tasks. Notice that although it implements the PerformTask() method of the IComponent interface, it actually delegates the work to it&#8217;s child components.</p>
<pre class="brush: csharp; ">

public abstract class CompositeComponent : IComponent
{
    private IList&lt;IComponent&gt; _tasks = new List&lt;IComponent&gt;();

    public void PerformTask()
    {
        foreach (var task in _tasks)
            task.PerformTask();
    }

    public void AddTask(IComponent task)
    {
        _tasks.Add(task);
    }

    public void RemoveTask(IComponent task)
    {
        _tasks.Remove(task);
    }
}
</pre>
<p>Now let&#8217;s create our first needed task (aka. leaf). This one represents the draining of the old oil in the vehicle.</p>
<pre class="brush: csharp; ">

public class DrainOldOilTask : IComponent
{
    public void PerformTask()
    {
        Console.WriteLine(&quot;Draining old oil.&quot;);
    }
}
</pre>
<p>The next step is to replace the oil filter which is made of two steps, removing the old filter and installing the new one. To demonstrate this, we&#8217;ll create a new CompositeComponent subclass.</p>
<pre class="brush: csharp; ">

public class RemoveOldFilterTask : IComponent
{
    public void PerformTask()
    {
        Console.WriteLine(&quot;Removing old filter.&quot;);
    }
}

public class InstallNewFilterTask : IComponent
{
    public void PerformTask()
    {
        Console.WriteLine(&quot;Installing new filter.&quot;);
    }
}

public class ReplaceFilterTask : CompositeComponent
{
    public ReplaceFilterTask()
    {
        AddTask(new RemoveOldFilterTask());
        AddTask(new InstallNewFilterTask());
    }
}
</pre>
<p>Last, we need to create a task for adding the new oil as well as a composite &#8220;ChangeOil&#8221; task that ties it all together. Notice that the ChangeOil object is composed of both regular tasks (DrainOilTask and AddNewOilTask) as well as a composite task (ReplaceFilterTask). </p>
<pre class="brush: csharp; ">

public class AddNewOilTask : IComponent
{
    public void PerformTask()
    {
        Console.WriteLine(&quot;Adding new oil.&quot;);
    }
}

public class ChangeOil : CompositeComponent
{
    public ChangeOil()
    {
        AddTask(new DrainOldOilTask());
        AddTask(new ReplaceFilterTask());
        AddTask(new AddNewOilTask());
    }
}
</pre>
<p>Now the entire process is a simple method call.</p>
<pre class="brush: csharp; ">

new ChangeOil().PerformTask();
</pre>
<p><strong>Output</strong><br />
<em>Draining old oil.<br />
Removing old filter.<br />
Installing new filter.<br />
Adding new oil.</em></p>
<h3>Ruby Example</h3>
<p>With Ruby, we no longer need to define a component interface. We just need ensure that our classes define a perform_work() method. We will, however, want to create a base class for our composite components.</p>
<pre class="brush: ruby; ">

class CompositeComponent
  def initialize
    @tasks = []
  end

  def perform_task
    @tasks.each {|task| task.perform_task}
  end

  def add_task(task)
    @tasks &lt;&lt; task
  end

  def remove_task(task)
    @tasks.delete task
  end
end
</pre>
<p>Now we&#8217;ll create our task objects. Besides basic syntax, the structure of these classes are pretty much the same C# versions.</p>
<pre class="brush: ruby; ">

class DrainOldOilTask
  def perform_task
    puts &quot;Draining old oil.&quot;
  end
end

class RemoveOldFilterTask
  def perform_task
    puts &quot;Removing old filter.&quot;
  end
end

class InstallNewFilterTask
  def perform_task
    puts &quot;Installing new filter.&quot;
  end
end

class ReplaceFilterTask &lt; CompositeComponent
   def initialize
     super
     add_task RemoveOldFilterTask.new
     add_task InstallNewFilterTask.new
   end
end

class AddNewOilTask
  def perform_task
    puts &quot;Adding new oil.&quot;
  end
end

class ChangeOil &lt; CompositeComponent
   def initialize
     super
     add_task DrainOldOilTask.new
     add_task ReplaceFilterTask.new
     add_task AddNewOilTask.new
   end
end
</pre>
<p>Using the objects is also very much the same.</p>
<pre class="brush: ruby; ">

ChangeOil.new.perform_task
</pre>
<p><strong>Output</strong><br />
<em>Draining old oil.<br />
Removing old filter.<br />
Installing new filter.<br />
Adding new oil.</em></p>
<p>As you can see, implementing the pattern in the two languages is pretty similar. The biggest difference is the lack of need for a component interface within the Ruby example.</p>
<p>Next time, we&#8217;ll be looking at the Iterator pattern. Stay tuned!</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.johnlmiller.com%2farchives%2f2009%2f07%2f22%2fcomparing-design-patterns-in-ruby-and-c-the-composite-pattern%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.johnlmiller.com%2farchives%2f2009%2f07%2f22%2fcomparing-design-patterns-in-ruby-and-c-the-composite-pattern%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=John%20Miller&amp;siteurl=http%3A%2F%2Fwww.johnlmiller.com%2F&amp;linkname=Comparing%20Design%20Patterns%20in%20Ruby%20and%20C%23%3A%20The%20Composite%20Pattern&amp;linkurl=http%3A%2F%2Fwww.johnlmiller.com%2Farchives%2F2009%2F07%2F22%2Fcomparing-design-patterns-in-ruby-and-c-the-composite-pattern%2F"><img src="http://www.johnlmiller.com/wp-content/plugins/add-to-any/share_save_171_16.gif" width="171" height="16" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://www.johnlmiller.com/archives/2009/07/22/comparing-design-patterns-in-ruby-and-c-the-composite-pattern/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Comparing Design Patterns in Ruby and C#: The Observer Pattern</title>
		<link>http://www.johnlmiller.com/archives/2009/07/15/compare-design-patterns-in-ruby-and-c-the-observer-pattern/</link>
		<comments>http://www.johnlmiller.com/archives/2009/07/15/compare-design-patterns-in-ruby-and-c-the-observer-pattern/#comments</comments>
		<pubDate>Wed, 15 Jul 2009 19:39:34 +0000</pubDate>
		<dc:creator>John Miller</dc:creator>
		
		<category><![CDATA[.Net]]></category>

		<category><![CDATA[Ruby]]></category>

		<category><![CDATA[C#]]></category>

		<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://www.johnlmiller.com/?p=163</guid>
		<description><![CDATA[Continuing our comparison of design patterns in Ruby and C#, we’re taking a look at the Observer pattern. With this pattern, we have a subject and a list of observers that are interested in knowing when changes occur on the subject. This happens in a push model, the subject maintains the list observers and notifies [...]]]></description>
			<content:encoded><![CDATA[<p>Continuing our comparison of design patterns in Ruby and C#, we’re taking a look at the Observer pattern. With this pattern, we have a subject and a list of observers that are interested in knowing when changes occur on the subject. This happens in a push model, the subject maintains the list observers and notifies each when needed.</p>
<p>In our examples, we’re going to create a Vehicle object that contains a couple of key properties, Mileage and MileageAtLastOilChange. When a new Vehicle instance is created both properties start at zero. As the vehicle’s Drive() method is called and miles are added to it, it notifies any known observers. The MilesUntilNextOilChange property lets others know how long the vehicle can be driven until it should get an oil change. When the PerformOilChangeMethod() is called, the MileageAtLastOilChange property is set to the current mileage and registered observers are notified that changes occurred. </p>
<p>We are also going to create a Dashboard object that will let us know how many miles the vehicle can be driven until it needs it’s next oil change as well as a warning message alerting the driver that it needs a oil change when it reaches 3000 miles.</p>
<h3>C# Example</h3>
<p>First we’ll create our Vehicle object as well as an IVehicleObserver interface that must be implemented by any Vehicle observers. Note that the Vehicle object contains an AddObserver() that allows observers to register themselves with the Vehicle.</p>
<pre class="brush: csharp; ">

using System.Collections.Generic;

namespace DesignPatterns.ObserverPattern
{
    public class Vehicle
    {
        private IList&lt;IVehicleObserver&gt; _observers = new List&lt;IVehicleObserver&gt;();

        public int Mileage { get; private set; }
        public int MileageAtLastOilChange { get; private set; }
        public int MilesUntilNextOilChange { get { return 3000 - (Mileage - MileageAtLastOilChange); } }

        public Vehicle()
        {
            Mileage = 0;
            MileageAtLastOilChange = 0;
        }

        public void Drive(int miles)
        {
            Mileage += miles;
            NotifyObservers();
        }

        public void PerformOilChange()
        {
            MileageAtLastOilChange = Mileage;
            NotifyObservers();
        }

        public void AddObserver(IVehicleObserver observer)
        {
            _observers.Add(observer);
        }

        private void NotifyObservers()
        {
            foreach (var observer in _observers)
                observer.Notify(this);
        }
    }
}
</pre>
<pre class="brush: csharp; ">

namespace DesignPatterns.ObserverPattern
{
    public interface IVehicleObserver
    {
        void Notify(Vehicle vehicle);
    }
}
</pre>
<p>And now we’ll create our Dashboard class which will implement the IVehicleObserver interface. When the Notify() method is called, it updates the Message property to reflect the vehicle’s current status.</p>
<pre class="brush: csharp; ">

namespace DesignPatterns.ObserverPattern
{
    public class Dashboard : IVehicleObserver
    {
        public string Message { get; private set; }

        public Dashboard()
        {
            Message = string.Empty;
        }

        public void Notify(Vehicle vehicle)
        {
            Message = vehicle.MilesUntilNextOilChange &lt;= 0
                      ? &quot;Time for an oil change!&quot;
                      : string.Format(&quot;Next oil change is due in {0} miles.&quot;, vehicle.MilesUntilNextOilChange);
        }
    }
}
</pre>
<p>Let’s take a look at how these two will work together.</p>
<pre class="brush: csharp; ">

var dashboard = new Dashboard();
var vehicle = new Vehicle();

vehicle.AddObserver(dashboard);

vehicle.Drive(2000);
Console.WriteLine(dashboard.Message);

vehicle.Drive(1500);
Console.WriteLine(dashboard.Message);

vehicle.PerformOilChange();
Console.WriteLine(dashboard.Message);

vehicle.Drive(1000);
Console.WriteLine(dashboard.Message);
</pre>
<p><img class="alignnone size-medium wp-image-167" title="Ruby Output" src="http://www.johnlmiller.com/wp-content/uploads/2009/07/observerpatterncsharpoutput.jpg" alt="" /></p>
<h3>Ruby Example</h3>
<p>The Ruby example really isn’t that much unlike the C# version. The big difference is that we don’t need to create an IVehicleObserver interface, we just need to make sure our Dashboard object has a “notify” method that accepts a Vehicle object. </p>
<pre class="brush: ruby; ">

class Vehicle
  attr_reader :mileage, :mileage_at_last_oil_change

  def initialize
    @mileage = 0
    @mileage_at_last_oil_change = 0
    @observers = []
  end

  def drive(miles)
    @mileage += miles
    notify_observers
  end

  def miles_until_next_oil_change
    3000 - (@mileage - @mileage_at_last_oil_change)
  end

  def perform_oil_change
    @mileage_at_last_oil_change = @mileage
    notify_observers
  end

  def add_observer(observer)
    @observers &lt;&lt; observer
  end

  private

  def notify_observers
    @observers.each {|observer| observer.notify self}
  end
end
</pre>
<pre class="brush: ruby; ">

class Dashboard
  attr_reader :message

  def initialize
    @message = &quot;&quot;
  end

  def notify(vehicle)
    @message = vehicle.miles_until_next_oil_change &lt;= 0 ?
                &quot;Time for an oil change!&quot; :
                &quot;Next oil change is due in #{vehicle.miles_until_next_oil_change} miles.&quot;
  end
end
</pre>
<p>And using the objects is very similiar to the C# example as well.</p>
<pre class="brush: ruby; ">

require &quot;dashboard&quot;
require &quot;vehicle&quot;

dashboard = Dashboard.new
vehicle = Vehicle.new

vehicle.add_observer dashboard

vehicle.drive 2000
puts dashboard.message

vehicle.drive 1500
puts dashboard.message

vehicle.perform_oil_change
puts dashboard.message

vehicle.drive 1000
puts dashboard.message
</pre>
<p><img class="alignnone size-medium wp-image-167" title="Ruby Output" src="http://www.johnlmiller.com/wp-content/uploads/2009/07/observerpatternrubyoutput.jpg" alt="" width="282" height="74" /></p>
<h3>Simplifying Our Objects</h3>
<p>Both languages have built-in mechanisms that we can take advantage of that can make implementing the Observer pattern easy.</p>
<p>In .Net, we&#8217;re given out-of-the-box event handling. We just need to create a delegate that defines the method our observers will use for receiving notifications. This reduces the need for an IVehicleObserver interface and simplifies our design.</p>
<pre class="brush: csharp; ">

public delegate void MilesChangedHandler(Vehicle vehicle);
</pre>
<pre class="brush: csharp; ">

public class Vehicle
{
    public int Mileage { get; private set; }
    public int MileageAtLastOilChange { get; private set; }
    public int MilesUntilNextOilChange { get { return 3000 - (Mileage - MileageAtLastOilChange); } }
    public event MilesChangedHandler MilesChangedEvent;

    public Vehicle()
    {
        Mileage = 0;
        MileageAtLastOilChange = 0;
    }

    public void Drive(int miles)
    {
        Mileage += miles;
        NotifyObservers();
    }

    public void PerformOilChange()
    {
        MileageAtLastOilChange = Mileage;
        NotifyObservers();
    }

    private void NotifyObservers()
    {
        if (MilesChangedEvent != null)
            MilesChangedEvent(this);
    }
}
</pre>
<p>And no changes have to be made to our Dashboard object.</p>
<pre class="brush: csharp; ">

public class Dashboard : IVehicleObserver
{
    public string Message { get; private set; }

    public Dashboard()
    {
        Message = string.Empty;
    }

    public void Notify(Vehicle vehicle)
    {
        Message = vehicle.MilesUntilNextOilChange &lt;= 0
                             ? &quot;Time for an oil change!&quot;
                             : string.Format(&quot;Next oil change is due in {0} miles.&quot;, vehicle.MilesUntilNextOilChange);
    }
}
</pre>
<p>Using the classes changes a bit, note how we subscribe to event on the Vehicle object.</p>
<pre class="brush: csharp; ">

var dashboard = new Dashboard();
var vehicle = new Vehicle();

vehicle.MilesChangedEvent += dashboard.Notify;

vehicle.Drive(2000);
Console.WriteLine(dashboard.Message);

vehicle.Drive(1500);
Console.WriteLine(dashboard.Message);

vehicle.PerformOilChange();
Console.WriteLine(dashboard.Message);

vehicle.Drive(1000);
Console.WriteLine(dashboard.Message);
</pre>
<p>Ruby also has some built goodness to make our work a little easier. We are actually given an Observable module that we can add to our Vehicle class that will handle the adding, removing, and notifying of observers. The only minor addition we need to add to our object is the a call to the &#8220;changed&#8221; method when we want to indicate that our object&#8217;s state has changed.</p>
<pre class="brush: ruby; ">

require &quot;observer&quot;

class Vehicle
  include Observable

  attr_reader :mileage, :mileage_at_last_oil_change

  def initialize
    @mileage = 0
    @mileage_at_last_oil_change = 0
    @observers = []
  end

  def drive(miles)
    @mileage += miles
    changed
    notify_observers self
  end

  def miles_until_next_oil_change
    3000 - (@mileage - @mileage_at_last_oil_change)
  end

  def perform_oil_change
    @mileage_at_last_oil_change = @mileage
    changed
    notify_observers self
  end
end
</pre>
<p>To use the module, our observers have to have an &#8220;update&#8221; method so we&#8217;ll need to rename our &#8220;notify&#8221; method on the Dashboard object.</p>
<pre class="brush: ruby; ">

class Dashboard
  attr_reader :message

  def initialize
    @message = &quot;&quot;
  end

  def update(vehicle)
    @message = vehicle.miles_until_next_oil_change &lt;= 0 ?
                &quot;Time for an oil change!&quot; :
                &quot;Next oil change is due in #{vehicle.miles_until_next_oil_change} miles.&quot;
  end
end
</pre>
<p>And our usage stays exactly the same!</p>
<pre class="brush: ruby; ">

require &quot;dashboard&quot;
require &quot;vehicle&quot;

dashboard = Dashboard.new
vehicle = Vehicle.new

vehicle.add_observer dashboard

vehicle.drive 2000
puts dashboard.message

vehicle.drive 1500
puts dashboard.message

vehicle.perform_oil_change
puts dashboard.message

vehicle.drive 1000
puts dashboard.message
</pre>
<p>That&#8217;s it for the Observer pattern, next time we&#8217;ll take a look at the Composite pattern.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.johnlmiller.com%2farchives%2f2009%2f07%2f15%2fcompare-design-patterns-in-ruby-and-c-the-observer-pattern%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.johnlmiller.com%2farchives%2f2009%2f07%2f15%2fcompare-design-patterns-in-ruby-and-c-the-observer-pattern%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=John%20Miller&amp;siteurl=http%3A%2F%2Fwww.johnlmiller.com%2F&amp;linkname=Comparing%20Design%20Patterns%20in%20Ruby%20and%20C%23%3A%20The%20Observer%20Pattern&amp;linkurl=http%3A%2F%2Fwww.johnlmiller.com%2Farchives%2F2009%2F07%2F15%2Fcompare-design-patterns-in-ruby-and-c-the-observer-pattern%2F"><img src="http://www.johnlmiller.com/wp-content/plugins/add-to-any/share_save_171_16.gif" width="171" height="16" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://www.johnlmiller.com/archives/2009/07/15/compare-design-patterns-in-ruby-and-c-the-observer-pattern/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Comparing Design Patterns in Ruby and C#: The Strategy Pattern</title>
		<link>http://www.johnlmiller.com/archives/2009/07/03/comparing-design-patterns-in-ruby-and-c-the-strategy-pattern/</link>
		<comments>http://www.johnlmiller.com/archives/2009/07/03/comparing-design-patterns-in-ruby-and-c-the-strategy-pattern/#comments</comments>
		<pubDate>Fri, 03 Jul 2009 20:50:34 +0000</pubDate>
		<dc:creator>John Miller</dc:creator>
		
		<category><![CDATA[.Net]]></category>

		<category><![CDATA[Ruby]]></category>

		<category><![CDATA[C#]]></category>

		<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://www.johnlmiller.com/?p=152</guid>
		<description><![CDATA[In the previous post of this series, we looked at how the Template pattern is implemented in both Ruby and C#. In this post, we’ll take a look at the Strategy pattern…one of my favorites.
In it’s classic form, the Strategy pattern consists of a context class and various &#8220;strategies&#8221; which share a common interface. The [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://www.johnlmiller.com/archives/2009/04/24/comparing-design-patterns-in-ruby-and-c-the-template-pattern/" target="_blank">previous post</a> of this series, we looked at how the Template pattern is implemented in both Ruby and C#. In this post, we’ll take a look at the Strategy pattern…one of my favorites.</p>
<p>In it’s classic form, the Strategy pattern consists of a context class and various &#8220;strategies&#8221; which share a common interface. The context class is given a strategy to which it can delegate work to. Think of it as passing an algorithm to a class. To change the way the class works, change the algorithm you feed it. This makes it really easy to adhere to the open-closed principle which states that an object should be open for extension but closed for modification. We can drastically change how our class operates without changing a line of code in the class itself.</p>
<p>In .Net, the Sort method on generic lists is a perfect example of how the Strategy pattern can be applied. To change how the list is sorted, you simply pass in a method that matches the Comparison&lt;T&gt; delegate or a class that implements IComparer&lt;T&gt;. (See my <a href="http://www.johnlmiller.com/archives/2009/01/31/sorting-generic-lists-using-icomparert-icomparablet-and-the-comparisont-delegate/" target="_blank">earlier post</a> on the various ways you can sort a generic list in .Net).</p>
<p>Ruby has a really cool example built in as well with it’s rdoc utility which uses strategies both for distilling documentation from various languages (C, Ruby, etc) and in how it ouputs the documentation (HTML, XML, CHM).</p>
<p>In our examples below, we’re creating a Driver object that has three different properties: DrivingHabit, MilesDriven, and SpeedingTickets. It also has a method “Drive” which accepts the number of hours that the driver should drive as a parameter. The Drive method delegates the actual &quot;driving” logic to the driving habit that it is composed with. A cautious driver follows the speed limit (55mph) and never gets a speeding ticket. A reckless driver, however, travels along at 80mph and gets a speeding ticket every 1/2 hour.</p>
<h3>C# Example</h3>
<p>For the Strategy pattern to work in a static language, we must first define a contract that the strategies themselves must adhere to as well as the context class. So we’ll start by creating the Driver object and defining the IDrivingHabit interface.</p>
<pre class="brush: csharp; ">

namespace DesignPatterns.StategyPattern
{
    public class Driver
    {
        public IDrivingHabit DrivingHabit { get; set; }
        public int MilesDriven { get; set; }
        public int SpeedingTickets { get; set; }

        public Driver(IDrivingHabit drivingHabit)
        {
            DrivingHabit = drivingHabit;
        }

        public void Drive(int hours)
        {
            DrivingHabit.Drive(this, hours);
        }
    }
}
</pre>
<pre class="brush: csharp; ">

namespace DesignPatterns.StategyPattern
{
    public interface IDrivingHabit
    {
        void Drive(Driver driver, int duration);
    }
}
</pre>
<p>Now let’s create our strategies.</p>
<pre class="brush: csharp; ">

namespace DesignPatterns.StategyPattern
{
    public class CautiousDrivingHabit : IDrivingHabit
    {
        public void Drive(Driver driver, int hours)
        {
            driver.MilesDriven =  hours * 55;
        }
    }
}
</pre>
<pre class="brush: csharp; ">

namespace DesignPatterns.StategyPattern
{
    public class RecklessDrivingHabit : IDrivingHabit
    {
        public void Drive(Driver driver, int hours)
        {
            driver.MilesDriven += hours * 80;
            driver.SpeedingTickets += hours * 2;
        }
    }
}
</pre>
<p>And to see how this would actually be used, we’ll take a look at the unit tests.</p>
<pre class="brush: csharp; ">

using NUnit.Framework;

namespace DesignPatterns.StategyPattern
{
    [TestFixture]
    public class When_a_cautious_driver_is_on_the_road_for_3_hours
    {
        private Driver granny;

        [SetUp]
        public void EstablishContext()
        {
            granny = new Driver(new CautiousDrivingHabit());
            granny.Drive(3);
        }

        [Test]
        public void Should_move_a_total_of_165_miles()
        {
            Assert.That(granny.MilesDriven, Is.EqualTo(165));
        }

        [Test]
        public void Should_not_receive_any_speeding_tickets()
        {
            Assert.That(granny.SpeedingTickets, Is.EqualTo(0));
        }
    }

    [TestFixture]
    public class When_a_reckless_driver_is_on_the_road_for_3_hours
    {
        private Driver speedRacer;

        [SetUp]
        public void EstablishContext()
        {
            speedRacer = new Driver(new RecklessDrivingHabit());
            speedRacer.Drive(3);
        }

        [Test]
        public void Should_move_a_total_of_240_miles()
        {
            Assert.That(speedRacer.MilesDriven, Is.EqualTo(240));
        }

        [Test]
        public void Should_receive_a_speeding_ticket_for_every_half_hour_on_the_road()
        {
            Assert.That(speedRacer.SpeedingTickets, Is.EqualTo(6));
        }
    }
}
</pre>
<p>Pretty simple, eh? Let’s take a look at how we would do this in Ruby.</p>
<h3>Ruby Example</h3>
<p>First, we’ll create the Driver object. So far doesn’t seem that much different from the C# example. </p>
<pre class="brush: ruby; ">

class Driver
  attr_accessor :driving_habit, :miles_driven, :speeding_tickets

  def initialize(driving_habit)
    @driving_habit = driving_habit
    @miles_driven = 0
    @speeding_tickets = 0
  end

  def drive(hours)
    @driving_habit.drive self, hours
  end
end
</pre>
<p>Next we’re going to jump straight into creating our Strategy classes. Since Ruby supports duck typing, we really have no need to create an object that defines what our strategies should look like. We could define a base DrivingHabit object that included a Drive method that we can override in our implementations, but that would be producing extra code for no added benefit. We’re ok as long as the object we pass in has a Drive method that matches the required signature. </p>
<pre class="brush: ruby; ">

class CautiousDrivingHabit
  def drive(driver, hours)
    driver.miles_driven += hours * 55
  end
end
</pre>
<pre class="brush: ruby; ">

require &#039;lib/driver&#039;

class RecklessDrivingHabit
  def drive(driver, hours)
    driver.miles_driven += hours * 80
    driver.speeding_tickets += hours * 2
  end
end
</pre>
<p>And now we’ll take a look at the corresponding unit tests.</p>
<pre class="brush: ruby; ">

require &#039;lib/cautious_driving_habit&#039;

describe &quot;When a cautious driver is on the road for 3 hours&quot; do
  before(:each) do
    @granny = Driver.new(CautiousDrivingHabit.new)
    @granny.drive 3
  end

  it &quot;should move a total of 165 miles&quot; do
    @granny.miles_driven.should == 165
  end

  it &quot;should not receive any speeding tickets&quot; do
    @granny.speeding_tickets.should == 0
  end
end
</pre>
<pre class="brush: ruby; ">

require &#039;lib/reckless_driving_habit&#039;

describe &quot;When a reckless driver is on the road for 3 hours&quot; do
  before(:each) do
    @speed_racer = Driver.new(RecklessDrivingHabit.new)
    @speed_racer.drive 3
  end

  it &quot;should move a total of 240 miles&quot; do
    @speed_racer.miles_driven.should == 240
  end

  it &quot;should not receive a speeding ticket for every half hour on the road&quot; do
    @speed_racer.speeding_tickets.should == 6
  end
end
</pre>
<h3>Simplifying the Strategy Pattern</h3>
<p>For simple scenarios (such as this one) where the strategies are extremely basic, we can actually reduce the need for the strategy classes themselves. In C#, we just need to add an overloaded Drive method that accepts a delegate that matches the Drive method in the IDrivingHabit interface. (We could have changed the contructor to do this instead.)</p>
<pre class="brush: csharp; ">

public void Drive(int hours, Action&lt;Driver, int&gt; drivingHabit)
{
     drivingHabit(this, hours);
}
</pre>
<p>And to use it, we pass a lambda expression in that contians our logic.</p>
<pre class="brush: csharp; ">

speedRacer.Drive(3, (driver, hours) =&gt;
                     {
                          driver.MilesDriven += hours*80;
                          driver.SpeedingTickets += hours*2;
                     });
</pre>
<p>We can do something very similiar in Ruby. We&#8217;ll create a new method that accepts a code block as a second parameter. Note that we had to create a new name for this method (Ruby doesn&#8217;t support method overloading).</p>
<pre class="brush: ruby; ">

def drive_using_habit(hours, &amp;amp;amp;driving_habit)
 driving_habit.call self, hours
end
</pre>
<p>And the code using this.</p>
<pre class="brush: ruby; ">

@speed_racer.drive_using_habit(3) do |driver, hours|
    driver.miles_driven += hours * 80
    driver.speeding_tickets += hours * 2
end
</pre>
<p>In the next post, we&#8217;ll take a look at a very similiar pattern, the Observer pattern.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.johnlmiller.com%2farchives%2f2009%2f07%2f03%2fcomparing-design-patterns-in-ruby-and-c-the-strategy-pattern%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.johnlmiller.com%2farchives%2f2009%2f07%2f03%2fcomparing-design-patterns-in-ruby-and-c-the-strategy-pattern%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=John%20Miller&amp;siteurl=http%3A%2F%2Fwww.johnlmiller.com%2F&amp;linkname=Comparing%20Design%20Patterns%20in%20Ruby%20and%20C%23%3A%20The%20Strategy%20Pattern&amp;linkurl=http%3A%2F%2Fwww.johnlmiller.com%2Farchives%2F2009%2F07%2F03%2Fcomparing-design-patterns-in-ruby-and-c-the-strategy-pattern%2F"><img src="http://www.johnlmiller.com/wp-content/plugins/add-to-any/share_save_171_16.gif" width="171" height="16" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://www.johnlmiller.com/archives/2009/07/03/comparing-design-patterns-in-ruby-and-c-the-strategy-pattern/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Challenge Yourself This Year: July Goals Progress</title>
		<link>http://www.johnlmiller.com/archives/2009/07/02/challenge-yourself-this-year-july-goals-progress/</link>
		<comments>http://www.johnlmiller.com/archives/2009/07/02/challenge-yourself-this-year-july-goals-progress/#comments</comments>
		<pubDate>Thu, 02 Jul 2009 13:30:49 +0000</pubDate>
		<dc:creator>John Miller</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[inspiration]]></category>

		<category><![CDATA[Personal]]></category>

		<guid isPermaLink="false">http://www.johnlmiller.com/?p=148</guid>
		<description><![CDATA[Earlier in the year I made a list of goals I wanted to accomplish this year and decided to publish my progress periodically here…to produce some sort of accountability. And as usual, seeing Darrell’s update made me realize that it’s been way to long since my last update!
Technical Goals
Read the following books:

Patterns of Enterprise Application [...]]]></description>
			<content:encoded><![CDATA[<p>Earlier in the year I made a list of goals I wanted to accomplish this year and decided to publish my progress periodically here…to produce some sort of accountability. And as usual, seeing <a href="http://darrell.mozingo.net/2009/07/01/2009-goals-july-update/" target="_blank">Darrell’s update</a> made me realize that it’s been way to long since my last update!</p>
<h3>Technical Goals</h3>
<p><strong>Read the following books:</strong></p>
<ul>
<li><a href="http://www.amazon.com/Enterprise-Application-Architecture-Addison-Wesley-Signature/dp/0321127420/ref=pd_bbs_sr_1?ie=UTF8&amp;s=books&amp;qid=1229896370&amp;sr=8-1" target="_blank"><span style="text-decoration: line-through;">Patterns of Enterprise Application Architecture</span></a><span style="text-decoration: line-through;"> – Fowler</span> <em>– Finished!</em></li>
<li><a href="http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1229896453&amp;sr=1-1" target="_blank">Domain Driven Design</a> – Evans</li>
<li><a href="http://www.amazon.com/Applying-Domain-Driven-Design-Patterns-Examples/dp/0321268202/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1229896587&amp;sr=1-1" target="_blank">Applying Domain-Driven Design and Patterns</a> – Nilsson</li>
<li><a href="http://www.amazon.com/Working-Effectively-Legacy-Robert-Martin/dp/0131177052/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1229896657&amp;sr=1-1" target="_blank">Working Effectively with Legacy Code</a> – Feathers</li>
<li><a href="http://www.amazon.com/Refactoring-Improving-Existing-Addison-Wesley-Technology/dp/0201485672" target="_blank">Refactoring</a> – Fowler</li>
<li><a href="http://www.amazon.com/Principles-Patterns-Practices-Robert-Martin/dp/0131857258/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1229896765&amp;sr=1-1" target="_blank">Agile Principles, Patterns, and Practices in C#</a> - Martin</li>
</ul>
<p><strong>Become proficient with the following tools &amp; technologies:</strong></p>
<ul>
<li><a href="http://www.asp.net/mvc/" target="_blank">ASP.Net MVC</a> – <em>No progress, hopefully in the next few months…</em></li>
<li><a href="http://www.hibernate.org/343.html" target="_blank"><span style="text-decoration: line-through;">NHibernate</span></a> – <em>Finished! Used NHibernate in my first project a couple of months ago and was blown away by it’s awesomeness!</em></li>
<li><a href="http://www.castleproject.org/" target="_blank"><span style="text-decoration: line-through;">The Castle Stack</span></a> – <em>Finished! Used Windsor on a recent project and explored ActiveRecord. Believe this is as far as I want to go with Castle this year.</em></li>
<li><a href="http://www.jetbrains.com/teamcity/" target="_blank"><span style="text-decoration: line-through;">Team City</span></a> – <em>Finished! Set up Team City for several projects in the last few months.</em></li>
<li><a href="http://www.ruby-lang.org/en/" target="_blank"><span style="text-decoration: line-through;">Ruby</span></a><span style="text-decoration: line-through;"> (the basics at a minimum)</span> – <em>Finished (but still learning)! My goal was to just learn the basics, actually taking that a step further and am working on an actual Rails project with a </em><a href="http://joshreedschramm.com/" target="_blank"><em>Josh</em></a><em>.</em></li>
<li><a href="http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx" target="_blank">Powershell</a> – <em>No progress here.</em></li>
</ul>
<p><strong>Get involved:</strong></p>
<ul>
<li>Two blog posts per month – <em>I more or less went silent in the last two months and hope to kick myself back into gear over the weekend. Started a series of posts comparing design pattern implementations in Ruby and C#, but only finished the first one (</em><a href="http://www.johnlmiller.com/archives/2009/04/24/comparing-design-patterns-in-ruby-and-c-the-template-pattern/" target="_blank"><em>Template pattern</em></a><em>). Will be continuing this series very soon. I promise.</em></li>
<li>Two technical presentations for coworkers to push agile methodologies at my current company. – <em>Our company has gone through some changes and I don’t see after hours presentations like this happening in the near future, so I’m gonna scratch this one for now.</em></li>
</ul>
<p><strong>Certifications:</strong></p>
<ul>
<li>Upgrade MCPD certification from 2.0 to 3.5 – <em>No progress here.</em></li>
</ul>
<h3>Personal Goals</h3>
<p><strong>Family Time</strong></p>
<ul>
<li>Take 2 one week long trips – <em>We took a trip to Disney World last month (which was a blast!) and are hoping to take another long vacation in the next few months.</em></li>
<li>Take 6 weekend getaways – <em>Way behind on this one, believe we’ve taken one so far this year.</em></li>
<li>By the end of the year, work from home regularly two times per week – <em>This is a tough one with my current job, the ability to do this is completely dependant on the project\client and hasn’t been an option lately.</em></li>
</ul>
<p><strong>Belief System</strong></p>
<ul>
<li>Read the Bible completely through – <em>I just finished II Kings so my guess is that put’s me at around 30% complete…and 50% of the year is gone already.</em></li>
</ul>
<p><strong>Financial</strong></p>
<ul>
<li>Reduce debt by two-thirds – <em>Surprisingly still on track here, it’s forced us to live paycheck to paycheck but it feels good to see substantial progress being made!</em></li>
<li>Become familiar with some of the ins and outs of day trading, as well as how currency trading works – <em>No longer as interested in stocks at the moment, mostly because almost all of our spare money is going to debt reduction. May pick interest up again next year.</em></li>
</ul>
<p><strong>Side Projects</strong></p>
<ul>
<li>Finish the project I’ve been working on for the last year! – <em>Almost done, hope to launch this month!!</em></li>
<li>Start a new venture and grow it to produce $500 per month of automated income by the end of the year. – <em>Still working on a project with <a href="http://joshreedschramm.com/" target="_blank">Josh</a>, may not turn a profit this year but we’ll see.</em></li>
</ul>
<p>Looks like I’m really falling behind in my reading (although I’ve been reading things here and there, they just haven’t been books on my list). Planning to change that in the second half of the year.</p>
<div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"><a href="http://www.dotnetkicks.com/kick/?url=http://www.johnlmiller.com/?p=148"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://www.johnlmiller.com/?p=148&amp;bgcolor=0080C0&amp;fgcolor=FFFFFF&amp;border=000000&amp;cbgcolor=D4E1ED&amp;cfgcolor=000000" border="0" alt="DotNetKicks Image" /></a></div>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=John%20Miller&amp;siteurl=http%3A%2F%2Fwww.johnlmiller.com%2F&amp;linkname=Challenge%20Yourself%20This%20Year%3A%20July%20Goals%20Progress&amp;linkurl=http%3A%2F%2Fwww.johnlmiller.com%2Farchives%2F2009%2F07%2F02%2Fchallenge-yourself-this-year-july-goals-progress%2F"><img src="http://www.johnlmiller.com/wp-content/plugins/add-to-any/share_save_171_16.gif" width="171" height="16" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://www.johnlmiller.com/archives/2009/07/02/challenge-yourself-this-year-july-goals-progress/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
