<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"><channel><atom:link rel="hub" href="http://tumblr.superfeedr.com/" xmlns:atom="http://www.w3.org/2005/Atom"/><description>
public namespace Wes
{
	public class Me
	{
		public string FirstName = "Wesley";
		public string LastName = "McClure";
		public string Handle = "g0t4";
	}
}
</description><title>Pleasant, unpleasant thoughts!</title><generator>Tumblr (3.0; @wesmcclure)</generator><link>http://wesmcclure.tumblr.com/</link><item><title>My cool code snippet</title><description>&lt;p&gt;I submitted this to the Resharper cool code snippet competition and thought I would share it with everyone else, including why it&amp;#8217;s cool!&lt;/p&gt;

&lt;p&gt;[Test]&lt;br/&gt;
public void $METHOD$_$SCENARIO$_$EXPECTATION$()&lt;br/&gt;
{&lt;br/&gt;
            $END$&lt;br/&gt;
}&lt;/p&gt;

&lt;p&gt;I’ve been doing a lot of TDD lately and I am constantly writing new tests. So my number one snippet is one that creates a simple test.  I’ve tweaked this template a lot, it started out with a simple test template with only one editable occurance for a name.  In “The Art of Unit Testing,” Roy Osherove talks about test readability which starts with the test name itself.  He suggests putting the test method name together with three components.  First, name the method under test (the Act in AAA), that way related tests for the same method are easy to identify (and actually R# sorts test fixture test methods by name so this is even more useful with Code Cleanup :) ).  Second, name it with a scenario, what is unique about the given context of the test (known as the Arrange in AAA).  Finally, include the outcome of the test, the expectation (Assert in AAA).  This way you know all of what will go into the test before you write it!&lt;/p&gt;

&lt;p&gt;I gave his naming scheme a try and found out it offers a pit of success.  If you cannot name these three parts then your test likely won’t be readable.  Anyone should know what a test does without reading it, like with any method, it should be intention revealing!  Without identifying a scenario explicitly, it may be blurred in several lines of setup (Arrange).  Having the scenario in the name makes it explicit and makes me keep it simple (I hate long method names).  The test may have too many expectations, again, I hate long method names so if I find myself putting multiple expectations in the name I will quickly realize I need to move the other expectations to new tests (SRP with testing)!&lt;/p&gt;

&lt;p&gt;The same day I tried using this test method naming convention, was the same day I created this test snippet and have kept it ever since.  Every time I write a test, I am very explicit and careful, which is very important with TDD, not to take on too much with any one test!&lt;/p&gt;

&lt;p&gt;This snippet is awesome, not because of the code it creates, but because it sets myself up for success every time I use it, like having Uncle Bob Martin watching over my shoulder :)&lt;/p&gt;</description><link>http://wesmcclure.tumblr.com/post/168675193</link><guid>http://wesmcclure.tumblr.com/post/168675193</guid><pubDate>Sat, 22 Aug 2009 00:06:18 -0400</pubDate></item><item><title>Outlook 2010 + Google Cal Sync hack</title><description>&lt;p&gt;So yeah Google Cal Sync doesn&amp;#8217;t work with Outlook 2010 Preview, but I found a way to get it to jive.
&lt;br/&gt;&lt;br/&gt;
I edited Outlook.exe in C:\Program Files\Microsoft Office\Office14 using Notepad++ with the Hex-Editor plugin. At assembly location 0x000c09b2, I changed the value to 0x32, in the ascii dump.  It originally read (14.0.0 and now reads (12.0.0
&lt;br/&gt;&lt;br/&gt;
Good luck, I have no idea what this might break, I hope it is just the outlook version that the add in manager reports to add ins :).  I have successfully synced events to and from my GCal!
&lt;br/&gt;&lt;br/&gt;
-Wes&lt;/p&gt;</description><link>http://wesmcclure.tumblr.com/post/156968222</link><guid>http://wesmcclure.tumblr.com/post/156968222</guid><pubDate>Thu, 06 Aug 2009 01:58:00 -0400</pubDate></item><item><title>"If you are doing custom Linq to Sql mappings, it currently doesn’t support having your own..."</title><description>“If you are doing custom Linq to Sql mappings, it currently doesn’t support having your own base Entity class that you extend all your entities from.  I found out the hard way through painful debugging.  However, it seems if you do this with the version of .net 3.5 sp1 on the Win 7 RC it will work, so this may not be a bug forever!”</description><link>http://wesmcclure.tumblr.com/post/155905924</link><guid>http://wesmcclure.tumblr.com/post/155905924</guid><pubDate>Tue, 04 Aug 2009 17:58:01 -0400</pubDate></item><item><title>NUnit 2.5.1 framework with Silverlight 3</title><description>&lt;p&gt;We&amp;#8217;re doing some Silverlight development at work and I&amp;#8217;m doing some off to the side. I like to stick with a familiar, proven unit test framework.  NUnit 2.5.1. has some great new attributes to use during testing (actually these came out in 2.5) such as Timeout and MaxTime.  To take advantage of them you have to have a version of NUnit compiled as a silverlight library or at least recompiled referencing the core of silverlight (system.dll and mscorlib versions 2.0.5.0).  
&lt;br/&gt;&lt;br/&gt;
In the spirit of continuing what a few other people have done, I have compiled the latest version of the NUnit framework into a SL library and want to make it available.  The work of the following guys has helped me use NUnit up to version 2.4 and helped me get 2.5.1 going as well!
&lt;br/&gt;&lt;br/&gt;
A nice template that included the SL framework version, if someone wants this updated please let me know and I can do that too, otherwise I&amp;#8217;ll just post my dlls:
&lt;a href="http://weblogs.asp.net/nunitaddin/archive/2008/05/01/silverlight-nunit-projects.aspx"&gt;&lt;a href="http://weblogs.asp.net/nunitaddin/archive/2008/05/01/silverlight-nunit-projects.aspx"&gt;http://weblogs.asp.net/nunitaddin/archive/2008/05/01/silverlight-nunit-projects.aspx&lt;/a&gt;&lt;/a&gt;
&lt;br/&gt;&lt;br/&gt;
A set of instructions to port the framework to SL (I diverged on some of these, see below):
&lt;a href="http://www.jeff.wilcox.name/2009/01/nunit-and-silverlight/"&gt;&lt;a href="http://www.jeff.wilcox.name/2009/01/nunit-and-silverlight/"&gt;http://www.jeff.wilcox.name/2009/01/nunit-and-silverlight/&lt;/a&gt;&lt;/a&gt;
&lt;br/&gt;&lt;br/&gt;
Here is the list of changes and what didn&amp;#8217;t make the cut:
&lt;/p&gt;&lt;ul&gt;&lt;li&gt;BinarySerializableConstraint - SL core doesn&amp;#8217;t have BinarySerializer&lt;/li&gt;
&lt;li&gt;AssertionException, IgnoreException, InconclusiveException, SuccessException - cannot be serialized, SL core doesn&amp;#8217;t have SerializationAttribute (goes along with BinarySerializer)&lt;/li&gt;
&lt;li&gt;RequiresSTA and RequiresMTA attributes&lt;/li&gt;
&lt;/ul&gt;&lt;br/&gt;
How was this pulled off?
&lt;ul&gt;&lt;li&gt;For both the nunit.framework and nunit.framework.tests I added new silverlight libraries and copied the links to the code that the respective projects already referenced. I also added a nunit.silverlight to drop in some of the following additional classes that are needed but not in the SL core.&lt;/li&gt;
&lt;li&gt;I want to thank Jeff Wilcox for his original work on some shims
&lt;ul&gt;&lt;li&gt;ArrayList which I added a ToArray method that takes a type, of course this was ripped off of the ArrayList (via reflector) in the .Net core so someone should let me know if MSFT is going to come take away my computer for publishing this&lt;/li&gt;
&lt;li&gt;Hashtable&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;I added a ListDictionary which is just a version of the generic Dictionary class with key and value set to type object&lt;/li&gt;
&lt;li&gt;String.Compare(string,string,bool) - a version of string comparison not included in the silverlight core, again thank you reflector&lt;/li&gt;
&lt;li&gt;I made up an ApplicationException as this wasn&amp;#8217;t in the SL core&lt;/li&gt;
&lt;li&gt;I made a version of the non generic Comparer class that isn&amp;#8217;t in the SL core, thanks reflector&lt;/li&gt;
&lt;li&gt;I added the compiler directive NET_2_0&lt;/li&gt;
&lt;li&gt;A lot of the functionality that was removed was done so by leveraging the SILVERLIGHT compiler directive to exclude the relevant code.&lt;/li&gt;
&lt;/ul&gt;&lt;br/&gt;
I also went into the framework tests and tweaked a new solution to work with silverlight.  I had to modify the tests as follows:
&lt;ul&gt;&lt;li&gt;CanTestContentsOfSortedList excluded - no SortedList in SL&lt;/li&gt;
&lt;li&gt;Remove references and tests with System.Data types (NotGreaterEqualIComparable, NotGreaterIComparable, NotLessEqualIComparable, NotLessIComparable) &lt;/li&gt;
&lt;li&gt;Remove SameColorAs constraint, which was only referenced by NamedAndUnnamedColorsCompareAsEqual, which was commented out anyways&lt;/li&gt;
&lt;li&gt;Remove BinarySerializableTest and XmlSerializableTest tests that depend on Serializable attribute&lt;/li&gt;
&lt;li&gt;Changed DifferentEncodingsOfSameStringAreNotEqual test to use System.Text.Encoding.UTF8.GetString(byte[],start,length) overload as (byte[]) overload isn&amp;#8217;t available in SL&lt;/li&gt;
&lt;li&gt;Removed CodeShouldNotCompile and CodeShouldNotCompileAsFinishedConstraint as Microsoft.CSharp.CSharpCodeProvider is not available in SL&lt;/li&gt;
&lt;/ul&gt;&lt;br/&gt;
So, altogether the changes were minimal and there are 1273 tests passing on the SL version of the framework!
&lt;br/&gt;&lt;br/&gt;
To use these assemblies:
&lt;ol&gt;&lt;li&gt;Setup a SL library as your test library.&lt;/li&gt;
&lt;li&gt;Download the SL libraries &lt;a href="http://nunitsilverlight.googlecode.com/files/NUnit_2_5_1_Silverlight.zip"&gt;here&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Include a reference to the nunit.framework.dll.&lt;/li&gt;
&lt;li&gt;If you have trouble getting tests to run (missing file exceptions to SL assemblies) then set &amp;#8220;Copy Local: true&amp;#8221; on the appropriate assembly reference in the properties.  I always have to do this for the system SL assembly.&lt;/li&gt;
&lt;/ol&gt;&lt;br/&gt;
If anyone wants more source for what I did or more bits of the nunit framework (like mocks or w/e) ported, please let me know and I will get that done, if possible :)  For now I&amp;#8217;m happy with just the framework as I use Rhino.Mocks (which already has a SL port) as an isolation container.
&lt;br/&gt;&lt;br/&gt;
-Wes</description><link>http://wesmcclure.tumblr.com/post/152727000</link><guid>http://wesmcclure.tumblr.com/post/152727000</guid><pubDate>Fri, 31 Jul 2009 00:48:00 -0400</pubDate><category>NUnit</category><category>Silverlight</category></item><item><title>"Not using a ubiquitous language when developing an application is incurring yet another form of..."</title><description>“Not using a ubiquitous language when developing an application is incurring yet another form of design debt, the overhead involved in manual testing is similar to the overhead incurred in translating between separate languages when conversations between users/domain experts and developers occur.  Like with foreign languages, idiomatic assumptions and other misunderstandings are likely to fall short of a true conversation, so just pony up and focus on using a COMMON LANGUAGE as Eric Evans refers to in DDD.”&lt;br/&gt;&lt;br/&gt; - &lt;em&gt;Me&lt;/em&gt;</description><link>http://wesmcclure.tumblr.com/post/149641542</link><guid>http://wesmcclure.tumblr.com/post/149641542</guid><pubDate>Sun, 26 Jul 2009 16:19:47 -0400</pubDate></item><item><title>Null Object Pattern</title><description>&lt;p&gt;Code reuse is very important for developers, most of the patterns and refactorings exist soley to reduce the smell of duplicated code.  Null checks are one of the biggest culprits of duplicated code.  It is also, to a degree, a concern that often gets scattered through out an application and isn&amp;#8217;t properly separated.  Without testing and/or good documentation, it&amp;#8217;s often hard to determine the expectations of a method that returns a reference type or a nullable value type.  Often, unnecessary, paranoid, null checks are incorporated to deal with the problem.

The null object pattern almost solely exists as a pattern to reduce code, so if it cannot reduce the amount of code you are writing, don&amp;#8217;t use it! 

The idea is that instead of setting a refernece type to null initially, you set it to an implementation of the type that executes &amp;#8220;null behavior&amp;#8221; if methods are called on it&amp;#8217;s contract that would normally throw a null reference exception. 
&lt;br/&gt;&lt;br/&gt;
Pros
&lt;ul&gt;&lt;li&gt;Redcue code&lt;/li&gt;
&lt;li&gt;Separated concerns when handling null logic&lt;/li&gt;&lt;li&gt;
&lt;/li&gt;&lt;/ul&gt;
Cons
&lt;ul&gt;&lt;li&gt;Not familiar to newer developers&lt;/li&gt;
&lt;li&gt;Can complicate code, make sure it is actually reducing the amount of code before implementing!  This is not a pattern to start with in a standard toolset!&lt;/li&gt;
&lt;/ul&gt;

Say we have a contract for a type:

&lt;pre class="brush: c#"&gt;
	public interface IThing
	{
		void Do();
		bool Execute();
	}
&lt;/pre&gt;

and your system made a large number of calls to this Do method but had to check if the Thing was null before calling Do/Execute, you could replace the initial value of a reference to it with a Null implementation instead, then if someone calls a method on a null instance it won&amp;#8217;t have any side effects (including null reference exceptions) if it wasn&amp;#8217;t initialized already. 

&lt;pre class="brush: c#"&gt;
	public class NullThing : IThing
	{
		public void Do()
		{
			
		}

		public bool Execute()
		{
			return true;
		}
	}
&lt;/pre&gt;

Then, anywhere that used this type could initilize to the NullThing:

&lt;pre class="brush: c#"&gt;
	public class ThingHaver
	{
		private IThing _Thing = new NullThing();
		public IThing Thing
		{
			get
			{
				return _Thing;

			}
			set
			{
				_Thing = value;
			}
		}
	}
&lt;/pre&gt;

What would be really cool is if we could somehow overload the default operator in c# and set what it returns.  Then, if we used an abstract base class of IThing (ThingBase), we could implement this to return our NullThing(), assuming that behind the scenes the compiler relied on wiring up calls to default whenever it ran across:
&lt;pre class="brush: c#"&gt;
private ThingBase _Thing; 
&lt;/pre&gt;
Then we wouldn&amp;#8217;t even have to set our variable to NullThing!  Though maybe I&amp;#8217;m getting too far off on a tangent here :)  My one concern with this pattern is that it is very easy to produce a disparity in a team if they all aren&amp;#8217;t aware of the pattern or it&amp;#8217;s implementation in a particular scenario.

-Wes&lt;/p&gt;</description><link>http://wesmcclure.tumblr.com/post/146358582</link><guid>http://wesmcclure.tumblr.com/post/146358582</guid><pubDate>Tue, 21 Jul 2009 18:40:00 -0400</pubDate></item><item><title>"Program to an interface, not to an implementation"</title><description>““Program to an interface, not to an implementation””&lt;br/&gt;&lt;br/&gt; - &lt;em&gt;Not sure if this has a source, but it’s a great concept.&lt;/em&gt;</description><link>http://wesmcclure.tumblr.com/post/127207489</link><guid>http://wesmcclure.tumblr.com/post/127207489</guid><pubDate>Sat, 20 Jun 2009 18:41:57 -0400</pubDate></item><item><title>Refactoring - Compose Method</title><description>&lt;p&gt;This refactoring, again from &lt;a href="http://www.pearsonhighered.com/educator/academic/product/0,3110,0321213351,00.html"&gt;Refactoring to Patterns&lt;/a&gt;, reduces ambiguity in methods that have too much detail or conditional logic to quickly comprehend. By breaking a method down into smaller methods, the ambiguity can be removed.
&lt;br/&gt;&lt;br/&gt;
The mechanics of this refactoring are rather subjective, but obviously lead to the use of Extract Method. Study the code and make sure you understand it, the longer this takes, the more you need to apply this refactoring! Clean up the code, look for unused or duplicated pieces. Then, extract detail to smaller methods. Reveal intention through naming of new variables and methods. Once you are done, make sure all the code in the Composed Method is of the same level of detail.
&lt;br/&gt;&lt;br/&gt;
Pros
&lt;ol&gt;&lt;li&gt;Readability&lt;/li&gt;
&lt;li&gt;Uniform level of detail.&lt;/li&gt;
&lt;li&gt;Joshua lists difficulty in debugging as a drawback, however, I think a stack trace that points to the smaller, intentionally named method will increase the likelihood that I can figure out what is wrong before I even crack open the code!&lt;/li&gt;
&lt;li&gt;Another benefit to add to Joshua’s list: code re-use of the extracted methods to replace other duplicated code.&lt;/li&gt;
&lt;/ol&gt;
Cons
&lt;ol&gt;&lt;li&gt;Excessive quantity of small methods, though Joshua points out this could lead to applying Extract Class.&lt;/li&gt;
&lt;/ol&gt;

So I rummaged around in some code and stumbled upon a text box validation method that was a great candidate for this refactoring:
&lt;pre class="brush: c#"&gt;
public virtual void Validate()
{
	IsValid = true;
	if (Visible &amp;amp;&amp;amp; Enabled)
	{
		if (IsRequired)
		{
			if (String.IsNullOrEmpty(Text) || Text.Trim().Length == 0)
			{
				ErrorMessage = String.Format(Messages.TextBoxCannotBeEmpty, InvalidDisplayName);
				IsValid = false;
			}
		}

		if (MaxLength != 0 &amp;amp;&amp;amp; !String.IsNullOrEmpty(Text) &amp;amp;&amp;amp; Text.Trim().Length &amp;gt; MaxLength)
		{
			ErrorMessage = String.Format(Messages.TextBoxExceedsMaximumLength, InvalidDisplayName, MaxLength);
			IsValid = false;
		}

		if (MinLength &amp;gt; 0 &amp;amp;&amp;amp; (String.IsNullOrEmpty(Text) || Text.Trim().Length &amp;lt; MinLength))
		{
			ErrorMessage = String.Format(Messages.TextBoxUnderMinimumLength, InvalidDisplayName, MinLength);
			IsValid = false;
		}
	}
}
&lt;/pre&gt;
The level of nested conditionals makes it rather hard to follow. First, I want to remove some of the nesting by returning immediately if the validation isn’t applicable:
&lt;pre class="brush: c#"&gt;
public virtual void Validate()
{
	IsValid = true;
	if (!Visible || !Enabled)
	{
		return;
	}
	if (IsRequired)
	{
		if (String.IsNullOrEmpty(Text) || Text.Trim().Length == 0)
		{
			ErrorMessage = String.Format(Messages.TextBoxCannotBeEmpty, InvalidDisplayName);
			IsValid = false;
		}
	}

	if (MaxLength != 0 &amp;amp;&amp;amp; !String.IsNullOrEmpty(Text) &amp;amp;&amp;amp; Text.Trim().Length &amp;gt; MaxLength)
	{
		ErrorMessage = String.Format(Messages.TextBoxExceedsMaximumLength, InvalidDisplayName, MaxLength);
		IsValid = false;
	}

	if (MinLength &amp;gt; 0 &amp;amp;&amp;amp; (String.IsNullOrEmpty(Text) || Text.Trim().Length &amp;lt; MinLength))
	{
		ErrorMessage = String.Format(Messages.TextBoxUnderMinimumLength, InvalidDisplayName, MinLength);
		IsValid = false;
	}
}
&lt;/pre&gt;
Next, I notice 3 different “sub validations” occurring. One validates if the field is required, the next validates the maximum length and the last validates the minimum length. Each of these can become their own methods:
&lt;pre class="brush: c#"&gt;
public virtual void Validate()
{
	IsValid = true;
	if (!Visible || !Enabled)
	{
		return;
	}

	ValidateRequired();
	ValidateMaximumLength();
	ValidateMinimumLength();
}
private void ValidateRequired()
{
	if (IsRequired)
	{
		if (String.IsNullOrEmpty(Text) || Text.Trim().Length == 0)
		{
			ErrorMessage = String.Format(Messages.TextBoxCannotBeEmpty, InvalidDisplayName);
			IsValid = false;
		}
	}
}
private void ValidateMaximumLength()
{
	if (MaxLength != 0 &amp;amp;&amp;amp; !String.IsNullOrEmpty(Text) &amp;amp;&amp;amp; Text.Trim().Length &amp;gt; MaxLength)
	{
		ErrorMessage = String.Format(Messages.TextBoxExceedsMaximumLength, InvalidDisplayName, MaxLength);
		IsValid = false;
	}
}
private void ValidateMinimumLength()
{
	if (MinLength &amp;gt; 0 &amp;amp;&amp;amp; (String.IsNullOrEmpty(Text) || Text.Trim().Length &amp;lt; MinLength))
	{
		ErrorMessage = String.Format(Messages.TextBoxUnderMinimumLength, InvalidDisplayName, MinLength);
		IsValid = false;
	}
}
&lt;/pre&gt;
Finally, I realize the level of detail isn’t uniform, I should extract a new property to check if the control is in use. Also, even more troublesome, the intentions of the first line to set the IsValid to true are lost to future developers. This is needed to reset the validation process, otherwise if a control is validated and fails, subsequent calls may still return invalid. My new Composed Method finally becomes:
&lt;pre class="brush: c#"&gt;
public virtual void Validate()
{
	ResetValidation();
	if (!InUse)
	{
		return;
	}
	
	ValidateRequired();
	ValidateMaximumLength();
	ValidateMinimumLength();
}
private void ResetValidation()
{
	IsValid = true;
}
private bool InUse
{
	get
	{
		return Visible &amp;amp;&amp;amp; Enabled;
	}
}
...
&lt;/pre&gt;
The new Composed Method is much easier to comprehend. Ironically enough, looking at other validation methods, the newly extract methods can be re-used either through inheritance or possibly by applying Extract Class. The new InUse property may eventually be exposed for public consumption.&lt;/p&gt;</description><link>http://wesmcclure.tumblr.com/post/125626550</link><guid>http://wesmcclure.tumblr.com/post/125626550</guid><pubDate>Thu, 18 Jun 2009 00:22:00 -0400</pubDate><category>Patterns</category><category>Refactoring</category></item><item><title>Chain Constructors</title><description>&lt;p&gt;Chain Constructors is another refactoring from the book &lt;a href="http://www.pearsonhighered.com/educator/academic/product/0,3110,0321213351,00.html"&gt;Refactoring to Patterns&lt;/a&gt;, it helps remove duplication in constructor overloads.  This should be a very familiar refactoring for most developers.  Catch all constructors are produced, and hopefully minimized, that other constructors rely on either directly or indirectly.

Mechanics
&lt;ol&gt;&lt;li&gt;
Study the constructors in the class and find the two with the most shared code.  Say I have two constructors to create lines as follows:
&lt;pre class="brush: c#"&gt;
public class Line
{
	...
	private Line()
	{
		Style = LineStyle.Solid;
		Color = LineColor.Black;
		Thickness = 1;
	}

	private Line(LineStyle style, LineColor color, int thickness)
	{
		Style = style;
		Color = color;
		Thickness = thickness;
	}
	...
}
&lt;/pre&gt;

These can be chained together, to reduce redundant code and leave a common spot for future property initializations.
&lt;pre class="brush: c#"&gt;
public class Line
{
	...
	private Line()
		: this(LineStyle.Solid, LineColor.Black, 1)
	{
	}

	private Line(LineStyle style, LineColor color, int thickness)
	{
		Style = style;
		Color = color;
		Thickness = thickness;
	}
	...
}
&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;
Repeat step one, even with constructors already chained, to maximize chaining and code re-use.
&lt;/li&gt;
&lt;li&gt;
Re-scope any constructors that no longer need to be public.
&lt;/li&gt;
&lt;/ol&gt;

Pros
&lt;ol&gt;&lt;li&gt;Code reuse&lt;/li&gt;
&lt;li&gt;Avoid future mistakes when new code in one constructor isn&amp;#8217;t copied to others.&lt;/li&gt;
&lt;/ol&gt;
Cons
&lt;ol&gt;&lt;li&gt;Highly nested constructors might become confusing, try to keep it simple, if you find many levels of chaining, you may want to consider applying refactorings to or twoards Creation Method and/or Factory patterns to help reduce ambiguity&lt;/li&gt;
&lt;/ol&gt;&lt;/p&gt;</description><link>http://wesmcclure.tumblr.com/post/125582636</link><guid>http://wesmcclure.tumblr.com/post/125582636</guid><pubDate>Wed, 17 Jun 2009 22:52:00 -0400</pubDate><category>Patterns</category><category>Refactoring</category></item><item><title>Refactoring, Creation Methods</title><description>&lt;p&gt;Lately, I&amp;#8217;ve been engulfed in several design books, one of which is &lt;a href="http://www.pearsonhighered.com/educator/academic/product/0,3110,0321213351,00.html"&gt;Refactoring to Patterns&lt;/a&gt; by Joshua Kerievsky.  The book is an extension of Martin Fowler&amp;#8217;s book, &lt;a href="http://www.martinfowler.com/books.html#refactoring"&gt;Refactoring&lt;/a&gt;.  It emphasizes learning to use patterns by working with existing code, identifying code that &amp;#8220;smells&amp;#8221; and then finding a pattern to refactor the code &amp;#8220;to, towards or away from.&amp;#8221;  Smelly code typically involves duplication, complexity and/or ambiguity.  
&lt;br/&gt;&lt;br/&gt;
Joshua believes, rather than heavy pattern use up front, to let code evolve into or away from patterns.  I thought it might be fun to share some of these refactorings and examples from my code past (gasp).
&lt;br/&gt;&lt;br/&gt;
One of the first refactorings, Replace Constructors with Creation Methods.  Simply put, when we have lots of overloads or parameters for our constructor(s), ambiguity arises as to the intended use.  Often we add conditional plumbing to construct different instances of the same class with different run time behavior.  The problem is that the constructors are called the same way and we have no way of providing intention through naming conventions like we can with methods and other members.
&lt;br/&gt;&lt;br/&gt;
I went back to some old code and found an example of where this refactoring could help.  The code was doing various types of charting by abstracting the creation of lines to separate instances before rendering the chart.  One of the classes, scrubbed, had constructors as follows:

&lt;pre class="brush: c#"&gt;
public class Line
{
	...
	public Line(int year, int month, int productId)
	{
		Initialize(year, month, productId);
		LoadData();
	}

	public Line(int month, int productId)
	{
		Initialize(2000, month, productId);
	}
	...
}
&lt;/pre&gt;
 
The first overload has an extra parameter to provide the year, that is all a user of this class would see when they come across instantiations of this class.  With out digging deeper they wouldn&amp;#8217;t realize that one overload queries and loads actual data points for the specified product while the other was intended to provide a way to manipulate and map existing lines to new lines.
&lt;br/&gt;&lt;br/&gt;
The refactoring seeks to use methods to create instances of the class and subsequently, if appropriate, hiding the original constructors so users are forced to use the new, hopefully less ambiguous, Creation Methods.
&lt;br/&gt;&lt;br/&gt;
Every refactoring has a set of steps, which should be performed one at at time until the desired changes are complete.  Joshua emphasizes that not all steps must be completed.  Sometimes only part of a refactoring is sufficient to clean up smelly code.
&lt;br/&gt;&lt;br/&gt;
The &amp;#8220;Mechanics,&amp;#8221; as Joshua refers to in his book, are as follows:
&lt;br/&gt;&lt;ol&gt;&lt;li&gt;Find a spot where the class is instantiated and apply the refactoring Extract Method.
&lt;pre class="brush: c#"&gt;
Line line = new Line(2009, 2, productId);
&lt;/pre&gt;
&lt;br/&gt;
Refactors to (note the extracted method should be static):
&lt;pre class="brush: c#"&gt;
Line line = CreateLine(2009, 2, productId);
...
public static Line CreateLine(int month, int year, int productId)
{
	return new Line(month, year, productId);
}
&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;Next, apply Move Method and move the new method to the class it instantiates.
&lt;pre class="brush: c#"&gt;
Line line = Line.CreateLine(2009, 2, productId);
...
public class Line
{
	...
	public static Line CreateLine(int month, int year, int productId)
	{
		return new Line(month, year, productId);
	}
	...
}
&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;Find all code that uses this specific constructor, for this specific intended use, and refactor it to use the new Creation Method.  Be careful to check for constructors that are used for several different intended purposes, these should be broken out into their own separate Creation Methods.  Red flags for this include conditional logic in the constructor and/or allowing null/default values for a parameter that drive different class behaviors.
&lt;/li&gt;
&lt;li&gt;
Joshua mentions to repeat steps 1 to 3 for all other constructor overloads.  I&amp;#8217;d rather switch his last two steps.  So, in this step, make any constructors that are no longer publicly used, private or internal to avoid users trying to call the constructors.  Remeber, each step is optional, and in some cases you may not want to re-scope the constructor.
&lt;pre class="brush: c#"&gt;
public class Line
{
	...
	private Line(int year, int month, int productId)
	{
		Initialize(year, month, productId);
		LoadData();
	}
	...
}
&lt;/pre&gt;
&lt;/li&gt;&lt;li&gt;
Repeat for all applicable constructors.  To save time, I will show the final form of my Line class:
&lt;pre class="brush: c#"&gt;
public class Line
{
	...
	private Line(int year, int month, int productId)
	{
		Initialize(year, month, productId);
		LoadData();
	}

	private Line(int month, int productId)
	{
		Initialize(2000, month, productId);
	}

	public static Line CreateLine(int month, int year, int productId)
	{
		return new Line(month, year, productId);
	}

	public static Line CreateMappingLine(int year, int productId)
	{
		return new Line(year, productId);
	}
	...
}
&lt;/pre&gt;
&lt;/li&gt;
&lt;/ol&gt;&lt;br/&gt;
It is easy to see how the intentions of the different constructors are present in the names of their Creation Methods.  The second overload&amp;#8217;s Creation Method now clearly creates a mapping line whereas the first creates an actual line.  This helps the developer avoid assumptions when reading the client code!
&lt;br/&gt;&lt;br/&gt;
Joshua lists pros and cons for each refactoring.  For this refactoring, the positives are that we can express intentions and increase the readability/maintainability of our code.  Also, in cases where a single constructor creates two instances that behave differently, we can get around this by using the exact same parameter set but showing the intended differences in the Creation Method names.  Whereas with constructors we can only have one constructor per parameter set.  Finally, a word of caution, using Creation Methods is rather non standard.  I would personally, and Joshua hints at it too, use some type of Factory/pattern with this instead of just a Creation Method.  I &lt;b&gt;feel&lt;/b&gt; that developers are likely to be familiar with the Factory/pattern(s) and know to look for that when constructors are missing, at least more so than Creation Methods.
&lt;br/&gt;
Happy Coding!&lt;/p&gt;</description><link>http://wesmcclure.tumblr.com/post/125036461</link><guid>http://wesmcclure.tumblr.com/post/125036461</guid><pubDate>Wed, 17 Jun 2009 01:46:00 -0400</pubDate><category>Patterns</category><category>Refactoring</category></item></channel></rss>
