<?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; Decorator Pattern</title>
	<atom:link href="http://www.agileatwork.com/tag/decorator-pattern/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>Inheritance is Evil: The Epic Fail of the DataAnnotationsModelBinder</title>
		<link>http://www.agileatwork.com/inheritance-is-evil-the-story-of-the-epic-fail-of-dataannotationsmodelbinder/</link>
		<comments>http://www.agileatwork.com/inheritance-is-evil-the-story-of-the-epic-fail-of-dataannotationsmodelbinder/#comments</comments>
		<pubDate>Mon, 04 Jan 2010 14:52:10 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Decorator Pattern]]></category>
		<category><![CDATA[Single Responsibility Principle]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=312</guid>
		<description><![CDATA[The DataAnnotationsModelBinder is a pretty neat little class that enforces validation attributes on models like this one:
public class Product {
    public int Id { get; set; }

    [Required]
    public string Description { get; set; }

    [Required]
    [RegularExpression(@"^\$?\d+(\.(\d{2}))?$")]
    [...]]]></description>
			<content:encoded><![CDATA[<p>The <font face="Courier New" size="2">DataAnnotationsModelBinder</font> is a pretty neat little class that enforces validation attributes on models like this one:</p>
<pre class="prettyprint"><code>public class Product {
    public int Id { get; set; }

    [Required]
    public string Description { get; set; }

    [Required]
    [RegularExpression(@"^\$?\d+(\.(\d{2}))?$")]
    public decimal UnitPrice { get; set; }
}</code></pre>
<p>Just for the record, this is a <a href="http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24471">cool bit of code</a> that was released to the community for backseat drivers like me to use and complain about. I&#8217;m really only bitter because I can&#8217;t use it. Let&#8217;s take a peek at the source code to see why:</p>
<pre class="prettyprint"><code>/// &lt;summary&gt;
/// An implementation of IModelBinder which is designed to be a replacement
/// default model binder, adding the functionality of validation via the validation
/// attributes in System.ComponentModel.DataAnnotations from .NET 4.0.
/// &lt;/summary&gt;
public class DataAnnotationsModelBinder : DefaultModelBinder {
    ...
}</code></pre>
<p>The problem with this class is that it&#8217;s not just about validation. It&#8217;s more about binding with validation sprinkled in. The author even states this as a design goal with the comment &#8220;designed to be a replacement default model binder.&#8221; This is a violation of the Single Responsibility Principle and it&#8217;s the reason I can&#8217;t use it. The <font face="Courier New" size="2">DefaultModelBinder</font> does some basic reflection mapping of form elements to model properties. That&#8217;s cool, but what about a controller action that takes json, xml, or anything slightly more complicated than what the default binder can handle?</p>
<p>I&#8217;ll tell you what happens. You write a <a href="http://www.agileatwork.com/custom-model-binder-in-asp-net-mvc/">custom model binder</a> which is pretty easy and happens to be a pretty rad extension point in the MVC framework. Consider this model binder that deserializes json:</p>
<pre class="prettyprint"><code>public class JsonModelBinder&lt;T&gt; : IModelBinder {
    private string key;

    public JsonModelBinder(string requestKey) {
        this.key = requestKey;
    }

    public object BindModel(ControllerContext controllerContext, ...) {
        var json = controllerContext.HttpContext.Request[key];
        return new JsonSerializer().Deserialize&lt;T&gt;(json);
    }
}</code></pre>
<p>That&#8217;s pretty cool, but now I&#8217;ve lost my validation! This my friend is the evil of inheritance and the epic fail of the <font face="Courier New" size="2">DataAnnotationsModelBinder</font>. So what’s wrong with inheritance, isn’t that what OOP is all about? The short answer is no (the long answer is also no.)</p>
<p><img title="peter-venkman-ghostbusters" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="224" alt="peter-venkman-ghostbusters" src="http://www.agileatwork.com/wp-content/uploads/2010/01/petervenkmanghostbusters.jpg" width="300" border="0" /> </p>
<blockquote>
<p>Human sacrifice, dogs and cats living together&#8230; mass hysteria! &#8212; Dr. Peter Venkman</p>
</blockquote>
<p>Inheritance is pretty enticing especially coming from procedural-land and it often looks deceptively elegant. I mean all I need to do is add this one bit of functionality to another other class, right? Well, one of the problems is that inheritance is probably the worst form of coupling you can have. Your base class breaks encapsulation by exposing implementation details to subclasses in the form of protected members. This makes your system rigid and fragile.</p>
<p>The more tragic flaw however is the new subclass brings with it all the baggage and opinion of the inheritance chain. Why does a model that enforces validation attributes care how the model is constructed? The answer is it shouldn&#8217;t, and to add insult to injury, the better design is actually easier to implement. Listen closely and you may hear the wise whispers of our forefathers&#8230;</p>
<p><img title="Ward Cunningham" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="117" alt="Ward Cunningham" src="http://www.agileatwork.com/wp-content/uploads/2010/01/ward.jpg" width="92" border="0" /> <img title="Martin Fowler" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="117" alt="Martin Fowler" src="http://www.agileatwork.com/wp-content/uploads/2010/01/martin.jpg" width="94" border="0" /> <img title="Kent Beck" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="117" alt="Kent Beck" src="http://www.agileatwork.com/wp-content/uploads/2010/01/kent.jpg" width="78" border="0" /> <img title="Robert Martin" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="117" alt="Robert Martin" src="http://www.agileatwork.com/wp-content/uploads/2010/01/robert.jpg" width="87" border="0" /> </p>
<blockquote>
<p>Use the decorator pattern.</p>
</blockquote>
<p>Is this really going to solve all my problems? The short answer is yes. Let&#8217;s take a look:</p>
<pre class="prettyprint"><code>public class BetterDataAnnotationsModelBinder : IModelBinder {
    private IModelBinder binder;

    public BetterDataAnnotationsModelBinder(IModelBinder binder) {
        this.binder = binder;
    }

    public object BindModel(ControllerContext controllerContext, ...) {
        var model = binder.BindModel(controllerContext, bindingContext);
        AddValidationErrorsToModelState(model, controllerContext);
        return model;
    }

    ...
}</code></pre>
<p>Now all this class does is enforce validation and we can use whatever model binder we want to construct our object. Let&#8217;s wire this up in the Global.asax real quick: </p>
<pre class="prettyprint"><code>var productModelBinder = new JsonModelBinder&lt;Product&gt;("product");

ModelBinders.Binders.Add(
    typeof(Product),
    new BetterDataAnnotationsModelBinder(productModelBinder));</code></pre>
<p>This is cool for the following reasons:</p>
<ol>
<li>We are not coupled to the <font face="Courier New" size="2">DefaultModelBinder</font>. This means we don&#8217;t know or care about the structure and implementation details of it so it&#8217;s free to change in the next version of ASP.NET MVC. </li>
<li>The code is simpler because it is only about validation. </li>
<li>The behavior is composable. This means we can add validation to any model binder (like our json model binder) and bolt on more responsibilities with a chain of decorators. How about converting <font face="Courier New" size="2">DateTime</font> fields to UTC or striping formatting characters from phone numbers? </li>
<li>It&#8217;s easy to test. </li>
</ol>
<p>You can substitute a decorator for a subclass in most cases and in most cases it&#8217;s the right choice. You&#8217;re better off making the decorator your default choice and only settle for inheritance when you really need it.</p>
<p><img title="kip" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="184" alt="kip" src="http://www.agileatwork.com/wp-content/uploads/2010/01/kip.jpg" width="170" border="0" /> </p>
<blockquote>
<p>&#8230;don&#8217;t be jealous that I&#8217;ve been chatting online with babes all day. Besides, we both know that I&#8217;m training to be a cage fighter. &#8212; Kip</p>
</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/inheritance-is-evil-the-story-of-the-epic-fail-of-dataannotationsmodelbinder/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Custom Model Binder in ASP.NET MVC</title>
		<link>http://www.agileatwork.com/custom-model-binder-in-asp-net-mvc/</link>
		<comments>http://www.agileatwork.com/custom-model-binder-in-asp-net-mvc/#comments</comments>
		<pubDate>Thu, 31 Dec 2009 22:59:22 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Command Query Separation]]></category>
		<category><![CDATA[Decorator Pattern]]></category>
		<category><![CDATA[Single Responsibility Principle]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=298</guid>
		<description><![CDATA[The default model binder or DataAnnotationsModelBinder in ASP.NET MVC works well for simple data structures that basically map properties directly to form elements, but it quickly breaks down in a real world application. Take this simple scenario:

The built-in model binder can handle the easy fields like FirstName, LastName, and Email, but it doesn’t know how [...]]]></description>
			<content:encoded><![CDATA[<p>The default model binder or <font face="Courier New" size="2">DataAnnotationsModelBinder</font> in ASP.NET MVC works well for simple data structures that basically map properties directly to form elements, but it quickly breaks down in a real world application. Take this simple scenario:</p>
<p><img title="brimley" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="277" alt="brimley" src="http://www.agileatwork.com/wp-content/uploads/2009/12/brimley.png" width="253" border="0" /></p>
<p>The built-in model binder can handle the easy fields like <font face="Courier New" size="2">FirstName</font>, <font face="Courier New" size="2">LastName</font>, and <font face="Courier New" size="2">Email</font>, but it doesn’t know how to deal with the roles. This is where the custom model binder comes in:</p>
<pre class="prettyprint"><code>public class UserModelBinder : IModelBinder {
    private readonly IModelBinder binder;

    public UserModelBinder(IModelBinder binder) {
        this.binder = binder;
    }

    public object BindModel(ControllerContext controllerContext, ...) {
        var user = (User)binder.BindModel(controllerContext, bindingContext);
        AddRoles(user, controllerContext);
        return user;
    }

    private static void AddRoles(User user, ControllerContext controllerContext) {
        foreach (var role in GetRoles(controllerContext)) {
            user.Add(role);
        }
    }

    private static IEnumerable&lt;Role&gt; GetRoles(ControllerContext controllerContext) {
        var roles = controllerContext.HttpContext.Request["roles"];
        if (roles == null) yield break;
        foreach (var roleId in roles.Split(',')) {
            yield return (Role)Convert.ToInt32(roleId);
        }
    }
}</code></pre>
<p>And it gets wired-up in the Global.asax like this:</p>
<pre class="prettyprint"><code>var defaultBinder = new DataAnnotationsModelBinder();
ModelBinders.Binders.DefaultBinder = defaultBinder;
ModelBinders.Binders.Add(typeof(User), new UserModelBinder(defaultBinder));</code></pre>
<p>Because <font face="Courier New" size="2">UserModelBinder</font> is a decorator, it preserves the base functionality (like validation) of the default binder and only adds the part about mapping the roles. This is good stuff because it keeps construction of the model out of the controller. That&#8217;s the Single-Responsibility Principle in action.</p>
<h3>Command Query Separation</h3>
<p>The two functions <font face="Courier New" size="2">AddRoles</font>, and <font face="Courier New" size="2">GetRoles</font> are an example of command query separation (CQS). It would be easy to combine those two functions together and in fact that&#8217;s how it looked at first. So why bother separating them? Well it doesn&#8217;t <em>really</em> matter in this simple case, but it’s like how I tell my 3 year-old son to move his milk cup away from the edge of the table. I figure it’s a good habit that will prevent a few spills in the long run. The idea with CQS is there is a natural seam between finding objects and doing stuff with them. I buy that. I expect <font face="Courier New" size="2">GetRoles</font> to be more volatile than <font face="Courier New" size="2">AddRoles</font> or at least change for different reasons.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/custom-model-binder-in-asp-net-mvc/feed/</wfw:commentRss>
		<slash:comments>1</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>Integration Testing with NHibernate</title>
		<link>http://www.agileatwork.com/integration-testing-with-nhibernate/</link>
		<comments>http://www.agileatwork.com/integration-testing-with-nhibernate/#comments</comments>
		<pubDate>Fri, 06 Nov 2009 22:12:34 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Decorator Pattern]]></category>
		<category><![CDATA[Integration Testing]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=195</guid>
		<description><![CDATA[While the first-level cache in NHibernate is great for production, it can be super annoying for integration tests. Basically I just want to make sure my mapping works and that when I save an entity it goes to the database.

[TestFixture]
public class MyIntegrationFixture : IntegrationFixture {
&#160;&#160;&#160; [Test]
&#160;&#160;&#160; public void Can_add_elements() {
&#160;&#160;&#160; &#160;&#160;&#160; var repository = Container.Resolve&#60;IRepository&#60;MyEntity&#62;&#62;();
&#160;
&#160;&#160;&#160; [...]]]></description>
			<content:encoded><![CDATA[<p>While the first-level cache in NHibernate is great for production, it can be super annoying for integration tests. Basically I just want to make sure my mapping works and that when I save an entity it goes to the database.</p>
<div style="font-family: Courier New; font-size: 10pt; color: black; background: white;">
<pre style="margin: 0px;">[<span style="color: #2b91af;">TestFixture</span>]</pre>
<pre style="margin: 0px;"><span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">MyIntegrationFixture</span> : <span style="color: #2b91af;">IntegrationFixture</span> {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af;">Test</span>]</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">void</span> Can_add_elements() {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> repository = Container.Resolve&lt;<span style="color: #2b91af;">IRepository</span>&lt;<span style="color: #2b91af;">MyEntity</span>&gt;&gt;();</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> entity = repository.FindById(1);</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; entity.Add(<span style="color: blue;">new</span> <span style="color: #2b91af;">Element</span> { Description = <span style="color: #a31515;">&quot;The Description&quot;</span> });</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; repository.Save(entity);</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">Assert</span>.That(repository.FindById(1).Elements.Count(), <span style="color: #2b91af;">Is</span>.EqualTo(1));</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">}</pre>
</div>
<p>The problem is the next time I call <font face="Courier New" size="2">FindById()</font> I get my object back from the first level cache (<font face="Courier New" size="2">ISession</font>), so the Assert passes but looking at the SQL output by NHibernate I can see that no INSERT statement is happening. There are two things that NHibernate needs to do in order for the integration test to work as expected.</p>
<ol>
<li>There needs to be an explicit transaction and it needs to be committed in order to actually send the INSERT statements to the database. </li>
<li>The entity needs to be evicted from the session in order to ensure that the next call to <font face="Courier New" size="2">FindById()</font> actually goes to the database. </li>
</ol>
<p>It’s the job of the application to manage the scope of the unit of work. Typically this is per web request in a web app. In a test, it’s per test. This turns into a bunch of boiler-plate noise. Also, this business about evicting the session is an NHibernate specific thing and doesn’t belong in a test that is dealing with an <font face="Courier New" size="2">IRepository</font> abstraction.</p>
<p>Since I solve all my problems with a <a href="http://www.agileatwork.com/an-order-processing-pipeline-in-aspnet-mvc/">pipeline</a> or decorator, I figured I’d <a href="http://www.agileatwork.com/wp-content/uploads/2010/03/SessionDecorator.zip">decorate the <font face="Courier New" size="2">ISession</font></a> and commit and evict on the operations I care about:</p>
<div style="font-family: Courier New; font-size: 10pt; color: black; background: white;">
<pre style="margin: 0px;"><span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">AutoCommitAndEvictSession</span> : <span style="color: #2b91af;">SessionDecorator</span> {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> AutoCommitAndEvictSession(<span style="color: #2b91af;">ISession</span> session)</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; : <span style="color: blue;">base</span>(session) {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">override</span> <span style="color: blue;">object</span> Save(<span style="color: blue;">object</span> obj) {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">object</span> result;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">using</span> (<span style="color: blue;">var</span> tx = Session.BeginTransaction()) {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; result = Session.Save(obj);</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; tx.Commit();</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Session.Evict(obj);</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> result;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">override</span> <span style="color: blue;">void</span> Update(<span style="color: blue;">object</span> obj) {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; CommitAndEvict(<span style="color: blue;">base</span>.Update, obj);</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">override</span> <span style="color: blue;">void</span> SaveOrUpdate(<span style="color: blue;">object</span> obj) {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; CommitAndEvict(<span style="color: blue;">base</span>.SaveOrUpdate, obj);</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">override</span> <span style="color: blue;">void</span> Delete(<span style="color: blue;">object</span> obj) {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; CommitAndEvict(<span style="color: blue;">base</span>.Delete, obj);</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">void</span> CommitAndEvict(<span style="color: #2b91af;">Action</span>&lt;<span style="color: blue;">object</span>&gt; action, <span style="color: blue;">object</span> entity) {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">using</span> (<span style="color: blue;">var</span> tx = Session.BeginTransaction()) {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; action.Invoke(entity);</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; tx.Commit();</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Session.Evict(entity);</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">}</pre>
</div>
<p>Then I just work it into a test fixture like this:</p>
<div style="font-family: Courier New; font-size: 10pt; color: black; background: white;">
<pre style="margin: 0px;">[<span style="color: #2b91af;">TestFixture</span>]</pre>
<pre style="margin: 0px;"><span style="color: blue;">public</span> <span style="color: blue;">abstract</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">IntegrationFixture</span> {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">protected</span> <span style="color: #2b91af;">IUnityContainer</span> Container { <span style="color: blue;">get</span>; <span style="color: blue;">private</span> <span style="color: blue;">set</span>; }</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af;">TestFixtureSetUp</span>]</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">virtual</span> <span style="color: blue;">void</span> TestFixtureSetUp() {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Container = <span style="color: blue;">new</span> <span style="color: #2b91af;">UnityContainer</span>()</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; .AddNewExtension&lt;<span style="color: #2b91af;">ConfigureNHibernate</span>&gt;();</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af;">TestFixtureTearDown</span>]</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">virtual</span> <span style="color: blue;">void</span> TestFixtureTearDown() {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Container.Dispose();</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af;">SetUp</span>]</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">virtual</span> <span style="color: blue;">void</span> SetUp() {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> session = Container.Resolve&lt;<span style="color: #2b91af;">ISessionFactory</span>&gt;().OpenSession();</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="background-color: #ffffcc">Container.RegisterInstance&lt;<span style="color: #2b91af;">ISession</span>&gt;(<span style="color: blue;">new</span> <span style="color: #2b91af;">AutoCommitAndEvictSession</span>(session));</style>
</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af;">TearDown</span>]</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">virtual</span> <span style="color: blue;">void</span> TearDown() {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Container.Resolve&lt;<span style="color: #2b91af;">ISession</span>&gt;().Dispose();</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">}</pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/integration-testing-with-nhibernate/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Domain Driven Design in the Small</title>
		<link>http://www.agileatwork.com/domain-driven-design-in-the-small/</link>
		<comments>http://www.agileatwork.com/domain-driven-design-in-the-small/#comments</comments>
		<pubDate>Sun, 09 Aug 2009 05:20:41 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Decorator Pattern]]></category>
		<category><![CDATA[Domain Driven Design]]></category>
		<category><![CDATA[Refactoring]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=180</guid>
		<description><![CDATA[A few months ago we built a Magento extension to send orders to a product supplier via soap for payment and fulfillment along with affiliate tracking. As part of the process, a contact record was created in the affiliate&#8217;s CRM account.
&#160; 
Recently, the stake holders came up with a twist that went something like this: [...]]]></description>
			<content:encoded><![CDATA[<p>A few months ago we built a <a href="http://www.magentocommerce.com/">Magento</a> extension to send orders to a product supplier via soap for payment and fulfillment along with affiliate tracking. As part of the process, a contact record was created in the affiliate&#8217;s CRM account.</p>
<p>&#160;<img title="SubmitYourIdea" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="240" alt="SubmitYourIdea" src="http://www.agileatwork.com/wp-content/uploads/2009/08/SubmitYourIdea1.jpg" width="240" border="0" /> </p>
<p>Recently, the stake holders came up with a twist that went something like this: If the order contains a gift card, add the contact to a specific folder in the CRM application. No big deal, we had a nicely abstracted <font face="Courier New" size="2">OrderGateway</font> interface and I was already envisioning a quick addition to the existing decorator chain.</p>
<pre class="csharpcode"><span class="kwrd">class</span> OrderWithGiftCardGateway <span class="kwrd">extends</span> OrderGatewayDecorator
{
    ...

    <span class="kwrd">public function</span> createOrder(CreateOrderRequest $order)
    {
        <span class="kwrd">if</span> ($this-&gt;containsGiftCard($order))
        {
            $this-&gt;addContactToFolder($order);
        }

        <span class="kwrd">return parent</span>::createOrder($order);
    }
}</pre>
<p>I had a few minutiae questions like what happens with duplicates, etc. It took me nearly an hour to track down the right person and get real answers. During the conversation, a subtle comment was made that I almost missed.</p>
<p><em>Stake holder</em>: We should check with the product supplier to make sure the gift card sku I made up isn’t for a real product.</p>
<p><em>Me</em>: Say what?</p>
<p><em>Stake holder</em>: The gift card is not fulfilled by the product supplier, it’s fulfilled by the affiliate.</p>
<p><em>Me</em>: %$@!&amp;, I’m glad we had this conversation.</p>
<p>We talked about what it meant for the the affiliate to fulfill the product and basically the folder stuff was okay, but I recommended we remove the fake sku from the order before sending it through.</p>
<pre class="csharpcode"><span class="kwrd">public function</span> createOrder(CreateOrderRequest $order)
{
    <span class="kwrd">if</span> ($this-&gt;containsGiftCard($order))
    {
        $this-&gt;addContactToFolder($order);
        $this-&gt;removeGiftCardFromOrder($order);
    }

    <span class="kwrd">return parent</span>::createOrder($order);
}</pre>
<p>I didn’t have a buddy to pair with so I just grabbed Keith for a minute at the end of the day to walk through things. I recapped the stake holder discussion and we looked through the code. He pointed out I was missing the concept of fulfillment and that was hard earned knowledge that would be lost!</p>
<pre class="csharpcode"><span class="kwrd">public function</span> createOrder(CreateOrderRequest $order)
{
    <span class="kwrd">if</span> ($this-&gt;containsGiftCard($order))
    {
        $this-&gt;sendToAffiliateForFulfillment($order);
        $this-&gt;removeGiftCardFromOrder($order);
    }

    <span class="kwrd">return parent</span>::createOrder($order);
}</pre>
<blockquote>
<p>That was huge. – Paris Hilton</p>
</blockquote>
<p><object width="560" height="340"><param name="movie" value="http://www.youtube.com/v/3nGAk_mo6Rw&amp;hl=en&amp;fs=1&amp;"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/3nGAk_mo6Rw&amp;hl=en&amp;fs=1&amp;" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="560" height="340"></embed></object></p>
<p>Why was that huge? Because it changed the conversation. Right away we thought of important requirements like this should be in a transaction with the order and the template email the affiliate gets should include the customer’s address, etc.</p>
<p>It tells an important story for the next guy looking at the code and it changes the role of the programmer from code monkey to business partner. Maybe you think I’m crazy, but this stuff matters to me.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/domain-driven-design-in-the-small/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>The Holy Trinity of Web 2.0 Application Monitoring</title>
		<link>http://www.agileatwork.com/the-holy-trinity-of-web-2-0-application-monitoring/</link>
		<comments>http://www.agileatwork.com/the-holy-trinity-of-web-2-0-application-monitoring/#comments</comments>
		<pubDate>Fri, 24 Jul 2009 19:34:22 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></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=171</guid>
		<description><![CDATA[We had just rolled out a new system for a client and they were doing a high profile launch of their product. We had all our normal monitoring in place like CPU, memory, connections and page load time. Everything was swell…
On their signup form, we did an ajax call to check if their desired username [...]]]></description>
			<content:encoded><![CDATA[<p>We had just rolled out a new system for a client and they were doing a high profile launch of their product. We had all our normal monitoring in place like CPU, memory, connections and page load time. Everything was swell…</p>
<p>On their signup form, we did an ajax call to check if their desired username was available. If it wasn’t, we displayed a validation error an prevented the user from submitting the form. Turns out our little jquery script was silently bombing out and always returning ‘false’ meaning nobody could sign up!</p>
<p><a href="http://www.agileatwork.com/wp-content/uploads/2009/07/scaredmonkey.png"><img title="scared-monkey" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="240" alt="scared-monkey" src="http://www.agileatwork.com/wp-content/uploads/2009/07/scaredmonkey_thumb.png" width="238" border="0" /></a></p>
<p>This little issue slipped through the cracks and it hurt pretty bad. I couldn’t just tell the stake holders “sorry”, I needed something a little better so I spent some time with <a href="http://blog.mattbeckman.com/">Matt, our super do-everything networking guy</a>, and we put together the holy trinity of web 2.0 application monitoring (insert enlightenment music here).</p>
<p><img title="Nagios" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; vertical-align: middle; border-right-width: 0px" height="50" alt="Nagios" src="http://www.agileatwork.com/wp-content/uploads/2009/07/Nagios.png" width="212" border="0" />&#160; <font size="7">+</font>&#160; <img title="cruisecontrol" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; vertical-align: middle; border-right-width: 0px" height="42" alt="cruisecontrol" src="http://www.agileatwork.com/wp-content/uploads/2009/07/cruisecontrol.png" width="195" border="0" />&#160; <font size="7">+</font>&#160; <img title="selenium" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; vertical-align: middle; border-right-width: 0px" height="90" alt="selenium" src="http://www.agileatwork.com/wp-content/uploads/2009/07/selenium.png" width="100" border="0" /></p>
<p>We were already using <a href="http://www.nagios.org/">Nagios</a> for monitoring and alerting, <a href="http://cruisecontrol.sourceforge.net/">CruiseControl</a> for running unit tests, and <a href="http://seleniumhq.org/">Selenium</a> for automated web application testing. We just needed to glue it all together!</p>
<p>1) The first step was to write a selenium test to go through the online order sequence. We then exported it as a phpUnit test and dropped it in a our svn repository in a folder named “monitoring.”</p>
<p>2) Next, we configured a CruiseControl project named “selenium-bot” to pull down all the phpUnit tests from the “monitoring” folder in svn and run the whole test suite every 10 minutes.</p>
<p>3) The last step was to use Nagios to monitor the CruiseControl log file to make sure it was actually running every 10 minutes and returning all green. If anything stops working, Nagios takes care of the alerting.</p>
<p>I should also mention that since this hits the live online order form every 10 minutes, we needed a way to a way to short circuit the test orders. Fortunately, we already had a convenient <font face="Courier New" size="2">OrderGateway</font> interface, so we were able accomplish this in a very <a href="http://en.wikipedia.org/wiki/Open/closed_principle">open-closed</a> manner using the decorator pattern:</p>
<pre class="csharpcode"><span class="kwrd">class</span> TestOrderInterceptor <span class="kwrd">implements</span> OrderGateway
{
  <span class="kwrd">const</span> TEST_CODE = '843feaa7-bf13-4aff-91f6-a074434f9c14';
  <span class="kwrd">const</span> SUCCESS_RESULT = 1;

  <span class="kwrd">private</span> $orderGateway;
  <span class="kwrd">private</span> $logger;

  <span class="kwrd">public function</span> __construct(OrderGateway $orderGateway, Logger $logger)
  {
    $this-&gt;orderGateway = $orderGateway;
    $this-&gt;logger = $logger;
  }

  <span class="kwrd">public function</span> createOrder(CreateOrderRequest $order)
  {
    if ($this-&gt;isTest($order))
    {
      $this-&gt;logger-&gt;debug(<span class="str">'test order intercepted'</span>);
      <span class="kwrd">return self</span>::SUCCESS_RESULT;
    }

    <span class="kwrd">return</span> $this-&gt;orderGateway-&gt;createOrder($order);
  }

  <span class="kwrd">private function</span> isTest($request)
  {
    <span class="kwrd">return</span> strpos($request-&gt;name1, <span class="kwrd">self</span>::TEST_CODE) !== false;
  }
}</pre>
<p>The decorator chain is wired up using <a href="http://www.picocontainer.org/">PicoContainer</a>, and looks like this:</p>
<pre class="csharpcode">$pico-&gt;regComponentImpl(<span class="str">'SoapOrderGateway'</span>, <span class="str">'SoapOrderGateway'</span>);

$pico-&gt;regComponentImpl(<span class="str">'OrderGateway'</span>, <span class="str">'TestOrderInterceptor'</span>, <span class="kwrd">array</span>(
    <span class="kwrd">new</span> BasicComponentParameter(<span class="str">'SoapOrderGateway'</span>),
    <span class="kwrd">new</span> BasicComponentParameter(<span class="str">'Logger'</span>)));</pre>
<p>This infrastructure has paid dividends more than a few times and now I can’t imagine rolling out a site without it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/the-holy-trinity-of-web-2-0-application-monitoring/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

