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

<channel>
	<title>Agile at Work &#187; Chain of Responsibility</title>
	<atom:link href="http://www.agileatwork.com/tag/chain-of-responsibility/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.agileatwork.com</link>
	<description>by Michael Valenty</description>
	<lastBuildDate>Sat, 10 Sep 2011 14:35:33 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Tamarack: Chain of Responsibility Framework for .NET</title>
		<link>http://www.agileatwork.com/tamarack-chain-of-responsibility-framework-for-net/</link>
		<comments>http://www.agileatwork.com/tamarack-chain-of-responsibility-framework-for-net/#comments</comments>
		<pubDate>Fri, 22 Apr 2011 05:39:04 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Chain of Responsibility]]></category>
		<category><![CDATA[Inversion of Control]]></category>
		<category><![CDATA[Single Responsibility Principle]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=554</guid>
		<description><![CDATA[The Chain of Responsibility is a key building block of extensible software.
Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. – Gang of Four

Variations of this [...]]]></description>
			<content:encoded><![CDATA[<p>The Chain of Responsibility is a key building block of extensible software.</p>
<blockquote><p>Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. – Gang of Four</p>
</blockquote>
<p>Variations of this pattern are the basis for <a href="http://www.oracle.com/technetwork/java/filters-137243.html">Servlet Filters</a>, <a href="http://learn.iis.net/page.aspx/366/developing-iis-70-modules-and-handlers-with-the-net-framework/">IIS Modules and Handlers</a> and several open source projects I’ve had the opportunity to work with including <a href="https://www.forge.funambol.org/">Sync4J</a>, <a href="http://james.apache.org/">JAMES</a>, <a href="http://logging.apache.org/log4net/">Log4Net</a>, <a href="http://unity.codeplex.com/">Unity</a> and yes, even <a href="http://www.joomla.org/">Joomla</a>. It&#8217;s an essential tool in the OO toolbox and key in transforming rigid procedural code into a composable Domain Specific Language.</p>
<p><a href="http://www.agileatwork.com/where-does-it-hurt/">I’ve blogged about this pattern before</a> so what’s new this time?</p>
<ol>
<li>The next filter in the chain is provided via a delegate parameter rather than a property </li>
<li>The project is <a href="https://github.com/mikevalenty/tamarack">hosted on github</a> </li>
<li>There is a <a href="http://nuget.org/List/Search?packageType=Packages&amp;searchCategory=All+Categories&amp;searchTerm=tamarack">NuGet package</a> for it </li>
</ol>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="pkgmgr3" border="0" alt="pkgmgr3" src="http://www.agileatwork.com/wp-content/uploads/2011/04/pkgmgr31.png" width="640" height="332" /> </p>
<h3>How does it work?</h3>
<p>It&#8217;s pretty simple, there is just one interface to implement and it looks like this:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">interface</span> <span style="color: #2b91af">IFilter</span>&lt;T, TOut&gt;</pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">    TOut Execute(T context, <span style="color: #2b91af">Func</span>&lt;T, TOut&gt; executeNext);</pre>
<pre style="margin: 0px">}</pre>
</div>
<p>Basically, you get an input to operate on and a value to return. The <font size="2" face="Courier New">executeNext</font> parameter is a delegate for the next filter in the chain. The filters are composed together in a chain which is referred to as a <font size="2" face="Courier New">Pipeline</font> in the Tamarack framework. This structure is the essence of the Chain of Responsibility pattern and it facilitates some pretty cool things:</p>
<ul>
<li>Modify the input before the next filter gets it </li>
<li>Modify the output of the next filter before returning </li>
<li>Short circuit out of the chain by not calling the executeNext delegate </li>
</ul>
<h3>Show me examples!</h3>
<p>Consider a block of code to process a blog comment coming from a web-based rich text editor. There are probably several things you&#8217;ll want to do before letting the text into your database.</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">int</span> Submit(<span style="color: #2b91af">Post</span> post)</pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">var</span> pipeline = <span style="color: blue">new</span> <span style="color: #2b91af">Pipeline</span>&lt;<span style="color: #2b91af">Post</span>, <span style="color: blue">int</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Add(<span style="color: blue">new</span> <span style="color: #2b91af">CanoncalizeHtml</span>())</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Add(<span style="color: blue">new</span> <span style="color: #2b91af">StripMaliciousTags</span>())</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Add(<span style="color: blue">new</span> <span style="color: #2b91af">RemoveJavascript</span>())</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Add(<span style="color: blue">new</span> <span style="color: #2b91af">RewriteProfanity</span>())</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Add(<span style="color: blue">new</span> <span style="color: #2b91af">GuardAgainstDoublePost</span>())</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Finally(p =&gt; repository.Save(p));</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">var</span> newId = pipeline.Execute(post);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">return</span> newId;</pre>
<pre style="margin: 0px">}</pre>
</div>
<p>What about dependency injection for complex filters? Take a look at this user login pipeline. Notice the generic syntax for adding filters by type. Those filters are built-up using the supplied implementation of <font size="2" face="Courier New">System.IServiceProvider</font>. My favorite is <font size="2" face="Courier New">UnityServiceProvider</font>.</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">bool</span> Login(<span style="color: blue">string</span> username, <span style="color: blue">string</span> password)</pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">var</span> pipeline = <span style="color: blue">new</span> <span style="color: #2b91af">Pipeline</span>&lt;<span style="color: #2b91af">LoginContext</span>, <span style="color: blue">bool</span>&gt;(serviceProvider)</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Add&lt;<span style="color: #2b91af">WriteLoginAttemptToAuditLog</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Add&lt;<span style="color: #2b91af">LockoutOnConsecutiveFailures</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Add&lt;<span style="color: #2b91af">AuthenticateAgainstLocalStore</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Add&lt;<span style="color: #2b91af">AuthenticateAgainstLdap</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Finally(c =&gt; <span style="color: blue">false</span>);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">return</span> pipeline.Execute(<span style="color: blue">new</span> <span style="color: #2b91af">LoginContext</span>(username, password));</pre>
<pre style="margin: 0px">}</pre>
<pre style="margin: 0px">&#160;</pre>
</div>
<p>Here’s another place you might see the chain of responsibility pattern. Calculating the spam score of a block of text:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">double</span> CalculateSpamScore(<span style="color: blue">string</span> text)</pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">var</span> pipeline = <span style="color: blue">new</span> <span style="color: #2b91af">Pipeline</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">double</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Add&lt;<span style="color: #2b91af">SpamCopBlacklistFilter</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Add&lt;<span style="color: #2b91af">PerspcriptionDrugFilter</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Add&lt;<span style="color: #2b91af">PornographyFilter</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Finally(score =&gt; 0);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">return</span> pipeline.Execute(text);</pre>
<pre style="margin: 0px">}</pre>
<pre style="margin: 0px">&#160;</pre>
</div>
<p>Prefer convention over configuration? Try this instead:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">double</span> CalculateSpamScore(<span style="color: blue">string</span> text)</pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">var</span> pipeline = <span style="color: blue">new</span> <span style="color: #2b91af">Pipeline</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">double</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .AddFiltersIn(<span style="color: #a31515">&quot;Tamarack.Example.Pipeline.SpamScorer.Filters&quot;</span>)</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Finally(score =&gt; 0);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">return</span> pipeline.Execute(text);</pre>
<pre style="margin: 0px">}</pre>
</div>
<p>Let&#8217;s look at the <font size="2" face="Courier New">IFilter</font> interface in action. In the spam score calculator example, each filter looks for markers in the text and adds to the overall spam score by modifying the <em>result</em> of the next filter before returning.</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">PerspcriptionDrugFilter</span> : <span style="color: #2b91af">IFilter</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">double</span>&gt;</pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">double</span> Execute(<span style="color: blue">string</span> text, <span style="color: #2b91af">Func</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">double</span>&gt; executeNext)</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> score = executeNext(text);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (text.Contains(<span style="color: #a31515">&quot;viagra&quot;</span>))</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; score += .25;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> score;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">}</pre>
</div>
<p>In the login example, we look for the user in our local user store and if it exists we&#8217;ll short-circuit the chain and authenticate the request. Otherwise we&#8217;ll let the request continue to the next filter which looks for the user in an LDAP repository.</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">AuthenticateAgainstLocalStore</span> : <span style="color: #2b91af">IFilter</span>&lt;<span style="color: #2b91af">LoginContext</span>, <span style="color: blue">bool</span>&gt;</pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">IUserRepository</span> repository;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> AuthenticateAgainstLocalStore(<span style="color: #2b91af">IUserRepository</span> repository)</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.repository = repository;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">bool</span> Execute(<span style="color: #2b91af">LoginContext</span> context, <span style="color: #2b91af">Func</span>&lt;<span style="color: #2b91af">LoginContext</span>, <span style="color: blue">bool</span>&gt; executeNext)</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> user = repository.FindByUsername(context.Username);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (user != <span style="color: blue">null</span>)</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> user.IsValid(context.Password);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> executeNext(context);</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">}</pre>
</div>
<h3>Why should I use it?</h3>
<blockquote>
<p>It&#8217;s pretty much my favorite animal. It&#8217;s like a lion and a tiger mixed&#8230; bred for its skills in magic. – Napoleon Dynamite</p>
</blockquote>
<p>It’s simple and mildly opinionated in effort to guide you and your code into <a href="http://blogs.msdn.com/b/brada/archive/2003/10/02/50420.aspx">The Pit of Success</a>. It’s easy to write single responsibility classes and use inversion of control and composition and convention over configuration and lots of other goodness. Try it out. Tell a friend.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/tamarack-chain-of-responsibility-framework-for-net/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Where Does it Hurt?</title>
		<link>http://www.agileatwork.com/where-does-it-hurt/</link>
		<comments>http://www.agileatwork.com/where-does-it-hurt/#comments</comments>
		<pubDate>Sat, 26 Dec 2009 23:21:55 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[AOP]]></category>
		<category><![CDATA[Chain of Responsibility]]></category>
		<category><![CDATA[Decorator Pattern]]></category>
		<category><![CDATA[Inversion of Control]]></category>
		<category><![CDATA[Open Closed Principle]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=255</guid>
		<description><![CDATA[Notes from my Brown Bag Learning Forum Presentation. Download the source code, or just sit back and relax.
GoF Patterns:

Chain of Responsibility 
Decorator 
Adapter 

Buzz Phrases:

Single Responsibility Principle 
Open-Closed Principle 
Inversion of Control 
Aspect Oriented Programming 

Embracing the Single Responsibility Principle, Open-Closed Principle and Inversion of Control results in trading fragile application logic for fragile configuration [...]]]></description>
			<content:encoded><![CDATA[<p>Notes from my Brown Bag Learning Forum Presentation. <a href="http://www.secure-session.com/files/20/205/1664955444/E20E1B7ED7/i/brownbag-20110205b.zip">Download the source code</a>, or just sit back and relax.</p>
<p><strong>GoF Patterns:</strong></p>
<ul>
<li>Chain of Responsibility </li>
<li>Decorator </li>
<li>Adapter </li>
</ul>
<p><strong>Buzz Phrases:</strong></p>
<ul>
<li>Single Responsibility Principle </li>
<li>Open-Closed Principle </li>
<li>Inversion of Control </li>
<li>Aspect Oriented Programming </li>
</ul>
<p>Embracing the Single Responsibility Principle, Open-Closed Principle and Inversion of Control results in trading fragile application logic for fragile configuration logic. That’s a pretty good trade.</p>
<p>Fragile application logic is costly and it will come back to hurt you repeatedly. It goes without saying that fragile application logic is not testable, otherwise it wouldn’t be fragile. No tests mean changes are scary, so you have to compensate by regaining an intimate understanding of all the twists and turns in order to have enough confidence to make the change. The time and mental energy it takes to work through delicate and subtle conditional logic is enormous. My mediocre brain can only manage a short call stack and juggle a handful of variables at once.</p>
<p>Let’s say you’re sold on the promise of pretentious acronyms like SRP, OCP, IoC and the like. So now you end up with a billion small classes and gobs of code dedicated to wiring-up your favorite inversion of control container (mine is <a href="http://www.codeplex.com/unity">Unity</a>). Are we better for it? Let’s examine this trade-off by implementing the same functionality conventionally and using fancy patterns and principles.</p>
<p><strong>The Scenario:</strong> Implement captcha as the first step in some business process, like a registration form.</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="captcha2" border="0" alt="captcha2" src="http://www.agileatwork.com/wp-content/uploads/2009/12/captcha2.png" width="492" height="238" /> </p>
<p>That’s pretty easy, I don’t need anything fancy to do that.</p>
<pre class="prettyprint"><code>public class SimpleController : Controller {
    private const string CaptchaTextKey = "captcha_text";

    public ActionResult Index() {
        return View();
    }

    public ActionResult Render() {

        var captchaImage = new CaptchaImage();

        HttpContext.Session[CaptchaTextKey] = captchaImage.Text;

        using (Bitmap bitmap = captchaImage.RenderImage()) {
            using (var stream = new MemoryStream()) {
                bitmap.Save(stream, ImageFormat.Jpeg);
                return new FileContentResult(stream.ToArray(), "image/jpeg");
            }
        }
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Verify(string captchaText) {

        var actualText = (string)HttpContext.Session[CaptchaTextKey];

        if (captchaText.Equals(actualText)) {
            ViewData["message"] = "You are a human";
        } else {
            ViewData["message"] = "fail";
        }

        return View("Index");
    }
}</code></pre>
<p>Fast forward 3 months and amazingly new requirements have crept into the simple captcha controller. Consider these contrived yet poignant scenarios:</p>
<ul>
<li>After the project goes to QA, you realize there needs to be a way to bypass the captcha check so automated Selenium tests can get to the rest of the application. </li>
<li>After the project goes live, the business decides it wants to know how many users are hitting the form. So an audit log is added. </li>
<li>After reviewing the audit log, it is discovered that some IPs are attacking the form, so we decide to implement a black list. </li>
<li>After the black list is live, the servers begin to perform slowly, so detailed logging is added. </li>
<li>The logs show the black list lookup is slow during attacks, so it is determined that caching should be implemented. </li>
<li>The business is doing a television promotion and expects traffic spikes. IT wants real-time visibility to monitor the application during heavy load. </li>
</ul>
<p>Now our <font size="2" face="Courier New">SimpleController</font> has morphed into a <font size="2" face="Courier New">SmellyController</font>:</p>
<pre class="prettyprint"><code>public class SmellyController : Controller {

    // ...

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Verify(string captchaText) {

        var ip = HttpContext.Request.ServerVariables["REMOTE_ADDR"];

        var isBlackListed = IsBlackListed(ip);

        if (IsMatch(captchaText) &amp;&amp; !isBlackListed || captchaText == "selenium" {
            ViewData["message"] = "You are a human";

            // reset consecutive error count
            ConsecutiveErrorCount = 0;
        } else {
            ViewData["message"] = "fail";

            // add to black list
            if (ConsecutiveErrorCount++ &gt;= 3 &amp;&amp; !isBlackListed) {
                AddToBlackList(ip);
            }
        }

        WriteToAuditLog(ip);

        return View("Index");
    }

    private bool IsBlackListed(string ip) {
        var sessionKey = BlackListKey + ip;
        object result = HttpContext.Cache[sessionKey];

        if (result == null) {
            using (var connection = new SqlConnection(connectionString)) {
                connection.Open();
		var sql = "select count(*) from blacklist where ip = @ip";
                using (var command = new SqlCommand(sql)) {
                    command.Connection = connection;
                    command.Parameters.AddWithValue("@ip", ip);
                    result = Convert.ToBoolean(command.ExecuteScalar());
                }
            }
            HttpContext.Cache[sessionKey] = result;
        }

        return (bool)result;
    }

    private int ConsecutiveErrorCount {
        get { return Convert.ToInt32(HttpContext.Session[ErrorCountKey] ?? "0"); }
        set { HttpContext.Session[ErrorCountKey] = value; }
    }

    // ...

    private bool IsMatch(IEquatable&lt;string&gt; captchaText) {
        var actualText = (string)HttpContext.Session[CaptchaTextKey];
        return captchaText.Equals(actualText);
    }</code></pre>
<p>How does this smell? Let me count the ways:</p>
<ol>
<li><a href="http://xunitpatterns.com/Hard%20to%20Test%20Code.html">Hard to test</a>&#160; </li>
<li><a href="http://c2.com/cgi/wiki?MixingLevels">Mixed levels of abstraction</a> </li>
<li>No separation of concerns </li>
</ol>
<p>What if we had followed <a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod">Uncle Bob’s SOLID principles</a>? Our controller might look like this:</p>
<pre class="prettyprint"><code>public class SolidController : Controller {
    private readonly ICaptchaProvider captchaProvider;

    public SolidController(ICaptchaProvider captchaProvider) {
        this.captchaProvider = captchaProvider;
    }

    public ActionResult Index() {
        return View();
    }

    public ActionResult Render() {
        using (var stream = new MemoryStream()) {
            captchaProvider.Render(stream, ImageFormat.Jpeg);
            return new FileContentResult(stream.ToArray(), "image/jpeg");
        }
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Verify(string captchaText) {

        if (captchaProvider.Verify(captchaText)) {
            ViewData["message"] = "You are a human";
        } else {
            ViewData["message"] = "fail";
        }

        return View("Index");
    }
}</code></pre>
<p>And our original simple captcha provider could look like this:</p>
<pre class="prettyprint"><code>[Serializable]
public class SimpleCaptchaProvider : ICaptchaProvider {
    private string captchaText;

    public void Render(Stream stream, ImageFormat format) {
        var captchaImage = new CaptchaImage();

        captchaText = captchaImage.Text;

        using (Bitmap bitmap = captchaImage.RenderImage()) {
            bitmap.Save(stream, format);
        }
    }

    public bool Verify(string text) {
        return text.Equals(captchaText);
    }
}</code></pre>
<p>If you’re wondering why we don’t have to store the captcha text in the session, it’s because we’re <a href="http://www.agileatwork.com/captcha-and-inversion-of-control/">putting the onus on the container</a> to give us the same instance of <font size="2" face="Courier New">SimpleCaptchaProvider</font> each time it’s requested in the same session.</p>
<p>Let’s revisit the list of features that made our controller smelly and see how we could have done it open-closed style (by writing new code instead modifying old code). The go-to technique for this is the decorator pattern. So let’s make a decorator to look for a secret captcha password that our selenium test knows and let it through.</p>
<pre class="prettyprint"><code>public class SeleniumBypassCaptchaProvider : ICaptchaProvider {
    private readonly ICaptchaProvider captchaProvider;
    private readonly string password;

    public SeleniumBypassCaptchaProvider(
        ICaptchaProvider captchaProvider,
        string password) {

        this.captchaProvider = captchaProvider;
        this.password = password;
    }

    public void Render(Stream stream, ImageFormat format) {
        captchaProvider.Render(stream, format);
    }

    public bool Verify(string captchaText) {
        if (captchaText == password) {
            return true;
        }
        return captchaProvider.Verify(captchaText);
    }
}</code></pre>
<p>Next is the audit log, then the black list. These could be implemented as two more decorators, however we’re outgrowing this solution which means it’s time to refactor. Let’s switch hats for a few minutes and promote our decorator chain into an explicit chain of responsibility. This is like adding another lane to the freeway, it really opens things up. We’re modifying existing code so maybe you’re wondering what happened to our open-closed principle? It’s still there, I promise. The first point I’ll make is that refactoring is a special activity. It does not change the observable behavior of the application. When working with single responsibility classes, all we end up doing is adapting the logic to a different interface. In our case, we’re moving logic from <font size="2" face="Courier New">BlackListCaptchaProvider</font> to <font size="2" face="Courier New">BlackListVerifyFilter</font>. The logic stays intact and the unit tests are minimally impacted.</p>
<p>The end result of this refactor might look like this:</p>
<pre class="prettyprint"><code>public class VerifyChainCaptchaProvider : ICaptchaProvider {
    private readonly ICaptchaProvider captchaProvider;
    private readonly IServiceProvider serviceProvider;

    public VerifyChainCaptchaProvider(
        ICaptchaProvider captchaProvider,
        IServiceProvider serviceProvider) {

        this.captchaProvider = captchaProvider;
        this.serviceProvider = serviceProvider;
    }

    public void Render(Stream stream, ImageFormat format) {
        captchaProvider.Render(stream, format);
    }

    public bool Verify(string captchaText) {
        return new Pipeline&lt;string , bool&gt;(serviceProvider)
            .Add&lt;AuditLoggingFilter&gt;()
            .Add&lt;BlackListingFilter&gt;()
            .Add&lt;SeleniumBypassFilter&gt;()
            .Add(new CaptchaProviderAdapter(captchaProvider))
            .Process(captchaText);
    }
}</code></pre>
<p>Was it worth it? Well, we’re left with all these little classes each with their single responsibility, however we still have to wire it up. I’m not going to lie, it’s ugly and it’s fragile. So why is this design any better? It’s better because troubleshooting bad configuration is better than troubleshooting bad application logic. Bad application logic can do really bad things. In a 24/7 business-critical application, this usually happens around 3 AM and involves you waking up and trying adjust your eyes to a harsh laptop screen. With bad configuration on the other hand, whole chunks of functionality are just missing. Chances are your app won’t even start, or maybe it starts but the black list or the audit logging isn’t wired in. These issues are easy to test and when you fix them, you have enormous confidence that the functionality you just wired-in will work and continue to work in the wee hours of the morning.</p>
<p>The second point I’ll make is the code more closely follows the way we think about our application. This makes it easier to respond to change because new requirements are extensions of the way we already think about our application. Consider the scenario that our selenium secret passphrase is not secure enough for production and we want to add an IP restriction or signature to make sure it’s really our selenium test that is getting through. In our smelly controller, a selenium test bypass is not an explicit concept, it’s just an or-clause tacked on to the end of an already abused <font size="2" face="Courier New">if</font> statement. We’ll have to go into our smelly controller and do some thrashing around in the most important and delicate block of code. In our solid controller however, we have a nicely abstracted testable single responsibility class we can isolate our change to.</p>
<p>As another example, consider the scenario that our black list caching is consuming too much memory on the web server. With our SOLID design we can surgically replace our <font size="2" face="Courier New">ICacheProvider</font> with an implementation backed by <a href="http://www.codeplex.com/memcachedproviders">Memcached</a>. Bits of functionality are free to evolve at their own pace. Some areas of your application will need a beefy solution and some will be just fine with a simple one. The important thing is that concerns are isolated from each other and allowed to fulfill their own destiny.</p>
<h3>Aspect-Oriented Programming</h3>
<p>I mentioned aspect oriented programming at the beginning of the article in a shallow attempt to pique your interest. So before I wrap things up I’ll show how it fits in. Since we’re already using an IoC container and faithfully employing our SOLID design principles, we pretty much get AOP for free. This is a big deal. Software running under service level agreements and government regulations demands visibility and having aspects in your toolbox is a must. Because aspects are reusable, they are typically higher quality and more mature than something hand-rolled for a one-off scenario. And because they are bolt-on, our core business logic stays focused on our business domain.</p>
<p>Consider the cliché logging example. It’s overused, but works well not unlike the calculator example for unit testing or the singleton job interview question. The idea is that we tell our IoC container to apply a logging aspect to all objects it has registered. Here’s what my logging aspect produces:</p>
<pre style="padding-bottom: 3px; background-color: black; padding-left: 3px; padding-right: 3px; color: white; font-size: 10pt; padding-top: 3px">DEBUG VerifyChainCaptchaProvider.Render() stream = MemoryStream, format = Jpeg
DEBUG SimpleCaptchaProvider.Render() stream = MemoryStream, format = Jpeg
DEBUG SimpleCaptchaProvider.Render() [72 ms]
DEBUG VerifyChainCaptchaProvider.Render() [74 ms]
DEBUG VerifyChainCaptchaProvider.Verify() text = afds
DEBUG AuditLoggingFilter.Process() input = afds
DEBUG BlackListingFilter.Process() input = afds
DEBUG CachingBlackListService.IsBlocked() ip = 127.0.0.1
DEBUG CachingBlackListService.IsBlocked() &gt; False [0 ms]
DEBUG SeleniumBypassFilter.Process() input = afds
DEBUG SimpleCaptchaProvider.Verify() text = afds
DEBUG SimpleCaptchaProvider.Verify() &gt; False [0 ms]
DEBUG SeleniumBypassFilter.Process() &gt; False [1 ms]
DEBUG BlackListingFilter.Process() &gt; False [4 ms]
DEBUG AuditLoggingFilter.Process() &gt; False [8 ms]
DEBUG VerifyChainCaptchaProvider.Verify() &gt; False [14 ms]</pre>
<p>Again, this is powerful because we didn’t have to pollute our code with logging statements, yet we see quality log entries with input, output and execution time. In addition to logging, we can attach <a href="http://www.agileatwork.com/definition-of-enterprise-software/">performance counters</a> to meaningful events, add exception policies to notify us when things go wrong, selectively add caching at run-time and lots more. To see it all in action, you can <a href="http://www.secure-session.com/files/20/205/1664955444/E20E1B7ED7/i/brownbag-20110205b.zip">download the source code</a> for the examples used in this article.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/where-does-it-hurt/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>A Class Isn&#8217;t Always a Noun</title>
		<link>http://www.agileatwork.com/a-class-isnt-always-a-noun/</link>
		<comments>http://www.agileatwork.com/a-class-isnt-always-a-noun/#comments</comments>
		<pubDate>Fri, 04 Dec 2009 20:45:46 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Chain of Responsibility]]></category>
		<category><![CDATA[Domain Driven Design]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=230</guid>
		<description><![CDATA[There is a convention programmers go by that says object names should be nouns and methods names should start with a verb. That’s crap and I’ll tell you why. First off, it’s an old rule kind of like Hungarian notation. Okay that was low. To be fair, I would probably recommend this rule to a [...]]]></description>
			<content:encoded><![CDATA[<p>There is a convention programmers go by that says object names should be nouns and methods names should start with a verb. That’s crap and I’ll tell you why. First off, it’s an old rule kind of like Hungarian notation. Okay that was low. To be fair, I would probably recommend this rule to a college student.</p>
<p>However, if you’re doing this as your full-time job and you’re neck deep in a complex business domain, then you are seriously selling yourself short. When working in a team environment you’ve got to use every means possible to communicate what you were thinking and what hard-earned knowledge you gained along the way. Some poor sucker is going to open your project at some point and your code should be screaming important concepts right from the class list.</p>
<p><img title="yext" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="595" alt="yext" src="http://www.agileatwork.com/wp-content/uploads/2009/12/yext1.png" width="277" border="0" /> </p>
<p>I don’t expect you to understand how the app works, but you should at least get a feel right away for the things that are important. Knowing it’s a console app, you could find the entry point and quickly navigate to the meat and potatoes of the application.</p>
<pre class="prettyprint"><code>public class SyncListingJob : MarshalByRefObject, IJob
{
    private IServiceProvider locator;
    private YextListing listing;

    public SyncListingJob(IServiceProvider locator)
    {
        this.locator = locator;
    }

    public void Init(YextListing listing)
    {
        this.listing = listing;
    }

    [UnitOfWork]
    public void Execute()
    {
        GuardAgainstNotInitialized();
        SyncListing();
    }

    private void SyncListing()
    {
        new LocatorChain&lt;Yextlisting&gt;(locator)
            .AddNew&lt;RevertDiscontinuedListing&gt;()
            .AddNew&lt;RefreshLinkedBusiness&gt;()
            .AddNew&lt;CreateLinkToExistingBusiness&gt;()
            .AddNew&lt;CreateNewBusinessAndLink&gt;()
            .Process(listing);
    }

    private void GuardAgainstNotInitialized()
    {
        if (listing == null) throw new Exception("Job not initialized!");
    }
}</code></pre>
<p><em><font size="2">* The <font face="Courier New">LocatorChain&lt;T&gt;</font> is an implementation of the chain of responsibility pattern.</font></em></p>
<p>I do everything I can to push out all the noise and bring the behavior to the surface.&#160; Sometimes the right way to name a class is after a feature or behavior. I want my code to read like a DSL and making everything a noun just doesn’t cut it. The drivers for me are context and readability.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/a-class-isnt-always-a-noun/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

