<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Making the Complex Simple &#187; Refactoring</title>
	<atom:link href="http://simpleprogrammer.com/category/refactoring/feed/" rel="self" type="application/rss+xml" />
	<link>http://simpleprogrammer.com</link>
	<description>Software Development from John Sonmez&#039;s Perspective</description>
	<lastBuildDate>Tue, 07 Feb 2012 17:47:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='simpleprogrammer.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Making the Complex Simple &#187; Refactoring</title>
		<link>http://simpleprogrammer.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://simpleprogrammer.com/osd.xml" title="Making the Complex Simple" />
	<atom:link rel='hub' href='http://simpleprogrammer.com/?pushpress=hub'/>
		<item>
		<title>A Simple Wrapper To Make Things More Fluent</title>
		<link>http://simpleprogrammer.com/2010/10/12/a-simple-wrapper-to-make-things-more-fluent/</link>
		<comments>http://simpleprogrammer.com/2010/10/12/a-simple-wrapper-to-make-things-more-fluent/#comments</comments>
		<pubDate>Tue, 12 Oct 2010 15:52:35 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Cool Stuff]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Refactoring]]></category>

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

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

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

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

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

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

		<media:content url="http://complextosimple.files.wordpress.com/2010/10/wrapped_thumb.jpg" medium="image">
			<media:title type="html">wrapped</media:title>
		</media:content>
	</item>
		<item>
		<title>Living Dangerously: Refactoring without a Safety Net</title>
		<link>http://simpleprogrammer.com/2010/10/01/living-dangerously-refactoring-without-a-safety-net/</link>
		<comments>http://simpleprogrammer.com/2010/10/01/living-dangerously-refactoring-without-a-safety-net/#comments</comments>
		<pubDate>Fri, 01 Oct 2010 16:53:49 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[IDEs]]></category>
		<category><![CDATA[Refactoring]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/2010/10/01/living-dangerously-refactoring-without-a-safety-net/</guid>
		<description><![CDATA[It’s usually a good idea to have unit tests in place before attempting to refactor some code. I’m going to go against the grain here today though and tell you that it is not always required. Many times code that should be refactored doesn’t get refactored due to the myth that you must always have [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1124&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>It’s usually a good idea to have unit tests in place before attempting to refactor some code.</p>
<p>I’m going to go against the grain here today though and tell you that it is not always required.</p>
<p>Many times code that should be refactored doesn’t get refactored due to the myth that you must always have unit tests in place before refactoring.&#160; </p>
<p>In many cases the same code stays unimproved over many revisions because the effort of creating the unit tests needed to refactor it is too high.</p>
<p>I think this is a shame because it is not always necessary to have unit tests in place before refactoring.</p>
<p><a href="http://complextosimple.files.wordpress.com/2010/10/manonwire3.jpg"><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="Philippe Petit" border="0" alt="Philippe Petit" src="http://complextosimple.files.wordpress.com/2010/10/manonwire3_thumb.jpg?w=503&#038;h=310" width="503" height="310" /></a></p>
<h2>Forgoing the safety net</h2>
<p>If you go to the circus, you will notice that some acts always have a safety net below because the stunt is so dangerous that there is always a chance of failure.&#160; </p>
<p>You’ll also notice that some acts don’t have a safety net, because even though there is risk of danger, it is extremely small, because of the training of the performers.</p>
<p>Today I’m going to talk about some of the instances where you don’t necessarily need to have a safety net in place before doing the refactor.</p>
<p><strong>Automatic refactorings</strong></p>
<p>This is an easy one that should be fairly obvious.&#160; If you use a modern IDE like Visual Studio, Eclipse, or IntelliJ, you will no doubt have seen what I call “right-click refactor” options.</p>
<p>Any of these automatic refactors are pretty much safe to do anytime without any worry of changing functionality.&#160; These kinds of automated refactors simply apply an algorithm to the code to produce the desired result and in almost all cases do not change functionality.</p>
<p>These refactoring tools you can trust because there is not a chance for human error.</p>
<p>Any time you have the option of using an automatic refactoring, do it!&#160; It just makes sense, even if you have unit tests.&#160; I am always surprised when I pair up with someone and they are manually doing refactorings like “extract method” or “rename.”</p>
<p>Most of the time everything you want to do to some code can be found in one of the automatic refactoring menus.</p>
<p><strong>Small step refactors</strong></p>
<p>While not as safe as automatic refactors, if you have a refactor that is a very small step, there is a much higher chance your brain can understand it and prevent any side effects.</p>
<p>A good example of this would be my post on <a href="http://simpleprogrammer.com/2010/01/18/how-to-refactor-removal-of-conditions/">refactoring the removal of conditions</a>.</p>
<p>The general idea is that if you can make very simple small steps that are so trivial that there is almost no chance of mistake, then you can end up making a big refactor as the net effect of those little changes.</p>
<p>This one is a judgment call.&#160; It is up to you to decide if what you are doing is a small step or not.&#160; </p>
<p>I do find that if I want to do a refactor that isn’t a small step refactor, I can usually break it down into a series of small steps that I can feel pretty confident in.&#160; (Most of the time these will be automated refactors anyway.)</p>
<p><strong>Turning methods into classes</strong></p>
<p>I hate huge classes.&#160; Many times everyone is afraid to take stuff out of a huge class, because it is likely to break and it would take years to write unit tests for that class.</p>
<p>One simple step, which greatly improves the architecture and lets you eventually create unit tests, is to take a big ol’ chunk of that class, move it to a new class, and keep all the logic in there exactly how it is.</p>
<p>It’s not always totally clean, you might have to pass in some dependencies to the new method or new class constructor, but if you can do it, it can be an easy and safe refactor that will allow you to write unit tests for the new class.</p>
<p>Obviously this one is slightly more dangerous than the other two I have mentioned before, but it also is one that has a huge “bang for your buck.”</p>
<p><strong>Unit tests, or test code themselves</strong></p>
<p>Another obvious one.&#160; Unless you are going to write meta-unit tests, you are going to have to live a little dangerously on this one.&#160; You really have no choice.</p>
<p>I think everyone will agree that refactoring unit tests is important though.&#160;&#160; So, how come no one is afraid to refactor unit tests?</p>
<p>I only include this example to make the point that you shouldn’t be so scared to refactor code without having unit tests.&#160; You probably do it pretty frequently with your unit tests.</p>
<h2>I’m not advocating recklessness here</h2>
<p>I know some of you are freaking out right now.</p>
<p>Be assured, my message is not to haphazardly refactor code without unit tests.&#160; My message is simply to use temperance when considering a refactor.</p>
<p>Don’t forgo a refactor just because you are following a hard and fast rule that you need unit tests first.</p>
<p>Instead, I am suggesting that some refactorings are so trivial and safe that if it comes between the choice of leaving the code as it is because unit testing will take too long, or refactoring the code without the safety net, don’t be a… umm… <strike>pu…</strike> wimp.&#160; Use your brain!</p>
<h2></h2>
<h2>Things that will bite you hard</h2>
<p>There are a few things to watch out for, even with the automatic refactorings.&#160; Even those can fail and cause all kinds of problems for you.</p>
<p>Most of these issues won’t exist in your code base unless you are doing some crazy funky stuff.</p>
<ul>
<li>If you’re using <em>dynamic </em>in C#, or some kind of PInvoke, <em>unsafe </em>(pointer manipulation) or COM interop, all bets are off on things like rename. </li>
<li>Reflection.&#160; Watch out for this one.&#160; This can really kick you in the gonads.&#160; If you are using reflection, changing a method name or a type could cause a failure that is only going to be seen at runtime. </li>
<li>Code generation.&#160; Watch out for this one also.&#160; If generated code is depending on a particular implementation of some functionality in your system, refactoring tools won’t have any idea. </li>
<li>External published interfaces.&#160; This goes without saying, but it is so important that I will mention it here.&#160; Watch out for other people using your published APIs.&#160; Whether you have unit tests or not, refactoring published APIs can cause you a whole bunch of nightmares. </li>
</ul>
<p>This list isn’t to scare you off from refactoring, but if you know any of the things in this list are in your code base, check before you do the refactor.&#160; Make sure that the code you are refactoring won’t be affected by these kinds of things.</p>
<h6><strong>As always, you can subscribe to this </strong><a href="http://feeds.feedburner.com/MakingTheComplexSimple"><strong>RSS feed</strong></a><strong> to follow my posts on Making the Complex Simple.&#160; Feel free to check out </strong><a href="http://elegantcode.com/"><strong>ElegantCode.com</strong></a><strong> where I post about the topic of writing elegant code about once a week.&#160; Also, you can follow me on twitter </strong><a href="http://twitter.com/jsonmez"><strong>here</strong></a><strong>.</strong></h6>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/1124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1124/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1124&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/10/01/living-dangerously-refactoring-without-a-safety-net/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>

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

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

		<guid isPermaLink="false">https://complextosimple.wordpress.com/?p=1109</guid>
		<description><![CDATA[Lately there has been a lot of chatter about whether writing clean code actually saves money or whether it is more about art, i.e. making things pretty. (See John MacIntyre’s post here if you are interested, and Uncle Bob’s response here.) Well, as Forest Gump would say,  “Maybe it’s both.” How can it be both? [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1109&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Lately there has been a lot of chatter about whether writing <a href="http://www.amazon.com/gp/product/0132350882?ie=UTF8&amp;tag=makithecompsi-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0132350882">clean code</a> actually saves money or whether it is more about art, i.e. making things pretty.</p>
<p>(See John MacIntyre’s post <a href="http://whileicompile.wordpress.com/2010/08/24/my-clean-code-experience-no-1/">here</a> if you are interested, and Uncle Bob’s response <a href="http://thecleancoder.blogspot.com/2010/09/john-macintyres-clean-code-experience-1.html">here</a>.)</p>
<p>Well, as Forest Gump would say,  “Maybe it’s both.”</p>
<h2><a href="http://complextosimple.files.wordpress.com/2010/09/gump.jpg"><img style="background-image:none;padding-left:0;padding-right:0;display:block;float:none;padding-top:0;border:0;" title="gump" src="http://complextosimple.files.wordpress.com/2010/09/gump_thumb.jpg?w=290&#038;h=358" border="0" alt="gump" width="290" height="358" /></a></h2>
<h2>How can it be both?</h2>
<p>I think overall writing clean code saves you money to build software.  (Unless the <a href="http://simpleprogrammer.com/2010/04/17/when-doing-the-right-thing-is-wrong/">time you are going to spend maintaining the software</a> is minimal or non-existent.)</p>
<p>The reason why it saves you money is where the both part comes into play.</p>
<p>If we just extracted the money part from the practice of writing clean code, we can make a pretty solid argument that overall it saves money by looking at what costs the most time and money in software development.</p>
<p>Go ahead take a guess.  What do you think it is?</p>
<p>That’s right.  <strong>Fixing a production bug.</strong> It may take awhile to write unit tests.  It may take awhile to refactor you code to be “clean.” But, if spending an extra 3 hours on a 3 hour coding task ends up saving you just 1 production issue, you’ve made your time back and then some.</p>
<p><strong>The actual time expense of a production issue, all the way down the line, from project managers to QA to programmers to back to QA and back to deployment can easily cost 10 or more hours per issue, easily.</strong></p>
<p>It’s really hard to argue against that logic by itself, but there is another element that comes into play here.</p>
<p>The human element.</p>
<p>You see it’s not all about dollars and money and what makes logical or practical sense when you throw humans into the mix.  I believe if the non-human benefits writing clean code didn’t save you any money, overall it would still save you money.</p>
<p>Let me explain.</p>
<h2>No one takes pride in crap</h2>
<p>I don’t care if the software works or if it looks pretty on the outside.  The person maintaining that code is going to have a different view of it.</p>
<p>If the internal code is crap, if it is nothing to feel good about, if it is a big pile of spaghetti code, it is going to severely demotivate developers.</p>
<p><strong>And what do demotivated developers do?</strong></p>
<p>All kinds of horrible things.  They look for new jobs.  They write more crap code.  They waste time and stall.  They do what they have to to get by until they can either get the heck out of this stupid profession, or that dream job comes along where they can write ASP.NET MVC code using an auto-mocking container and BDD.</p>
<p>Sometimes you have to ask yourself, is it really that much more difficult to maintain that existing VB6 app than if it were converted to C#?  Seems like it shouldn’t be, right?  It definitely is easier to maintain a nicely built C# application, but there is a compelling reason why those applications eventually get rewritten, even though they really might not need to.</p>
<p>Developers working on old crusty applications just are not motivated to do so.  Developers like new shiny technology.  They like to feel like they are learning and expanding their skills, not just maintaining status quo.</p>
<p>So even though rewriting that VB6 application doesn’t really make practical sense… even though your metrics and charts tell you that you shouldn’t do it…  When you do rewrite that application you will find this magical hidden cost savings, because suddenly developers won’t drag their feet trying to fix a bug or add a feature to “that crappy old VB6 app.”  To the customer that application might even look exactly the same, but to the developers working on it, it will be a brand new shiny toy.</p>
<h2>Writing clean code is about more than saving money</h2>
<p>So you see, in the theoretical there are argument about whether refactoring that code will actually be a positive return on investment or negative.  I’ll argue for the positive on purely practical and chartable theory every time, but when you throw in the human art element, it is no contest.</p>
<p>If your code  base is something that your developers take pride in, you will see huge savings in time, because your developers will be significantly motivated to make it even better.</p>
<p><strong>Clean code begets clean code.</strong></p>
<p>So when I say it is both, I’m not just being non-committal or luke-warm about the topic.  The human element makes that fact that clean code is art important to saving money.</p>
<p><strong>As always, you can subscribe to this </strong><a href="http://feeds.feedburner.com/MakingTheComplexSimple"><strong>RSS feed</strong></a><strong> to follow my posts on Making the Complex Simple.  Feel free to check out </strong><a href="http://elegantcode.com/"><strong>ElegantCode.com</strong></a><strong> where I post about the topic of writing elegant code about once a week.  Also, you can follow me on twitter </strong><a href="http://twitter.com/jsonmez"><strong>here</strong></a><strong>.</strong></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/1109/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1109/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1109/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1109/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1109/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1109/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1109/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1109/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1109/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1109/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1109/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1109/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1109/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1109/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1109&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/09/21/clean-code-saves-money-or-is-art/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2010/09/gump_thumb.jpg" medium="image">
			<media:title type="html">gump</media:title>
		</media:content>
	</item>
		<item>
		<title>Switch is Just a Fancy If Else</title>
		<link>http://simpleprogrammer.com/2010/08/12/switch-is-just-a-fancy-if-else/</link>
		<comments>http://simpleprogrammer.com/2010/08/12/switch-is-just-a-fancy-if-else/#comments</comments>
		<pubDate>Thu, 12 Aug 2010 15:07:40 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Language]]></category>
		<category><![CDATA[Refactoring]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/?p=1047</guid>
		<description><![CDATA[Sorry to rain on your parade.  I know that you just refactored that series of if-else statements into one switch statement, and you&#8217;re feeling like you did your good deed for the day. Take a moment to rest on your laurels before I tear your laurels to shreds. Go ahead, I’ll wait. Okay, now let&#8217;s [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1047&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Sorry to rain on your parade.  I know that you just refactored that series of if-else statements into one switch statement, and you&#8217;re feeling like you did your good deed for the day.</p>
<p>Take a moment to rest on your laurels before I tear your laurels to shreds.</p>
<p>Go ahead, I’ll wait.</p>
<p>Okay, now let&#8217;s get down to business.</p>
<h2>Saying the same thing a different way</h2>
<p>The problem with changing if-else statements into a switch statement is that nothing really has changed besides the dialect in which it was said.</p>
<p>It’s all apples!</p>
<p><a href="http://complextosimple.files.wordpress.com/2010/08/apples.jpg"><img style="display:inline;border:0;" title="apples" src="http://complextosimple.files.wordpress.com/2010/08/apples_thumb.jpg?w=460&#038;h=310" border="0" alt="apples" width="460" height="310" /></a></p>
<p>Now, switch is slightly better than if-else for maintenance purposes, but not much better.  Both constructs (switch and if-else) try to represent some form of data (a mapping) as code.</p>
<p>Now data and code are not clearly delineated.  But, in general we have a concept of what constitutes data and what constitutes code.</p>
<p><strong>Data is some information that does not contain in itself logic.</strong></p>
<p><strong>Code is some information that is primarily instructions and logic.</strong></p>
<p>For this reason, I say that switch statements and if-else statements are both trying to treat data as logic.  They are both code constructs that mix in data elements with logic elements and do not clearly separate the two, although a switch statement does a slightly better job of it.</p>
<p>Consider the most basic form of an if-else and switch statement.  The form in which you directly map one piece of data to another piece of data.</p>
<p><em>If “A” then return “kittens”, If “B” then return “puppies”…</em></p>
<p><em>Switch (data1), case “A”: return “kittens”, case “B”: return “puppies”…</em></p>
<p>When I rewrite it in this form, the parallel becomes much more clear.   We can also very easily separate logic from data.</p>
<p><strong>Data:</strong></p>
<ul>
<li>”A”</li>
<li>”B”</li>
<li>”kittens”</li>
<li>”puppies”</li>
</ul>
<p><strong>Logic: </strong></p>
<ul>
<li>Map something of dataset1 to something of dataset2.</li>
<li>Return a mapped value.</li>
</ul>
<p>The problem with either of these forms, (the switch or the if-else), is that both of them tend to mix logic and data together.</p>
<h2>Why is it bad to mix logic and data?</h2>
<p>Let me ask you a question.  Which is more likely to change?</p>
<p>Hopefully it is data and not logic.</p>
<p>Consider the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single Responsibility Principle</a> (SRP.)</p>
<p>A module should have one and only one reason to change.  Ideally, we want to separate out logic from data so that we can change the two independently.</p>
<p>Sticking with our contrived example, suppose we wanted to make “A” map to “dinosaurs” instead of “kittens,” or we want to add more mappings.  We should be able to do this in a way that does not interfere with the logic at all or add new logic.</p>
<p>If we have an if-else structure, we will have to add more if-else constructs or change a data value that is inside of the method that is doing the logic.  The same applies for a switch statement.  We are not declaring our data one place and our logic another, they will be side by side, right next to each other in the code.</p>
<p>Suppose we want to change the logic so that instead of returning a value, we assign it to some variable, or reverse it.  Again, we are faced with changing logic in multiple places, in the same module as the data.</p>
<p>Consider the case where we want to read the data from a file or some other data source?  Is that possible with a switch or if-else structure?  Not really, because the data is essentially “hard-coded” into the logic.</p>
<h2>What can we do about it?</h2>
<p>So by now hopefully you have gotten the point that your refactoring of the if-else into a switch statement didn’t really solve the basic problem of mixing data and logic together.</p>
<p>But now, you have another problem.  You need to separate your data and logic so that they can change independently.  You want to be a good steward of the SRP.  You want to someday be able to read your data from a file or database, so that you won’t even have to recompile your code to change it.</p>
<p>On my <a href="http://simpleprogrammer.com/2010/08/17/pulling-out-the-switch-its-time-for-a-whooping/">next post</a>, I will show you how to take switch statements and refactor them into a better form that separates data from logic.</p>
<p>I will talk about the different “forms” of the switch statement and why to choose a particular method of refactoring over another.</p>
<h6>As always, you can subscribe to this <a href="http://feeds.feedburner.com/MakingTheComplexSimple">RSS feed</a> to follow my posts on Making the Complex Simple.  Feel free to check out <a href="http://elegantcode.com/">ElegantCode.com</a> where I post about the topic of writing elegant code about once a week.  Also, you can follow me on twitter <a href="http://twitter.com/jsonmez">here</a>.</h6>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/1047/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/1047/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/1047/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/1047/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/1047/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/1047/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/1047/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/1047/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/1047/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/1047/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/1047/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/1047/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/1047/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/1047/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=1047&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/08/12/switch-is-just-a-fancy-if-else/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2010/08/apples_thumb.jpg" medium="image">
			<media:title type="html">apples</media:title>
		</media:content>
	</item>
		<item>
		<title>Don&#8217;t Chain Failure States in Returns</title>
		<link>http://simpleprogrammer.com/2010/06/25/dont-chain-failure-states-in-returns/</link>
		<comments>http://simpleprogrammer.com/2010/06/25/dont-chain-failure-states-in-returns/#comments</comments>
		<pubDate>Fri, 25 Jun 2010 15:47:34 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Language]]></category>
		<category><![CDATA[Refactoring]]></category>

		<guid isPermaLink="false">https://complextosimple.wordpress.com/?p=964</guid>
		<description><![CDATA[I had originally started writing this post, thinking that I knew that answer to the problem I am about to demonstrate. What surprised me is how much more clean a try catch solution seems to work than my original solution. The unclean code I am using a short example here, so the refactoring might not [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=964&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I had originally started writing this post, thinking that I knew that answer to the problem I am about to demonstrate.</p>
<p>What surprised me is how much more clean a try catch solution seems to work than my original solution.</p>
<h2>The unclean code</h2>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:3bd0022f-f33f-4432-8d33-bdb7be5848ee" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp; pad-line-numbers: true;">
public void Process()
{
    foreach (string line in file)
    {
        string[] columns = line.split(',');
        foreach (string column in columns)
        {
            if (hasBadData(column))
            {
                LogErrorMessage();
                return;
            }

            Print(column);
        }
    }
}
</pre></p>
</div>
<p>I am using a short example here, so the refactoring might not really jump out to you as necessary, but let’s refactor it to be as clean as possible anyway.  (This comes from a much larger example where the refactoring is a must.)</p>
<h2>Refactor 1: Returning booleans</h2>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:aa2be422-8397-45a6-aee3-94208b7d6814" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
public void Process()
{
    foreach (string line in file)
    {
        if (!ProcessLine(line))
        {
            return;
        }
    }
}

private bool ProcessLine(string line)
{
    string[] columns = line.split(',');
    foreach (string column in columns)
    {
        if (!ProcessColumn(column))
        {
            return false;
        }
    }
    return true;
}

private bool ProcessColumn(string column)
{
    if (hasBadData(column))
    {
        LogErrorMessage();
        return false;
    }

    Print(column);
    return true;
}
</pre></p>
</div>
<p>We’ve broken each loop into its own method and separated the handling of each line and each column in each line into its own method.  A good refactor that makes things a little more clear.</p>
<p>Notice the bool return types on the new methods and the special handling to return early if a result is false.  Most people when refactoring the first example (myself included) forget that the first example breaks out of both loops with an early return.</p>
<p>If you don’t take this into account, your behavior will be different.  <strong>When you refactor, your behavior had better not be different.</strong></p>
<p>This is the crux of the problem.  Returning bools is bad.  It doesn’t make sense that our methods return bool.  What does the bool mean?  We happen to know it means success or failure, but will the next reader?  It seems very out of place, and look at the verbosity to handle the return types.</p>
<h2>Refactor 2: Storing error state</h2>
<p>This next refactor was what this post was going to be titled.  I was going to suggest in this post that you should not return boolean error states, but instead use the error state as part of your class.  I still think this is a decent solution.</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:3d58e88f-e2ab-42b0-ac70-39e2de429aa0" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
private bool IsFatalError { get; set; };

public void Process()
{
    foreach (string line in file)
    {
        ProcessLine(line);
        if (this.IsFatalError)
        {
            return;
        }
    }
}

private void ProcessLine(string line)
{
    string[] columns = line.split(',');
    foreach (string column in columns)
    {
        ProcessColumn(column);
        if (this.IsFatalError)
        {
            return;
        }
    }
}

private void ProcessColumn(string column)
{
    if (hasBadData(column))
    {
        LogErrorMessage();
        this.IsFatalError = true;
        return;
    }

    Print(column);
}
</pre></p>
</div>
<p>What we have done here is stored some state information about our object instead of chaining result codes down the method calls.  This is a huge improvement, because our meaning is much more explicit and our object is holding its own state.</p>
<p>It still is quite verbose.  Why do we have to check for a fatal error everywhere?  Seems like we are likely to forget.</p>
<p>Still, much better than returning booleans.  If you are in a class don’t be afraid to manipulate the state of that class internally.  <strong>Many times you can eliminate return values and parameters passed into private methods in a class by simply making that data part of the class.</strong></p>
<p>So, the verbosity was still bothering me.  So, I tried this:</p>
<h3>Refactor 3: Exception handler flow control</h3>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:154007d7-d1d7-404a-9aa1-bc284341a249" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
public void Process()
{
    try
    {
        foreach (string line in file)
        {
            ProcessLine(line);
        }
    }
    catch (BadColumnDataException exception)
    {
        LogErrorMessage();
    }
}

private void ProcessLine(string line)
{
    string[] columns = line.split(',');
    foreach (string column in columns)
    {
        ProcessColumn(column);
    }
}

private void ProcessColumn(string column)
{
    if (hasBadData(column))
    {
        throw new BadColumnDataException();
    }

    Print(column);
}
</pre></p>
</div>
<p>This is surprisingly clean.  Notice that we don’t actually have to put if conditions in the loops to check whether or not we should return early?  Instead, if an exception is thrown, flow will jump immediately to the catch block where we will log the error message.</p>
<p>I’m a little bit uncomfortable to be using exception handling as a flow control mechanism, but given that:</p>
<ol>
<li>When encountering the error, we are aborting the normal flow of the program completely (breaking out of two loops).</li>
<li>It is so much more clean and clear.</li>
</ol>
<p>I think this is actually my preferred solution.  I normally would never use exceptions where I could reasonably detect the failure condition, but I may have to rethink that viewpoint.</p>
<p><strong>As always, you can subscribe to this </strong><a href="http://feeds.feedburner.com/MakingTheComplexSimple"><strong>RSS feed</strong></a><strong> to follow my posts on Making the Complex Simple.  Feel free to check out </strong><a href="http://elegantcode.com/"><strong>ElegantCode.com</strong></a><strong> where I post about the topic of writing elegant code about once a week.  Also, you can follow me on twitter </strong><a href="http://twitter.com/jsonmez"><strong>here</strong></a><strong>.</strong></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/964/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/964/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/964/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/964/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/964/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/964/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/964/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/964/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/964/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/964/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/964/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/964/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/964/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/964/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=964&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/06/25/dont-chain-failure-states-in-returns/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>
	</item>
		<item>
		<title>How to Refactor the Helper Class</title>
		<link>http://simpleprogrammer.com/2010/04/14/how-to-refactor-the-helper-class/</link>
		<comments>http://simpleprogrammer.com/2010/04/14/how-to-refactor-the-helper-class/#comments</comments>
		<pubDate>Wed, 14 Apr 2010 16:01:58 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Legacy Code]]></category>
		<category><![CDATA[Refactoring]]></category>

		<guid isPermaLink="false">http://simpleprogrammer.com/?p=651</guid>
		<description><![CDATA[In my previous post, I posed the question Should I Leave that Helper Class?  Hopefully I&#8217;ve convinced you that you should not leave the helper class. Now, I&#8217;m going to detail some of the techniques I have used to eliminate helper classes in legacy code. First, let&#8217;s set a ground rule: We are not going [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=651&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In my previous post, I posed the question <a href="http://simpleprogrammer.com/2010/04/12/should-i-leave-that-helper-class/">Should I Leave that Helper Class</a>?  Hopefully I&#8217;ve convinced you that you should not leave the helper class.</p>
<p><a href="http://complextosimple.files.wordpress.com/2010/04/jabbahelper.png"><img class="alignnone size-full wp-image-675" title="jabbahelper" src="http://complextosimple.files.wordpress.com/2010/04/jabbahelper.png?w=500" alt=""   /></a></p>
<p>Now, I&#8217;m going to detail some of the techniques I have used to eliminate helper classes in legacy code.</p>
<p><strong>First, let&#8217;s set a ground rule:</strong> We are not going to just jump into legacy code and eliminate helper classes for the heck of it.  Why?</p>
<ol>
<li>It doesn&#8217;t have a good return on investment (ROI) for the time you spend doing it.</li>
<li>Your manager or general overlord will probably look at you with a disapproving frown, since you&#8217;re not adding any tangible value to the product.</li>
<li>If you break something, you will give refactoring a bad name, and be shunned by other developers.  You will have to wear a big red scarlet &#8220;R&#8221;.</li>
<li>It is not exactly fun.  I mean, it shouldn&#8217;t be fun&#8230;  Let me put it this way.  If this kind of thing is fun for you, then I&#8217;ve got a bunch of  other &#8220;fun&#8221; stuff you can do around my house.</li>
</ol>
<p>So what are we going to do then?  We are going to refactor the helper class into real classes or existing classes <strong>when we are modifying or adding functionality to it</strong>.  Let&#8217;s get started&#8230;</p>
<h2>Modifying a method</h2>
<p>If you have to modify a method that is in a helper class, the very first step is to move the logic <strong>as it is</strong> into a concrete class that we can write a unit test for.  Here is an example:</p>
<p><pre class="brush: csharp;">
public static int getDependantCount(MonsterObject stuff)
{
    int dependantCount = 0;
    List&lt;Relation&gt; relations = stuff.getPerson().getRelations();
    foreach(Relation relation in relations)
    {
        if(RelationshipHelper.isDependant(stuff.getPerson(), relation))
        {
            dependantCount++;
        }
    }

    return dependantCount;
}
</pre></p>
<p>Looking at this example, the first thing we need to do is to figure out what real class this helper class&#8217;s method belongs to.  (Quick side note here:  notice the helper method in question also uses another help class.  This is likely to be the case in the real world.)</p>
<p>One technique I use to figure this out is to look and see what data this helper method is using.  In this simple example it is pretty obvious that the data it is operating on belongs to <em>Person</em>, even though the method is passing in <em>MonsterObject. </em><strong>Usually the correct place to move a helper method is the place where you will maximize the amount of <em>this </em></strong><strong>operators that are used in the method.</strong></p>
<p>In this case, let&#8217;s move the helper method to person.  Here is what it would look like after:</p>
<p><pre class="brush: csharp;">
private int getDependantCount()
{
    int dependantCount = 0;
    List&lt;Relation&gt; relations = this.getRelations();
    foreach(Relation relation in relations)
    {
        if(RelationshipHelper.isDependant(this, relation))
        {
            dependantCount++;
        }
    }

    return dependantCount;
}
</pre></p>
<p>Notice what we did here?</p>
<ul>
<li>We eliminated a parameter being passed in.</li>
<li>We replaced a bunch of calls with this dot.</li>
<li>We made the method non-static and private.</li>
<li>And of course we moved it onto person, where it belonged.</li>
</ul>
<p>We still have a reference to the helper method it was originally calling, but we can eliminate that later down the road.  If this logic ends up being complex, we might have a <em>DependantCounter</em> class that takes in a list of relations that our Person method instantiates and calls in order to get the person count.</p>
<p>Our next step here is to write a unit test that tests the current functionality, then check in our code.  Finally, after we have that done, we can write a unit test that will fail for the changes we want to make to the method, and then modify the method.</p>
<p>It is much cleaner and easier to do things this way, and we have just eliminated a method in a helper class!</p>
<h2>Adding a method</h2>
<p>Adding a method to a helper class is much easier.  JUST DON&#8217;T DO IT!!!  Instead figure out what data that method is going to operate on and move it to the class that contains that data.</p>
<p>If the functionality you are going to add is large and seems to have its own responsibility, then go ahead and create a new class.</p>
<p>As you are modifying code and bringing the helper methods into real classes, or adding new methods in classes that would have been in helper classes by convention, you may start to see some of the classes these methods are being moved into grow.   That is ok, you are discovering that you need more classes.  A helper class is not a spill over class for long methods that you don&#8217;t want to put into the class they actually belong in.  Instead, the appropriate thing to do is to break up the class based on responsibility.</p>
<p>To stick with the current example, imagine a <em>Person</em> class that has some data on it for money.  Perhaps there is a private variable called <em>cashOnHand</em>.  As you add to the class you may end up bringing in data on their savings account, their outstanding loans.  You might bring in methods that operate on their savings account information and their cash on hand.  It is ok, and good to discover that <em>Person</em> becomes a separate thing than a person&#8217;s financial data.  At that point you might create a class called <em>Financials</em> and a person would have a reference to it.</p>
<h2>Refactoring helper classes is about figuring out where things belong.</h2>
<p>It is just like cleaning out the junk drawer in your kitchen.  You have to go through each item and find out where its real home should be.  If there isn&#8217;t one, you might have to make one.</p>
<p>If a method operates on a piece of data, it belongs as close to that data as possible.  Don&#8217;t try and tackle the huge helper class all at once, but rather eliminate the helper class piece by piece as you change or add functionality.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/651/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/651/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/651/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/651/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/651/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/651/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/651/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/651/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/651/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/651/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/651/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/651/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/651/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/651/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=651&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/04/14/how-to-refactor-the-helper-class/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2010/04/jabbahelper.png" medium="image">
			<media:title type="html">jabbahelper</media:title>
		</media:content>
	</item>
		<item>
		<title>Should I Leave That Helper Class</title>
		<link>http://simpleprogrammer.com/2010/04/12/should-i-leave-that-helper-class/</link>
		<comments>http://simpleprogrammer.com/2010/04/12/should-i-leave-that-helper-class/#comments</comments>
		<pubDate>Mon, 12 Apr 2010 14:59:13 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Legacy Code]]></category>
		<category><![CDATA[Refactoring]]></category>

		<guid isPermaLink="false">http://simpleprogrammer.com/?p=637</guid>
		<description><![CDATA[The project I am working on is riddled with &#8220;helper&#8221; classes.  What is a helper class? Good question.  I don&#8217;t really know.  Neither does the helper class. When you ask the helper class, what do you do&#8230; He half smiles, looks down at his over-sized feet and replies with a squirrely &#8221;stuff&#8221;. How to identify helper classes There are [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=637&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The project I am working on is riddled with &#8220;helper&#8221; classes.  What is a helper class?</p>
<p>Good question.  I don&#8217;t really know.  Neither does the helper class.</p>
<p>When you ask the helper class, what do you do&#8230; He half smiles, looks down at his over-sized feet and replies with a squirrely &#8221;stuff&#8221;.</p>
<h2>How to identify helper classes</h2>
<p>There are a few common attributes we can look at that will tell us if we are dealing with a helper class, in no particular order:</p>
<ul>
<li>Doesn&#8217;t have a clear responsibility of any kind.</li>
<li>Doesn&#8217;t hold any of its own state data.</li>
<li>Has mostly or all static methods.</li>
<li>Class name ends in helper.  (This is a good tip off!)</li>
<li>If it does get newed up somewhere, it gets passed all around afterwards.</li>
<li>Lives in a package or namespace called &#8220;utilities&#8221;.</li>
</ul>
<p>A helper class is a class that contains auxiliary methods for other classes, but isn&#8217;t really a thing in and of itself.  A helper class is <strong>the opposite of object oriented programming.</strong> I wrote about the dangers of static methods <a href="http://simpleprogrammer.com/2010/01/29/static-methods-will-shock-you/">before</a>, and helper classes usually are the result of proliferation and breeding of static methods.</p>
<p>We are going to skip going any further into why they are bad and go straight into the burning question&#8230;  When you see one of these in your code base&#8230;</p>
<h2>Should you just leave it there?</h2>
<h1><a href="http://complextosimple.files.wordpress.com/2010/04/just_say_no.gif"><img class="alignnone size-full wp-image-642" title="just_say_no" src="http://complextosimple.files.wordpress.com/2010/04/just_say_no.gif?w=500" alt=""   /></a></h1>
<p>(The above picture means &#8220;No&#8221;)</p>
<p>When you see a car accident on the freeway that no one has reported, should you just drive on and not dial 911?</p>
<p>When you see an old woman being <strong>beaten </strong>on the street, should you walk right on by?</p>
<p>When you open your fridge, and you open the vegetable drawer and you see a <strong>rotting</strong> cucumber mush in a bag, do you just forget you ever saw it?</p>
<p><a href="http://complextosimple.files.wordpress.com/2010/04/spoiledrotten_cucumber09.jpg"><img class="alignnone size-full wp-image-639" title="spoiledrotten_cucumber09" src="http://complextosimple.files.wordpress.com/2010/04/spoiledrotten_cucumber09.jpg?w=500" alt=""   /></a></p>
<p>I&#8217;m not suggesting you should start diving into your legacy code base and start removing all the helper methods right now.  But what I am saying is that if you are working inside of a helper method to change some functionality and you think it is ok to just add one more method, using some lame excuse like &#8220;it&#8217;s the convention&#8221;, I&#8217;d like to take a big boat paddle and teach you some single responsibility.  Don&#8217;t be part of the problem.  Be part of the solution.</p>
<p>Here are some lame excuses for leaving helper classes and propagating them.</p>
<ul>
<li>I am just making a small change to the code.</li>
<li>I don&#8217;t want to break this stuff that is already working.</li>
<li>I am just following the convention of the architecture.</li>
<li>I don&#8217;t understand how it works.</li>
<li>There is no class this functionality belongs too.</li>
<li>I&#8217;m a lazy bastard and I don&#8217;t care about making the world a better place.</li>
<li>The world is going to end in 2012 anyway.</li>
</ul>
<p>If you&#8217;re using one of these lame excuses&#8230; STOP IT!  3000 line helper classes weren&#8217;t born overnight.  Some idiot first created the class, then more idiots added methods to it.  Don&#8217;t be just another idiot.  I implore you.  We have enough.</p>
<h2>John, I want to do the right thing&#8230; help me.</h2>
<p>What?  You do?  I&#8217;ll assume you are being sincere&#8230; even though I have my reservations.</p>
<p>First take this oath.  Place your hand on <a href="http://www.amazon.com/gp/product/0201485419?ie=UTF8&amp;tag=makithecompsi-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0201485419">The Art of Computer Programming</a> and repeat after me.</p>
<blockquote><p>I, &lt;your name&gt;, solemnly swear to not propagate the aberration or pure evil and generally sucky code known as the helper class.</p>
<p>I promise to uphold the values of single responsibility, data abstraction, and the open closed principle.</p>
<p>I will vanquish helper classes, and helper methods and properly put them in associated classes where they belong, under no less penalty than having my arms and legs removed with a butter knife.</p></blockquote>
<p>Welcome initiates, <a href="http://simpleprogrammer.com/2010/04/14/how-to-refactor-the-helper-class/">next post</a> I&#8217;ll tell you some techniques I use to eliminate helper classes.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/637/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/637/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/637/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/637/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/637/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/637/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/637/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/637/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/637/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/637/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/637/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/637/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/637/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/637/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=637&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/04/12/should-i-leave-that-helper-class/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2010/04/just_say_no.gif" medium="image">
			<media:title type="html">just_say_no</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2010/04/spoiledrotten_cucumber09.jpg" medium="image">
			<media:title type="html">spoiledrotten_cucumber09</media:title>
		</media:content>
	</item>
		<item>
		<title>Refactor then Change Legacy Code</title>
		<link>http://simpleprogrammer.com/2010/03/26/refactor-then-change-legacy-code/</link>
		<comments>http://simpleprogrammer.com/2010/03/26/refactor-then-change-legacy-code/#comments</comments>
		<pubDate>Fri, 26 Mar 2010 17:08:59 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Process Improvement]]></category>
		<category><![CDATA[Refactoring]]></category>
		<category><![CDATA[Self Improvement]]></category>

		<guid isPermaLink="false">http://simpleprogrammer.com/?p=560</guid>
		<description><![CDATA[I was reminded yesterday of a very important step I had been forgetting when working with legacy code.  The first step.  Refactoring. Working with legacy code can be challenging.  Especially legacy code that was written by someone who didn&#8217;t know what they were doing and then modified 10 times by someone who didn&#8217;t care what [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=560&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I was reminded yesterday of a very important step I had been forgetting when working with legacy code.  The first step.  Refactoring.</p>
<p><a href="http://complextosimple.files.wordpress.com/2010/03/legacy.jpg"><img class="alignnone size-full wp-image-561" title="legacy" src="http://complextosimple.files.wordpress.com/2010/03/legacy.jpg?w=500" alt=""   /></a></p>
<p>Working with legacy code can be challenging.  Especially legacy code that was written by someone who didn&#8217;t know what they were doing and then modified 10 times by someone who didn&#8217;t care what they were doing.  (This is perhaps 90% of legacy code.)</p>
<p>I was having the tendency to jump right in and start implementing my clean feature in my own class that I would integrate into the legacy code, and move the relevant logic into my own class.</p>
<h2>The good way</h2>
<p>Let me see if I can summarize what my steps have looked like:</p>
<ol>
<li>Create failing unit test for new functionality I am implementing.</li>
<li>Create new class which only has the logic for that functionality, but that I know overlaps some of the legacy code.</li>
<li>Repeat until my functionality is working.</li>
<li>Integrate the use of my class into the legacy code.</li>
<li>Start moving parts of the legacy code that share the responsibility of my class into my class.</li>
<li>Refactor the remaining legacy code.</li>
</ol>
<h2>The better way</h2>
<p>I don&#8217;t think these steps are that bad.  But there is one problem, which is easily solved by adding the step of &#8220;Refactor the legacy code&#8221; at the beginning.  The problem is that of clearly knowing the responsibilities of the legacy code.  Most of the time in this situation the legacy code has multiple responsibilities.  When you are done implementing the new functionality and cleaning up the code, you should end up with several classes in single responsibility (<a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">SRP</a>).</p>
<p>The problem is that poorly written legacy code tends to hide all of the things it is doing.  Refactoring the code first allows you to be able to understand better what responsibilities may be hiding in the code.  It also allows you to better see the true structure of the logic, which helps to clearly identify the class you want to pull out to put your new logic in.</p>
<p>So, a better set of steps for adding functionality to legacy code is:</p>
<ol>
<li>Refactor legacy code to be as clean as possible.</li>
<li>Create failing unit test for new functionality I am implementing.</li>
<li>Create new class which only has the logic for that functionality, but that I know overlaps some of the legacy code.</li>
<li>Repeat until my functionality is working.</li>
<li>Integrate the use of my class into the legacy code.</li>
<li>Start moving parts of the legacy code that share the responsibility of my class into my class.</li>
<li>Refactor the remaining legacy code.</li>
</ol>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/560/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/560/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/560/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/560/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/560/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/560/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/560/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/560/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/560/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/560/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/560/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/560/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/560/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/560/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=560&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/03/26/refactor-then-change-legacy-code/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2010/03/legacy.jpg" medium="image">
			<media:title type="html">legacy</media:title>
		</media:content>
	</item>
		<item>
		<title>Super Combo: Map + Function Pointer</title>
		<link>http://simpleprogrammer.com/2010/02/25/super-combo-map-function-pointer/</link>
		<comments>http://simpleprogrammer.com/2010/02/25/super-combo-map-function-pointer/#comments</comments>
		<pubDate>Thu, 25 Feb 2010 17:00:01 +0000</pubDate>
		<dc:creator>jsonmez</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Cool Stuff]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Refactoring]]></category>

		<guid isPermaLink="false">http://simpleprogrammer.com/?p=421</guid>
		<description><![CDATA[Anyone who has coded with me, if asked to describe me in three words would say&#8230; Function-Pointer, Enumeration, Map When I get to combine 2 or more of these things together, I am usually pretty excited!  Map + Function Pointer to me is like a kick in the face to code duplication! Why is this [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=421&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Anyone who has coded with me, if asked to describe me in three words would say&#8230;</p>
<h1><strong><span style="color:#000000;">Function-Pointer, Enumeration, Map</span></strong></h1>
<p><strong><span style="color:#000000;"><br />
</span></strong></p>
<p>When I get to combine 2 or more of these things together, I am usually pretty excited!  Map + Function Pointer to me is like a <strong>kick in the face</strong> to code duplication!</p>
<p><a href="http://complextosimple.files.wordpress.com/2010/02/supercombokicktoface.jpg"><img class="alignnone size-medium wp-image-422" title="supercombokicktoface" src="http://complextosimple.files.wordpress.com/2010/02/supercombokicktoface.jpg?w=300&#038;h=168" alt="" width="300" height="168" /></a></p>
<p>Why is this little combo so awesome?</p>
<p>Let me give you a little code example:</p>
<p><pre class="brush: csharp;">
public void HandleData(DataPackage package)
{
    string packageType = package.GetType();
    switch(packageType)
    {
        case &quot;RoundHouseKick&quot;:
            Player.RoundHouseKick(package.destination);
            break;

        case &quot;FaceSlap&quot;:
            Player.FaceSlap(package.destination);
            break;

        case &quot;EvilEye&quot;:
            Player.Taunt(package.destination);
            break;

        case &quot;Bite&quot;:
            Player.Bite(package.destination);
            break;

        case &quot;FireBall&quot;:
            Player.Fireball(package.destination);
            break;
    }
}
</pre></p>
<p>Rewriting this as a super-awesome-hard-to-contain-myself map of function pointers you get:</p>
<p><pre class="brush: csharp;">
private Dictionary&lt;string, Func&lt;Destination&gt;&gt; moveMap = new Dictionary&lt;string, Func&lt;Destination&gt;&gt;()
{
   { &quot;RoundHouseKick&quot;, Player.RoundHouseKick },
   { &quot;FaceSlap&quot;, Player.FaceSlap },
   { &quot;EvilEye&quot;, Player.Taunt },
   { &quot;Bite&quot;, Player.Bite },
   { &quot;FireBall&quot;, Player.FireBall },
};

public void HandleData2(DataPackage package)
{
   string packageType = package.GetType();
   moveMap[packageType](package.destination);
}
</pre></p>
<p>Now if we forgo the use of strings, but use an enumeration from the get go&#8230;  We achieve the most-super-awesome-ultimate-combo <span style="text-decoration:underline;">MAP OF ENUMERATIONS TO FUNCTION POINTERS!!!</span></p>
<p><pre class="brush: csharp;">
public enum Moves
{
    RoundHouseKick,
    FaceSlap,
    EvilEye,
    Bite,
    FireBall
}

private Dictionary&lt;Moves, Func&lt;Destination&gt;&gt; moveMap = new Dictionary&lt;Moves, Func&lt;Destination&gt;&gt;()
{
    { Moves.RoundHouseKick, Player.RoundHouseKick },
    { Moves.FaceSlap, Player.FaceSlap },
    { Moves.EvilEye, Player.Taunt },
    { Moves.Bite, Player.Bite },
    { Moves.FireBall, Player.FireBall },
};

public void HandleData2(DataPackage package)
{
    Moves moveType = package.GetType();
    moveMap[moveType](package.destination);
}
</pre></p>
<h2>Why is this so super awesome?</h2>
<p>It isn&#8217;t as apparent in a little code snippet, but imagine an application where you have many sections of code that deal with this logic in the same way.  Often you encounter a third-party API that has methods or properties that are named after the type of data they work on or retrieve instead of having a parameter passed in.  In situations like these, it is very useful to map the mapping between data and logic into one location.</p>
<p>I also don&#8217;t like switch statements very much.  They can be confusing with the break statements in there, and end up being duplicated all over of the code base.  Anytime you see a switch statement in code, it is a possible candidate for the super-fantastic-mega-awesome-30-hit-combo of Map + Function pointer.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/complextosimple.wordpress.com/421/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/complextosimple.wordpress.com/421/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/complextosimple.wordpress.com/421/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/complextosimple.wordpress.com/421/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/complextosimple.wordpress.com/421/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/complextosimple.wordpress.com/421/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/complextosimple.wordpress.com/421/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/complextosimple.wordpress.com/421/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/complextosimple.wordpress.com/421/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/complextosimple.wordpress.com/421/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/complextosimple.wordpress.com/421/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/complextosimple.wordpress.com/421/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/complextosimple.wordpress.com/421/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/complextosimple.wordpress.com/421/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=simpleprogrammer.com&amp;blog=10597120&amp;post=421&amp;subd=complextosimple&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://simpleprogrammer.com/2010/02/25/super-combo-map-function-pointer/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/695e2a956b2dcb5ac45a7095b6ee338a?s=96&#38;d=retro&#38;r=PG" medium="image">
			<media:title type="html">jsonmez</media:title>
		</media:content>

		<media:content url="http://complextosimple.files.wordpress.com/2010/02/supercombokicktoface.jpg?w=300" medium="image">
			<media:title type="html">supercombokicktoface</media:title>
		</media:content>
	</item>
	</channel>
</rss>
