<?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>Mind-driven development &#187; Design patterns</title>
	<atom:link href="http://www.minddriven.de/index.php/category/technology/development/design-patterns/feed" rel="self" type="application/rss+xml" />
	<link>http://www.minddriven.de</link>
	<description>Matthias Jauernig -- .NET technology, architecture and design</description>
	<lastBuildDate>Sun, 29 Jan 2012 19:31:38 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>Explicit Property Memento</title>
		<link>http://www.minddriven.de/index.php/technology/development/design-patterns/explicit-property-memento</link>
		<comments>http://www.minddriven.de/index.php/technology/development/design-patterns/explicit-property-memento#comments</comments>
		<pubDate>Sun, 12 Sep 2010 03:00:20 +0000</pubDate>
		<dc:creator>Matthias Jauernig</dc:creator>
				<category><![CDATA[Design patterns]]></category>
		<category><![CDATA[design pattern]]></category>
		<category><![CDATA[explicit]]></category>
		<category><![CDATA[memento]]></category>
		<category><![CDATA[property]]></category>
		<category><![CDATA[property memento]]></category>

		<guid isPermaLink="false">http://www.minddriven.de/?p=1042</guid>
		<description><![CDATA[Introduction Some weeks ago I&#8217;ve introduced the Property Memento pattern as solution for temporarily saving the state of an entity&#8217;s property on creation of the Property Memento and restoring this initial state when the Property Memento disposes. I&#8217;ve shown that the using(){} syntax separates between the Property Memento initialization and the core logic which should [...]]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>Some weeks ago <a href="http://www.minddriven.de/index.php/technology/development/design-patterns/property-memento-pattern">I&#8217;ve introduced</a> the <strong>Property Memento pattern</strong> as solution for temporarily saving the state of an entity&#8217;s property on creation of the Property Memento and restoring this initial state when the Property Memento disposes. I&#8217;ve shown that the <code>using(){}</code> syntax separates between the Property Memento initialization and the core logic which should be run inside the Memento with temporarily changed property values.</p>
<p>While I like the pattern and its usage, I see that the <code>using</code> syntax can be disturbing for developers who don&#8217;t know the internal implementation of the Property Memento. The implementation mixes <code>using</code> as common syntax with other semantics, which violates the <em>uniformity principle</em> of computer science.</p>
<p>A <a href="http://svenerikmatzen.wordpress.com/" target="_blank">colleague</a> suggested an implementation of the pattern, which makes the three steps in a Property Memento&#8217;s lifetime explicit:</p>
<ol>
<li><strong>Memorize</strong> the current properties values.</li>
<li><strong>Invoke</strong> some actions.</li>
<li><strong>Restore</strong> the memorized values.</li>
</ol>
<p>I&#8217;ve adopted his implementation to fit my needs of memorizing properties even for more than one entity.</p>
<h3>Explicit Property Memento implementation</h3>
<p>The implementation of the Explicit Property Memento projects the 3 steps of a Property Memento by the methods <code>Memorize()</code>, <code>Invoke()</code> and <code>RestoreValues()</code>. Thus the intention is revealed, which yields to a better understanding of the whole process. Instead of memorizing one property of just a single entity on the creation of the Property Memento, the <code>ExplicitPropertyMemento</code> has the ability to store several property values of more than one entity. This makes the implementation a bit heavier, but the usage very smart. First here&#8217;s the implementation part:</p>
<pre class="brush:csharp">public class ExplicitPropertyMemento
{
    class MemorizedProperty
    {
        public string Name { get; set; }
        public object Value { get; set; }
    }

    private readonly IDictionary&lt;object, List&lt;MemorizedProperty&gt;&gt; _memorizedProperties
        = new Dictionary&lt;object, List&lt;MemorizedProperty&gt;&gt;();

    public static ExplicitPropertyMemento Create
    {
        get { return new ExplicitPropertyMemento(); }
    }

    public ExplicitPropertyMemento Memorize(
        object classInstance, params Expression&lt;Func&lt;object&gt;&gt;[] propertySelectors)
    {
        if(propertySelectors == null)
            return this;

        var properties = new List&lt;MemorizedProperty&gt;();
        foreach(var propertySelector in propertySelectors)
        {
            string propertyName = GetPropertyName(propertySelector);
            properties.Add(new MemorizedProperty
                {
                    Name = propertyName,
                    Value = GetPropertyValue(classInstance, propertyName)
                });
        }

        if(_memorizedProperties.ContainsKey(classInstance))
            _memorizedProperties[classInstance].AddRange(properties);
        else
            _memorizedProperties.Add(classInstance, properties);

        return this;
    }

    public ExplicitPropertyMemento Memorize&lt;TProperty&gt;(object classInstance,
        Expression&lt;Func&lt;object&gt;&gt; propertySelector, TProperty tempValue)
    {
        Memorize(classInstance, propertySelector);

        string propertyName = GetPropertyName(propertySelector);
        SetPropertyValue(classInstance, propertyName, tempValue);

        return this;
    }

    public ExplicitPropertyMemento Invoke(Action action)
    {
        try
        {
            action.Invoke();
        }
        catch
        {
            RestoreValues();
            throw;
        }

        return this;
    }

    public void RestoreValues()
    {
        foreach(var memorizedEntity in _memorizedProperties)
        {
            object classInstance = memorizedEntity.Key;
            foreach(var property in memorizedEntity.Value)
                SetPropertyValue(classInstance, property.Name, property.Value);
        }
    }

    private string GetPropertyName(Expression&lt;Func&lt;object&gt;&gt; propertySelector)
    {
        var body = propertySelector.Body;
        if (body.NodeType == ExpressionType.Convert)
            body = ((UnaryExpression)body).Operand;
        return ((MemberExpression)body).Member.Name;
    }

    private object GetPropertyValue(object classInstance, string propertyName)
    {
        return classInstance
            .GetType()
            .GetProperty(propertyName)
            .GetValue(classInstance, null);
    }

    private void SetPropertyValue(object classInstance, string propertyName, object value)
    {
        classInstance
            .GetType()
            .GetProperty(propertyName)
            .SetValue(classInstance, value, null);
    }
}</pre>
<h3>Usage example</h3>
<p>The usage is explicitly projecting the Property Memento process by the methods <code>Memorize()</code>, <code>Invoke()</code> and <code>RestoreValues()</code> and it&#8217;s straightforward. In case of the <a href="http://www.minddriven.de/index.php/technology/development/design-patterns/property-memento-pattern" target="_blank">introductory example</a> it&#8217;s shown next:</p>
<pre class="brush:csharp">private void SomeMethod(...)
{
    int oldValSumHeight = _valSum.Height;
    int newValSumHeight = 0;

    var newAnchor = AnchorStyles.Top | AnchorStyles.Left;
    ExplicitPropertyMemento.Create
        .Memorize(_valSum, () =&gt; _valSum.AutoSize, true)
        .Memorize(_valSum, () =&gt; _valSum.Anchor, newAnchor)
        .Memorize(_detailContent, () =&gt; _detailContent.Anchor, newAnchor)
        .Invoke(() =&gt;
            {
                _valSum.SetValidationMessages(validationMessages);

                newValSumHeight = _valSum.Height;
                Height = Height - oldValSumHeight + newValSumHeight;
            })
        .RestoreValues();

    _valSum.Height = newValSumHeight;
}</pre>
<p>Alternatively the <code>ExplicitPropertyMemento</code> implementation allows specifying more than one property as argument for the <code>Memorize()</code> method, if you don&#8217;t want to set the new property value directly by this method. Thus you could use some code like this:</p>
<pre class="brush:csharp">private void SomeMethod(...)
{
    int oldValSumHeight = _valSum.Height;
    int newValSumHeight = 0;

    ExplicitPropertyMemento.Create
        .Memorize(_valSum, () =&gt; _valSum.AutoSize, () =&gt; _valSum.Anchor)
        .Memorize(_detailContent, () =&gt; _detailContent.Anchor)
        .Invoke(() =&gt;
            {
                _valSum.AutoSize = true;
                _valSum.Anchor = AnchorStyles.Top | AnchorStyles.Left;
                _detailContent.Anchor = AnchorStyles.Top | AnchorStyles.Left;

                _valSum.SetValidationMessages(validationMessages);

                newValSumHeight = _valSum.Height;
                Height = Height - oldValSumHeight + newValSumHeight;
            })
        .RestoreValues();

    _valSum.Height = newValSumHeight;
}</pre>
<h3>Conclusion</h3>
<p>Instead of the <code>using</code> syntax this article has shown an Explicit Property Memento implementation, which makes the whole Property Memento process explicit by defining methods for each step of the process. I still like the <code>using</code> syntax because it&#8217;s very dense, but in terms of <em>intention revealing</em> I also like the <code>ExplicitPropertyMemento</code>. What&#8217;s your opinion? At least feel free to choose the implementation you prefer <img src='http://www.minddriven.de/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d1042"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d1042" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.minddriven.de/index.php/technology/development/design-patterns/explicit-property-memento/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Follow-up: Property Memento pattern</title>
		<link>http://www.minddriven.de/index.php/technology/development/design-patterns/property-memento-followup</link>
		<comments>http://www.minddriven.de/index.php/technology/development/design-patterns/property-memento-followup#comments</comments>
		<pubDate>Sun, 05 Sep 2010 09:11:13 +0000</pubDate>
		<dc:creator>Matthias Jauernig</dc:creator>
				<category><![CDATA[Design patterns]]></category>
		<category><![CDATA[design pattern]]></category>
		<category><![CDATA[memento]]></category>
		<category><![CDATA[property]]></category>
		<category><![CDATA[property memento]]></category>

		<guid isPermaLink="false">http://www.minddriven.de/?p=1037</guid>
		<description><![CDATA[In a previous blog post I introduced the Property Memento pattern as way to temporarily save the value of an entity&#8217;s properties and restoring the initial values when the memento disposes. While I like the pattern itself I think the syntax can be done better. Here comes an implementation that uses just one type parameter [...]]]></description>
			<content:encoded><![CDATA[<p>In a <a href="http://www.minddriven.de/index.php/technology/development/design-patterns/property-memento-pattern">previous blog post</a> I introduced the <strong>Property Memento pattern</strong> as way to temporarily save the value of an entity&#8217;s properties and restoring the initial values when the memento disposes.</p>
<p>While I like the pattern itself I think the syntax can be done better. Here comes an implementation that uses just one type parameter for the property type and misses the reflection helper. The <code>static class PropertyMemento</code> helps to generate <code>PropertyMemento&lt;T&gt;</code> instances without specifying the type parameter (it&#8217;s inferred by the compiler):</p>
<pre class="brush:csharp">public class PropertyMemento&lt;TProperty&gt; : IDisposable
{
    private readonly TProperty _originalPropertyValue;
    private readonly object _classInstance;
    private readonly string _propertyName;

    public PropertyMemento(object classInstance,
        Expression&lt;Func&lt;TProperty&gt;&gt; propertySelector)
    {
        _classInstance = classInstance;
        _propertyName = ((MemberExpression)propertySelector.Body).Member.Name;
        _originalPropertyValue = GetPropertyValue();
    }

    public PropertyMemento(object classInstance,
        Expression&lt;Func&lt;TProperty&gt;&gt; propertySelector, TProperty tempValue)
        : this(classInstance, propertySelector)
    {
        SetPropertyValue(tempValue);
    }

    public void Dispose()
    {
        SetPropertyValue(_originalPropertyValue);
    }

    private TProperty GetPropertyValue()
    {
        return (TProperty)_classInstance
            .GetType()
            .GetProperty(_propertyName)
            .GetValue(_classInstance, null);
    }

    private void SetPropertyValue(TProperty value)
    {
        _classInstance
            .GetType()
            .GetProperty(_propertyName)
            .SetValue(_classInstance, value, null);
    }
}

public static class Memento
{
    public static PropertyMemento&lt;TProperty&gt; From&lt;TProperty&gt;(object classInstance,
        Expression&lt;Func&lt;TProperty&gt;&gt; propertySelector)
    {
        return new PropertyMemento&lt;TProperty&gt;(classInstance, propertySelector);
    }

    public static PropertyMemento&lt;TProperty&gt; From&lt;TProperty&gt;(object classInstance,
        Expression&lt;Func&lt;TProperty&gt;&gt; propertySelector, TProperty tempValue)
    {
        return new PropertyMemento&lt;TProperty&gt;(classInstance, propertySelector, tempValue);
    }
}</pre>
<p>And now its usage in the same scenario shown in the original blog post:</p>
<pre class="brush:csharp">private void SomeMethod(...)
{
    int oldValSumHeight = _valSum.Height;
    int newValSumHeight = 0;

    AnchorStyles newAnchor = AnchorStyles.Top | AnchorStyles.Left;
    using (PropertyMemento.From(_valSum, () =&gt; _valSum.AutoSize, true))
    using (PropertyMemento.From(_valSum, () =&gt; _valSum.Anchor, newAnchor))
    using (PropertyMemento.From(_detailContent, () =&gt; _detailContent.Anchor, newAnchor))
    {
        _valSum.SetValidationMessages(validationMessages);

        newValSumHeight = _valSum.Height;
        Height = Height - oldValSumHeight + newValSumHeight;
    }

    _valSum.Height = newValSumHeight;
}</pre>
<p>As said before: just a little improvement to the original code which slightly improves the implementation and usage of the pattern&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.minddriven.de/index.php/technology/development/design-patterns/property-memento-followup/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple message-based Event Aggregator</title>
		<link>http://www.minddriven.de/index.php/technology/development/design-patterns/event-aggregator-implementation</link>
		<comments>http://www.minddriven.de/index.php/technology/development/design-patterns/event-aggregator-implementation#comments</comments>
		<pubDate>Sun, 29 Aug 2010 12:32:38 +0000</pubDate>
		<dc:creator>Matthias Jauernig</dc:creator>
				<category><![CDATA[Design patterns]]></category>
		<category><![CDATA[design pattern]]></category>
		<category><![CDATA[event aggregator]]></category>
		<category><![CDATA[event broker]]></category>
		<category><![CDATA[indirection]]></category>
		<category><![CDATA[message-based]]></category>

		<guid isPermaLink="false">http://www.minddriven.de/?p=1023</guid>
		<description><![CDATA[This blog post is more about implementation than in-depth description or background information. It&#8217;s covering an implementation of a simple Event Aggregator that I&#8217;ve developed and used in a non-trivial Silverlight project and which I found quite useful. A word of warning: It&#8217;s not fully fledged and not suited for all scenarios&#8230; and it&#8217;s not [...]]]></description>
			<content:encoded><![CDATA[<p>This blog post is more about implementation than in-depth description  or background information. It&#8217;s covering an implementation of a simple <strong>Event Aggregator</strong> that I&#8217;ve developed and used in a non-trivial  Silverlight project and which I found quite useful. A word of warning: It&#8217;s not fully fledged and not suited for all scenarios&#8230; and it&#8217;s not intended to be.</p>
<h3>(Little) background</h3>
<p><img class="alignright size-full wp-image-1032" style="margin-left: 10px;" title="Event broker linkage, Copyright: Matthias Jauernig" src="http://www.minddriven.de/wp-content/uploads/2010/08/IMG_4537.jpg" alt="Event broker linkage, Copyright: Matthias Jauernig" width="400" height="267" />The first time I&#8217;ve seen an implementation of the <strong>event  aggregator pattern</strong> was in the <a href="http://compositewpf.codeplex.com/">Prism</a> framework. I like the idea  behind this pattern. It&#8217;s decoupling event publishers and subscribers.  It&#8217;s representing a kind of <a href="http://www.eaipatterns.com/ramblings/03_hubandspoke.html"><strong>Hub</strong></a>. Each time a publisher publishs  an event it gets into the hub and then it&#8217;s redirected to the  subscribers. The publishers/subscribers don&#8217;t have to know each other,  they just have to know the concrete event aggregator which is a mediator and mediates  between both parties. Thus the event aggregator is realizing a useful <strong>indirection  mechanism</strong>.</p>
<p>The event aggregator can be used in many scenarios and situations.  I&#8217;ve mainly used it in <strong>UI-related scenarios</strong>, but it&#8217;s not limited  to that. In the UI situation it helped me out e.g. at <em>view  synchronization</em> and <em>indirect communication</em>: between multiple  user controls/views, views and view models (both directions) or views  and controllers. They don&#8217;t have to know each other and thus can be  loosely coupled.</p>
<p>While I came across with the Prism event aggregator at first, after some investigation I didn&#8217;t like the implementation very much in view of the usage from a client&#8217;s perspective. You first have to get an event from the event aggregator and then you can subscribe to this event or publish the event with some event arguments. This is kind of duplicated work. When I know the type of the event arguments why do I have to know the event anymore (under the assumption that there&#8217;s a 1:1 relationship between both)? <a href="http://neverindoubtnet.blogspot.com/2009/07/simplify-prism-event-aggregator.html">Others</a> <a href="http://thejoyofcode.com/A_Suck_Less_Event_Aggregator_for_Prism.aspx">came</a> <a href="http://codebetter.com/blogs/jeremy.miller/archive/2009/07/21/braindump-on-the-event-aggregator-pattern.aspx">across</a> with this issue as well. A better approach in my opinion is a <strong>solely message-based event aggregator</strong>. A system that doesn&#8217;t distinguish between events and event arguments, but is based on messages people can subscribe to and publish.</p>
<h3>Implementation</h3>
<p>Let&#8217;s come to the bits&#8217;n'bytes of my implementatoin. My message-based event aggregator should be able to handle messages of type <code>IMessage</code>. This is just an empty interface for type-correctness in the other components. Additionally it makes the message type explicit which I like because a message should be a very specific type of your application domain:</p>
<pre class="brush:csharp">public interface IMessage { }</pre>
<p>Another important component is the <code>ISubscription&lt;TMessage&gt;</code> interface and its default implementation <code>Subscription&lt;TMessage&gt;</code>. A subscription is something the event aggregator stores internally when an action should be subscribed to a message. This subscription process results in an <code>ISubscription&lt;TMessage&gt;</code> object, which is returned to the caller. The caller will be able to unsubscribe from the event aggregator with this subscription object &#8211; there&#8217;s no need to reference the subscribed action, which is handy e.g. in situations where you want to use anonymous methods (via delegates or lambdas). Furthermore when the subscription disposes it&#8217;s unsubscribed from the event aggregator, which I found quite useful:</p>
<pre class="brush:csharp">public interface ISubscription&lt;TMessage&gt; : IDisposable
    where TMessage : IMessage
{
    Action&lt;TMessage&gt; Action { get; }
    IEventAggregator EventAggregator { get; }
}

public class Subscription&lt;TMessage&gt; : ISubscription&lt;TMessage&gt;
    where TMessage : IMessage
{
    public Action&lt;TMessage&gt; Action { get; private set; }
    public IEventAggregator EventAggregator { get; private set; }

    public Subscription(IEventAggregator eventAggregator, Action&lt;TMessage&gt; action)
    {
        if(eventAggregator == null) throw new ArgumentNullException("eventAggregator");
        if(action == null) throw new ArgumentNullException("action");

        EventAggregator = eventAggregator;
        Action = action;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if(disposing)
            EventAggregator.UnSubscribe(this);
    }
}</pre>
<p>Note the reference to <code>EventAggregator</code> in the interface and its use in the implementation. This is necessary due to the disposing functionality. Of course if you don&#8217;t want this behavior in your scenario you can adapt the implementation.</p>
<p>At the end the <code>IEventAggregator</code> interface and its default implementation <code>EventAggregator</code> handle the whole message publish/subscribe mechanism. Clients can <code>Subscribe()</code> to specific types of messages with custom actions that are stored in an <code>ISubscription&lt;TMessage&gt;</code> object. Those clients can <code>UnSubscribe()</code> if they&#8217;re owning the <code>ISubscription&lt;TMessage&gt;</code> object. Other clients can <code>Publish()</code> concrete messages, which gets the subscribers of the message notified:</p>
<pre class="brush:csharp">public interface IEventAggregator
{
    void Publish&lt;TMessage&gt;(TMessage message)
        where TMessage : IMessage;

    ISubscription&lt;TMessage&gt; Subscribe&lt;TMessage&gt;(Action&lt;TMessage&gt; action)
        where TMessage : IMessage;

    void UnSubscribe&lt;TMessage&gt;(ISubscription&lt;TMessage&gt; subscription)
        where TMessage : IMessage;

    void ClearAllSubscriptions();
    void ClearAllSubscriptions(Type[] exceptMessages);
}

public class EventAggregator : IEventAggregator
{
    private readonly IDictionary&lt;Type, IList&gt; _subscriptions = new Dictionary&lt;Type, IList&gt;();

    public void Publish&lt;TMessage&gt;(TMessage message)
        where TMessage : IMessage
    {
        if(message == null) throw new ArgumentNullException("message");

        Type messageType = typeof(TMessage);
        if(_subscriptions.ContainsKey(messageType))
        {
            var subscriptionList = new List&lt;ISubscription&lt;TMessage&gt;&gt;(
                _subscriptions[messageType].Cast&lt;ISubscription&lt;TMessage&gt;&gt;());
            foreach(var subscription in subscriptionList)
                subscription.Action(message);
        }
    }

    public ISubscription&lt;TMessage&gt; Subscribe&lt;TMessage&gt;(Action&lt;TMessage&gt; action)
        where TMessage : IMessage
    {
        Type messageType = typeof(TMessage);
        var subscription = new Subscription&lt;TMessage&gt;(this, action);

        if(_subscriptions.ContainsKey(messageType))
            _subscriptions[messageType].Add(subscription);
        else
            _subscriptions.Add(messageType, new List&lt;ISubscription&lt;TMessage&gt;&gt;{subscription});

        return subscription;
    }

    public void UnSubscribe&lt;TMessage&gt;(ISubscription&lt;TMessage&gt; subscription)
        where TMessage : IMessage
    {
        Type messageType = typeof(TMessage);
        if (_subscriptions.ContainsKey(messageType))
            _subscriptions[messageType].Remove(subscription);
    }

    public void ClearAllSubscriptions()
    {
        ClearAllSubscriptions(null);
    }

    public void ClearAllSubscriptions(Type[] exceptMessages)
    {
        foreach (var messageSubscriptions in new Dictionary&lt;Type, IList&gt;(_subscriptions))
        {
            bool canDelete = true;
            if (exceptMessages != null)
                canDelete = !exceptMessages.Contains(messageSubscriptions.Key);

            if (canDelete)
                _subscriptions.Remove(messageSubscriptions);
        }
    }
}</pre>
<h3>Usage</h3>
<p>The usage of this event aggregator implementation is simple and straight forward. Clients can subscribe to messages they&#8217;re interested in:</p>
<pre class="brush:csharp">// Option 1: Explicit action subscription
Action&lt;MyMessage&gt; someAction = message =&gt; { /*...*/ };
var subscription1 = eventAggregator.Subscribe(someAction);

// Option 2: Subscription via lambda
var subscription2 = eventAggregator.Subscribe&lt;MyMessage&gt;(message =&gt; { /*...*/ });</pre>
<p>The clients get an <code>ISubscription&lt;TMessage&gt;</code> in return, from which they&#8217;re able to unsubscribe:</p>
<pre class="brush:csharp">// Option 1: Unsubscribe by calling the event aggregator method
eventAggregator.UnSubscribe(subscription);

// Option 2: Unsubscribe by calling Dispose() on the subscription object
subscription.Dispose();</pre>
<p>Other clients now are able to publish concrete messages and subscribers get informed about those messages:</p>
<pre class="brush:csharp">eventAggregator.Publish(new MyMessage{ /*...*/ });</pre>
<p>How to get an instance of <code>IEventAggregator</code>, you may ask? Well, that&#8217;s your decision! Implement a singleton for accessing an instance, use your favorite DI container, whatever&#8230;</p>
<h3>Conclusion</h3>
<p>That&#8217;s it. A simple message-based event aggregator implementation that can be used in a variety of situations. And which can be replaced by other  implementations as well. Perhaps you want to persist or log messages, enable detached subscribers, allow async event processing or even further functionality like load balancing&#8230; It&#8217;s up to you to provide your own implementation. And feel free to connect the <a href="http://www.minddriven.de/index.php/technology/development/design-patterns/latch-design-pattern">Latch Pattern</a> <img src='http://www.minddriven.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>While the presented <code>EventAggregator</code> perfectly fitted <em>my</em> needs, it&#8217;s not intended to be universally applicable. For example I know that Prism uses <code>WeakReference</code>s to simplify garbage collection. I say it again: feel free to do that in your own implementation. Besides there are many more <em>syntactic</em> ways to implement event aggregators/brokers. Paste your comments if you have further suggestions &#8211; you&#8217;re welcome!</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d1023"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d1023" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.minddriven.de/index.php/technology/development/design-patterns/event-aggregator-implementation/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>The Property Memento pattern</title>
		<link>http://www.minddriven.de/index.php/technology/development/design-patterns/property-memento-pattern</link>
		<comments>http://www.minddriven.de/index.php/technology/development/design-patterns/property-memento-pattern#comments</comments>
		<pubDate>Wed, 11 Aug 2010 09:22:30 +0000</pubDate>
		<dc:creator>Matthias Jauernig</dc:creator>
				<category><![CDATA[Design patterns]]></category>
		<category><![CDATA[design pattern]]></category>
		<category><![CDATA[memento]]></category>
		<category><![CDATA[property]]></category>
		<category><![CDATA[property memento]]></category>
		<category><![CDATA[restore value]]></category>
		<category><![CDATA[state]]></category>

		<guid isPermaLink="false">http://www.minddriven.de/?p=975</guid>
		<description><![CDATA[Edit: Find an improved implementation of the pattern here. Edit: Find an explicit implementation of the pattern here. This blog post shows the Property Memento as pattern for storing property values and later restoring from those. Constructive feedback is welcome everytime! Problem description It&#8217;s a common task in several scenarios: you want to store the [...]]]></description>
			<content:encoded><![CDATA[<p><em><strong>Edit</strong>: Find an improved implementation of the pattern <a href="http://www.minddriven.de/index.php/technology/development/design-patterns/property-memento-followup">here</a>.</em><em><strong><br />
Edit</strong>: Find an explicit implementation of the pattern <a href="http://www.minddriven.de/index.php/technology/development/design-patterns/explicit-property-memento">here</a>.</em></p>
<p>This blog post shows the Property Memento as pattern for storing property values and later restoring from those. Constructive feedback is welcome everytime!</p>
<h3>Problem description</h3>
<p>It&#8217;s a common task in several scenarios: you want to store the value of an object&#8217;s property, then temporarily change it to perform some actions and at the end restore the original property value again. Especially with UI-related task you come into this situation quite often.</p>
<p>The last time I came across with this requirement is only some days/weeks ago and was a UI task as well. I created a generic detail view in WinForms, which was built up by Reflection from an object&#8217;s properties and optional metadata information. This form contained a control for the object&#8217;s values on the one side and a validation summary control for showing validation messages on the other side. The validation summary had to change its content and layout dynamically while performing validation.</p>
<p>Through the dynamic nature of the form unfortunately I couldn&#8217;t use the <code>AutoSize</code> feature and thus had to layout the control manually (calculating and setting control sizes etc.). But I <em>still</em> wanted to use some <code>AutoSize</code> functionality, at least for the validation summary. And here&#8217;s the deal: everytime the validation messages on the summary change, the control should <code>AutoSize</code> to fit its content. With the new size I recalculate the Height of the whole form. This task can be done by manually setting the <code>AutoSize</code> property temporarily. Additionally it&#8217;s necessary to temporarily set the <code>Anchor</code> property of the details control and the validation summary to complete the layouting process correctly.</p>
<p>Normally in the past I would have used a manual approach like this:</p>
<pre class="brush:csharp">private void SomeMethod(...)
{
    int oldValSumHeight = _valSum.Height;
    int newValSumHeight = 0;

    bool oldValSumAutoSize = _valSum.AutoSize;
    AnchorStyles oldValSumAnchor = _valSum.Anchor;
    AnchorStyles oldDetailAnchor = _detailContent.Anchor;

    _valSum.AutoSize = true;
    _valSum.Anchor = AnchorStyles.Left | AnchorStyles.Top;
    _detailContent.Anchor = AnchorStyles.Left | AnchorStyles.Top;

    _valSum.SetValidationMessages(validationMessages);

    newValSumHeight = _valSum.Height;
    Height = Height - oldValSumHeight + newValSumHeight;

    _valSum.AutoSize = oldValSumAutoSize;
    _valSum.Anchor = oldValSumAnchor;
    _detailContent.Anchor = oldDetailAnchor;

    _valSum.Height = newValSumHeight;
}</pre>
<p>What a <strong>verbose and dirty code</strong> for such a simple task! Saving the old property values, setting  the new values, performing some action and restoring the original property values&#8230; It&#8217;s even hard to find out the <strong>core logic</strong> of the method. Oh dear! While this solution works, it has a really <strong>poor readability</strong>. Moreover it&#8217;s not dealing with <strong>exceptions</strong> that could occur when actions are performed in between. Thus the UI could be left in an inconsistently layouted state and presented to the user in this way. What a mess! But what&#8217;s the alternative?</p>
<h3>The  Property Memento</h3>
<p>Better solution? What do you think about that (<em>edit: find a better implementation <a href="../index.php/technology/development/design-patterns/property-memento-followup">here</a></em>):</p>
<pre class="brush:csharp">private void SomeMethod(...)
{
    int oldValSumHeight = _valSum.Height;
    int newValSumHeight = 0;

    using (GetAutoSizeMemento(_valSum, true))
    using (GetAnchorMemento(_valSum, AnchorStyles.Top|AnchorStyles.Left))
    using (GetAnchorMemento(_detailContent, AnchorStyles.Top|AnchorStyles.Left))
    {
        _valSum.SetValidationMessages(validationMessages);

        newValSumHeight = _valSum.Height;
        Height = Height - oldValSumHeight + newValSumHeight;
    }

    _valSum.Height = newValSumHeight;
}

private PropertyMemento&lt;Control, bool&gt; GetAutoSizeMemento(
    Control control, bool tempValue)
{
    return new PropertyMemento&lt;Control, bool&gt;(
        control, () =&gt; control.AutoSize, tempValue);
}

private PropertyMemento&lt;Control, AnchorStyles&gt; GetAnchorMemento(
    Control control, AnchorStyles tempValue)
{
    return new PropertyMemento&lt;Control, AnchorStyles&gt;(
        control, () =&gt; control.Anchor, tempValue);
}</pre>
<p>Notice that the logic of <code>SomeMethod()</code> is <strong>exactly the same</strong> as in the first code snippet. But now the responsibility of storing and restoring property values is encapsulated in Memento objects which are utilized inside a <code>using(){ }</code> statement. <code>GetAutoSizeMemento()</code> and <code>GetAnchorMemento()</code> are just two simple helper methods to create the Memento objects, which support readability in this blog post, but nothing more&#8230;</p>
<p>So how is the Property Memento working <strong>conceptually</strong>? On creation of the Property Memento it stores the original value of an object&#8217;s property. Optionally it&#8217;s possible to set a new temporary value for this property as well. During the lifetime of the Property Memento the value of the property can be changed by a developer. Finally when <code>Dispose()</code> is called on the Property Memento, the initial property value is restored. Thus the Property Memento clearly encapsulates the task of storing and restoring property values.</p>
<p>The <strong>technical implementation</strong> of the Property Memento in C# uses Reflection and is shown below (<em>edit: find a better implementation <a href="http://www.minddriven.de/index.php/technology/development/design-patterns/property-memento-followup">here</a></em>):</p>
<pre class="brush:csharp">public class PropertyMemento&lt;TClass, TProperty&gt; : IDisposable
    where TClass : class
{
    private readonly TProperty _originalPropertyValue;
    private readonly TClass _classInstance;
    private readonly Expression&lt;Func&lt;TProperty&gt;&gt; _propertySelector;

    public PropertyMemento(TClass classInstance,
        Expression&lt;Func&lt;TProperty&gt;&gt; propertySelector)
    {
        _classInstance = classInstance;
        _propertySelector = propertySelector;
        _originalPropertyValue =
            ReflectionHelper.GetPropertyValue(classInstance, propertySelector);
    }

    public PropertyMemento(TClass memberObject,
        Expression&lt;Func&lt;TProperty&gt;&gt; memberSelector, TProperty tempValue)
        : this(memberObject, memberSelector)
    {
        SetPropertyValue(tempValue);
    }

    public void Dispose()
    {
        SetPropertyValue(_originalPropertyValue);
    }

    private void SetPropertyValue(TProperty value)
    {
        ReflectionHelper.SetPropertyValue(
            _classInstance, _propertySelector, value);
    }
}</pre>
<p>This implementation uses the following <code>ReflectionHelper</code> class:</p>
<pre class="brush:csharp">static class ReflectionHelper
{
    public static PropertyInfo GetProperty&lt;TEntity, TProperty&gt;(
        Expression&lt;Func&lt;TProperty&gt;&gt; propertySelector)
    {
        return GetProperty&lt;TEntity&gt;(GetPropertyName(propertySelector));
    }

    public static PropertyInfo GetProperty&lt;T&gt;(string propertyName)
    {
        var propertyInfos = typeof(T).GetProperties();
        return propertyInfos.First(pi =&gt; pi.Name == propertyName);
    }

    public static string GetPropertyName&lt;T&gt;(
        Expression&lt;Func&lt;T&gt;&gt; propertySelector)
    {
        var memberExpression = propertySelector.Body as MemberExpression;
        return memberExpression.Member.Name;
    }

    public static TProperty GetPropertyValue&lt;TEntity, TProperty&gt;(
        TEntity entity, Expression&lt;Func&lt;TProperty&gt;&gt; propertySelector)
    {
        return (TProperty)GetProperty&lt;TEntity, TProperty&gt;(propertySelector)
            .GetValue(entity, null);
    }

    public static void SetPropertyValue&lt;TEntity, TProperty&gt;(TEntity entity,
        Expression&lt;Func&lt;TProperty&gt;&gt; propertySelector, TProperty value)
    {
        GetProperty&lt;TEntity, TProperty&gt;(propertySelector)
            .SetValue(entity, value, null);
    }
}</pre>
<p>As you can see, the Property Memento implementation is no rocket science. The constructor gets the class instance and an <code>Expression</code> which selects the property from this instance. Optionally you can provide a property value that should be set temporarily in place of the original value. Getting and setting the property value is done via the <code>ReflectionHelper</code> class. For the sake of shortness the implementation doesn&#8217;t have a good error handling mechanism. You could employ your own checks if you want. What I like is the use of generics. This eliminates many error sources and guides a developer with the usage of the Property Memento.</p>
<h3>Really a pattern and a Memento?</h3>
<p>I&#8217;ve used the Property Memento now in several different situations with success and thus I think it&#8217;s justified to call it a <em>pattern</em>.</p>
<p>But is it a <em>Memento</em> as well? Wikipedia says about the <a href="http://en.wikipedia.org/wiki/Memento_pattern" target="_blank">Memento pattern</a>:</p>
<blockquote><p>&#8220;The <strong>memento pattern</strong> is a <a title="Design pattern (computer science)" href="http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29">software design pattern</a> that provides the ability to restore an object to its previous state [...]&#8220;</p></blockquote>
<p>And this is true for the Property Memento, where the &#8220;object&#8221; equals a property value on a class instance! The &#8220;previous state&#8221; is stored on creation of the Memento and &#8220;restore an object&#8221; is done on call of <code>Dispose()</code>.</p>
<h3>Finally</h3>
<p>This blog post has shown the Property Memento as pattern for storing original property values and later on restoring them.</p>
<p>Compared to the &#8220;manual way&#8221; the Property Memento has valuable advantages. It <strong>encapsulates the responsibility</strong> of storing an original value and restoring it when the <code>using()</code> block is finished. Client code remains clean and is condensed to the <strong>core logic</strong>, while delegating responsibilities to the Property Memento by an explicit <code>using(){ }</code> block. Thus the code becomes much more concise and <strong>readable</strong>. Last but not least the Property Memento employs an automatic <strong>exception handling</strong> mechanism. If an exception occurs inside a <code>using()</code> block of the Property Memento, finally the <code>Dispose()</code> method is called. Thus the Property Memento restores the original property state even in exceptional situations and the user gets a consistent layouted UI.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d975"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d975" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.minddriven.de/index.php/technology/development/design-patterns/property-memento-pattern/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Latch me if you can!</title>
		<link>http://www.minddriven.de/index.php/technology/development/design-patterns/latch-design-pattern</link>
		<comments>http://www.minddriven.de/index.php/technology/development/design-patterns/latch-design-pattern#comments</comments>
		<pubDate>Wed, 04 Aug 2010 07:22:38 +0000</pubDate>
		<dc:creator>Matthias Jauernig</dc:creator>
				<category><![CDATA[Design patterns]]></category>
		<category><![CDATA[design pattern]]></category>
		<category><![CDATA[Latch]]></category>

		<guid isPermaLink="false">http://www.minddriven.de/?p=968</guid>
		<description><![CDATA[In my first blog post I&#8217;ve shown a common UI problem when it comes to event handling and programmatic vs. user-triggered events on the one handside and to infinite loops due to recursive event chains on the other. With event detach/attach and boolean flags I&#8217;ve shown two simple solutions which are very common in many [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://www.minddriven.de/index.php/technology/development/design-patterns/common-ui-problem">first blog post</a> I&#8217;ve shown  a <strong>common UI problem</strong> when it comes to event handling and programmatic  vs. user-triggered events on the one handside and to infinite loops due to recursive event chains on the other. With event detach/attach  and boolean flags I&#8217;ve shown two simple solutions which are very common  in many development projects. But they have their shortcomings and just don&#8217;t feel <em>natural</em>. This blog post shows an alternative which I found  simple and beautiful.</p>
<h3>Latch to the rescue</h3>
<p>Jeremy Miller introduced the <a href="http://codebetter.com/blogs/jeremy.miller/archive/2007/07/02/build-your-own-cab-12-rein-in-runaway-events-with-the-quot-latch-quot.aspx">Latch design pattern</a> as possible solution for the  problem at hand. It&#8217;s a tiny beautiful, yet little know solution and  the latter is a pitty. A <strong>Latch</strong> encapsulates the logic of executing an  action depending on the current state of the Latch. If the Latch is in  &#8220;Latched&#8221; state, no action is executed. And actions can be executed inside  of the Latch (changing the state to &#8220;Latched&#8221;), preventing other actions  from executing.</p>
<h3>Latch #1: Disposing Latch</h3>
<p>Before reading Jeremy&#8217;s post, I&#8217;ve made a sort of Latch pattern for myself. Here the Latch implements <code>IDisposable</code>, and the Latched state is set on creation of the Latch and  reset at a call of <code>Dispose()</code>. This allows the application of the <code>using() { }</code> syntax and the Latch state is reset automatically when exceptions  occur. The <code>Latch</code> class would look like this:</p>
<pre class="brush:csharp">public class Latch : IDisposable
{
    public bool IsLatched { get; private set; }

    public Latch()
    {
        IsLatched = true;
    }

    public void RunIfNotLatched(Action action)
    {
        if (IsLatched)
            return;

        action();
    }

    public void Dispose()
    {
        IsLatched = false;
    }

    public static Latch Latched
    {
        get { return new Latch(); }
    }
    public static Latch UnLatched
    {
        get { return new Latch { IsLatched = false }; }
    }
}</pre>
<p>The  <code>RunIfNotLatched()</code> method is just a little helper which executes an action given on the current state of the Latch. The actual application of the Latch in the example code from the <a href="http://www.minddriven.de/index.php/technology/development/design-patterns/common-ui-problem">previous post</a> is shown here:</p>
<pre class="brush:csharp">public partial class SomeControl : UserControl
{
    // ...

    private Latch _textSetByCodeLatch = Latch.UnLatched;

    private ViewData _viewData;
    public ViewData ViewData
    {
        get { return _viewData; }
        set
        {
            _viewData = value;
            if (value != null)
            {
                using (_textSetByCodeLatch = new Latch())
                {
                    _someTextBox.Text = value.SomeValue;
                }
                // other operations
            }
        }
    }

    private void OnSomeTextBoxTextChanged(object sender, EventArgs e)
    {
        _textSetByCodeLatch.RunIfNotLatched(() =&gt;
        {
            // perform data/view update operations
        });
    }
}</pre>
<p>At first sight I liked the <code>using() { }</code> syntax. It frees the application code from manually reseting the Latch to UnLatched state. At  second sight I think there could be a cleaner solution. In my Latch  implementation the <code>using() { }</code> syntax is kind of <em>misused</em> and could lead  to irritations because there is implicit knowledge about the internal  functionality of the Latch. Again, the intent is not <em>explicitly</em> revealed.</p>
<h3>Latch #2: Boolean Latch</h3>
<p>A cleaner solution with explicit methods for running actions inside  of the Latch and missing action execution when other actions have  entered the Latch could be the following Latch implementation:</p>
<pre class="brush:csharp">public class Latch
{
    public bool IsLatched { get; private set; }

    public void RunLatched(Action action)
    {
        try
        {
            IsLatched = true;
            action();
        }
        finally
        {
            IsLatched = false;
        }
    }

    public void RunIfNotLatched(Action action)
    {
        if (IsLatched)
            return;

        action();
    }
}</pre>
<p>Here the basic boolean logic behind matches with  the Disposing Latch, but the syntax has changed. The Latch now contains  two methods. <code>RunLatched()</code> executes an action inside the Latch and  prevents actions from being executed in <code>RunIfNotLatched()</code>. Here&#8217;s the usage for this Latch type in our example:</p>
<pre class="brush:csharp">public partial class SomeControl : UserControl
{
    // ...

    private readonly Latch _textSetByCodeLatch = new Latch();

    private ViewData _viewData;
    public ViewData ViewData
    {
        get { return _viewData; }
        set
        {
            _viewData = value;
            if (value != null)
            {
                _textSetByCodeLatch.RunLatched(() =&gt;
                {
                    _someTextBox.Text = value.SomeValue;
                });
                // other operations
            }
        }
    }

    private void OnSomeTextBoxTextChanged(object sender, EventArgs e)
    {
        _textSetByCodeLatch.RunIfNotLatched(() =&gt;
        {
            // perform data/view update operations
        });
    }
}</pre>
<p>Now  the Latch has a cleaner and more explicit syntax. And like the Disposing  Latch it has a clean exception handling mechanism. That&#8217;s the good  news. With that our Boolean Latch is applicable in most simple  scenarios. But not in all! Imagine <em>parallel execution</em> of UI actions.  Moreover imagine having two actions which should be run in <code>RunLatched()</code> of the same Latch object &#8211; again in parallel:</p>
<ol>
<li>Action 1 enters <code>RunLatched()</code> and the Latch changes its state.</li>
<li>Action 2 enters <code>RunLatched()</code>, the Latch state remains in  <code>IsLatched</code>.</li>
<li>Action 1 leaves <code>RunLatched()</code> and the Latch changes its state to  not latched.</li>
</ol>
<p>Step 3 is the problem. Action 2 is still running inside the Latch,  but due to the boolean logic the Latch is not latched any longer. Thus  other actions are executed when given to <code>RunIfNotLatched()</code>, which is no  help on the initial problem. This is not only true for the Boolean  Latch, but for the Disposing Latch as well.</p>
<h3>Latch #3: Counting Latch</h3>
<p>This problem is solved by the Counting Latch, which is most similar  to Jeremy&#8217;s Latch implementation. Instead of having just a boolean  discriminator, it employs a counter for parallel <code>RunLatched()</code> calls. The  <code>IsLatched</code> state is determined based on this counter. If it&#8217;s equal to <code>0</code>, the Latch is not latched (because no method is currently running  inside of <code>RunLatched()</code>). Else the Latch is treat as latched. Here&#8217;s the  implementation of this Latch variant (edit: thanks nwiersma for the thread-safe <a href="http://www.minddriven.de/index.php/technology/development/design-patterns/latch-design-pattern#comment-6208">hint</a>):</p>
<pre class="brush:csharp">public class Latch
{
    private readonly object _counterLock = new object();

    public int LatchCounter { get; private set; }

    public bool IsLatched
    {
        get { return (LatchCounter &gt; 0); }
    }

    public void RunLatched(Action action)
    {
        try
        {
            lock(_counterLock) { LatchCounter++; }
            action();
        }
        finally
        {
            lock(_counterLock) { LatchCounter--; }
        }
    }

    public void RunIfNotLatched(Action action)
    {
        if (IsLatched)
            return;

        action();
    }
}</pre>
<p>The  usage in this case is equivalent to the Boolean Latch. You should note that <em>each</em> of these Latch implementations works, it&#8217;s just a matter  of your requirements which of them you want to use. The Counting Latch as  most generic Latch implementation above and applies to most situations.</p>
<h3>Benefits of using the Latch</h3>
<p>Using the Latch for the foresaid problems has clear advantages over the  use of event detach/attach and boolean flags. First the Latch  <em>encapsulates the logic</em> of running actions depending on a state, in this  case the current execution of another action. Thus the purpose of a  Latch is <em>explicit</em>, in contrast to the implicit intent of e.g. boolean  flags. This <em>increases code readability</em>.</p>
<p>The second advantage  comes with <em>resetting the initial state</em>. The Latch performs this task  itself when an action leaves the <code>RunLatched()</code> method for example. With  boolean flags and event detach/attach this is your task. It&#8217;s most likely getting problematic if exceptions are thrown  inside an action. The Latch takes over the responsibility of automatically rolling back the state of the Latch on occurrence of an exception.</p>
<p>In <strong>conclusion</strong> the Latch is a pretty simple design pattern which increases readability  and <em>feels right</em> for the problem of dependent action execution. For  myself, at least I&#8217;ve found some nice solution for UI event reaction  depending on the source of the trigger of the event and for infinite event loops, without relying on  ugly boolean flags or event attach/detach.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d968"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d968" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.minddriven.de/index.php/technology/development/design-patterns/latch-design-pattern/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>A common UI problem</title>
		<link>http://www.minddriven.de/index.php/technology/development/design-patterns/common-ui-problem</link>
		<comments>http://www.minddriven.de/index.php/technology/development/design-patterns/common-ui-problem#comments</comments>
		<pubDate>Tue, 03 Aug 2010 12:50:43 +0000</pubDate>
		<dc:creator>Matthias Jauernig</dc:creator>
				<category><![CDATA[Design patterns]]></category>
		<category><![CDATA[boolean flags]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[UI problem]]></category>

		<guid isPermaLink="false">http://www.minddriven.de/?p=963</guid>
		<description><![CDATA[This blog post is all about a common UI-related programming problem. Ever since my first UI-based application I&#8217;ve come across with this problem and never found a satisfying way to resolve it (until now ). This first blog post is about describing the problem and my former solution approaches. In the next blog post I [...]]]></description>
			<content:encoded><![CDATA[<p>This blog post is all about a common UI-related programming problem.  Ever since my first UI-based application I&#8217;ve come across with this  problem and never found a satisfying way to resolve it (until now <img src='http://www.minddriven.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  ). This first blog post is about describing the problem and my former solution approaches. In <a href="http://www.minddriven.de/index.php/technology/development/design-patterns/latch-design-pattern">the next blog post</a> I will demonstrate a more proper solution.</p>
<p>The code in these two blog posts is using WinForms  and C#, but it should be easy adoptable to other UI technologies as  well.</p>
<h3>Problem description</h3>
<p>It&#8217;s a common problem: you  want to react on an event like the <code>TextChanged</code> event on a <code>TextBox</code>, but <strong> <em>ONLY</em> if the user changed</strong> the text and it&#8217;s not changed programmatically. For example you want to update some data, when the user changes the content of a <code>TextBox</code>, but this update process should not be triggered when the progam itself sets some data and therefore updates the text. The  starting point for that could be something like the following code:</p>
<pre class="brush:csharp">public partial class SomeControl : UserControl
{
    // ...

    private ViewData _viewData;
    public ViewData ViewData
    {
        get { return _viewData; }
        set
        {
            _viewData = value;
            if (value != null)
            {
                _someTextBox.Text = value.SomeValue;
                // other operations
            }
        }
    }

    private void OnSomeTextBoxTextChanged(object sender, EventArgs e)
    {
        // perform data/view update operations
    }
}</pre>
<p>Here the <code>OnSomeTextBoxTextChanged()</code> method is bound to the <code>_someTextBox.TextChanged</code> event. <code>ViewData</code> is a class with arbitrary data that should show up in the UI.<br />
<strong>Notice the problem</strong>: when the <code>ViewData</code> property is set programmatically the <code>OnSomeTextBoxTextChanged()</code> method is being executed, which is not what was intended (firing the event only when the user changes the value of the <code>TextBox</code>).</p>
<p>A similar problem arises with <strong>infinite loops</strong>. Imagine a user changes something in the UI and an event <code>X</code> is fired. You hook this event and start a complex UI workflow, which at the end fires the event <code>X</code> again. The proces is executed again and very easy you come into an infinite loop situation. If you are an UI developer you would very probably agree that UI event chains are often opaque and can get messy.</p>
<p>Let&#8217;s look at some obvious, however not very elegant, solutions.</p>
<h3>Approach #1: Temporary event detach</h3>
<p>One of those simple solution is the <strong>temporary detachment</strong> of the problematic event. For example if you don&#8217;t want to react on the <code>TextChanged</code> event when the <code>TextBox.Text</code> property is set programmatically, you could detach your event handler from <code>TextChanged</code> before setting the <code>Text</code> and afterwards attach it again. This approach is shown in the following  example code:</p>
<pre class="brush:csharp">public partial class SomeControl : UserControl
{
    // ...

    private ViewData _viewData;
    public ViewData ViewData
    {
        get { return _viewData; }
        set
        {
            _viewData = value;
            if (value != null)
            {
                _someTextBox.TextChanged -= OnSomeTextBoxTextChanged;
                _someTextBox.Text = value.SomeValue;
                _someTextBox.TextChanged += OnSomeTextBoxTextChanged;

                // other operations
            }
        }
    }

    private void OnSomeTextBoxTextChanged(object sender, EventArgs e)
    {
        // perform data/view update operations
    }
}</pre>
<p>While this is working, it&#8217;s not a recommendable solution, because there are <strong>several shortcomings</strong>. First the manual event handling is not very intuitive and <em>doesn&#8217;t explicitly reveal the intent</em> of the programmer with this manual process. Thus your code is more difficult to read for others (and after some months for you as well). Moreover, you get <em>undefined states</em> when exceptions are thrown and caught in an outer component (and you miss a <code>finally</code> which attaches the event again). Then the event handler could be detached further on and the UI isn&#8217;t working properly afterwards. The whole event detach/attach process is getting very messy if you have <em>complex views</em> with many such problematic events. Last but not least this manual event handling process <em>binds your code tightly</em> to the view and you get trouble if you want to refactor several parts out.</p>
<h3>Approach #2: Boolean flags</h3>
<p>A similarly simple approach comes with <em>boolean flags</em> which indicate that a value is currently set  programmatically and thus that <em>Changed</em> events should not be handled. The following code shows an example how this could solve our initial problem:</p>
<pre class="brush:csharp">public partial class SomeControl : UserControl
{
    // ...

    private bool _isTextSetByProgram = false;

    private ViewData _viewData;
    public ViewData ViewData
    {
        get { return _viewData; }
        set
        {
            _viewData = value;
            if (value != null)
            {
                _isTextSetByProgram = true;
                _someTextBox.Text = value.SomeValue;
                _isTextSetByProgram = false;

                // other operations
            }
        }
    }

    private void OnSomeTextBoxTextChanged(object sender, EventArgs e)
    {
        if (!_isTextSetByProgram)
        {
            // perform data/view update operations
        }
    }
}</pre>
<p>I think this is the <strong>most common solution</strong> that I&#8217;ve seen for the problem. For myself I must admit that I&#8217;ve mostly used this approach. But it has the <strong>same disadvantages</strong> like the event detach/attach solution (except the tight view coupling). Boolean variables don&#8217;t explicitly show the intent behind them and get likewise messy if used in complex situations where you could have dozens of those variables scattered around a view.</p>
<p>So while those solutions are very widespread and work they <strong>just don&#8217;t feel <em>right</em> and clean</strong>. But what&#8217;s the alternative? An interesting little one I will show you in <a href="http://www.minddriven.de/index.php/technology/development/design-patterns/latch-design-pattern">the next post</a> which comes shortly.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d963"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d963" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.minddriven.de/index.php/technology/development/design-patterns/common-ui-problem/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Reactive Framework (Rx) &#8211; first look</title>
		<link>http://www.minddriven.de/index.php/technology/dot-net/reactive-framework-rx-first-look</link>
		<comments>http://www.minddriven.de/index.php/technology/dot-net/reactive-framework-rx-first-look#comments</comments>
		<pubDate>Thu, 15 Oct 2009 12:41:20 +0000</pubDate>
		<dc:creator>Matthias Jauernig</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Design patterns]]></category>
		<category><![CDATA[asynchronous]]></category>
		<category><![CDATA[dualism]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[Iterator]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[LINQ to Events]]></category>
		<category><![CDATA[Observer]]></category>
		<category><![CDATA[pull]]></category>
		<category><![CDATA[push]]></category>
		<category><![CDATA[Reactive Framework]]></category>
		<category><![CDATA[reactive programming]]></category>
		<category><![CDATA[Rx]]></category>

		<guid isPermaLink="false">http://www.leading-edge-dev.de/?p=501</guid>
		<description><![CDATA[During the last weeks I took some time to have a first look at the Reactive Framework. Here I want to share some impressions and information with you. Rx: What is it about? The Reactive Framework (Rx) has been developed at the Microsoft Live Labs and is another creation by Erik Meijer, the father of LINQ. [...]]]></description>
			<content:encoded><![CDATA[<p>During the last weeks I took some time to have a first look at the Reactive Framework. Here I want to share some impressions and information with you.</p>
<h3>Rx: What is it about?</h3>
<p>The <strong>Reactive Framework (Rx)</strong> has been developed at the Microsoft <a href="http://livelabs.com/">Live Labs</a> and is another creation by <a href="http://research.microsoft.com/en-us/um/people/emeijer/">Erik Meijer</a>, the father of <a href="http://en.wikipedia.org/wiki/LINQ">LINQ</a>. Rx will be part of the upcoming <strong>.NET Framework 4.0</strong>, but is already included as preview DLL (<code>System.Reactive.dll</code>) in the sources of the current <a href="http://www.codeplex.com/Silverlight">Silverlight 3 Toolkit</a>. It&#8217;s used there to get some smoother Unit Tests to work.</p>
<p>The aim of Rx is to simplify/unify complex event-based and asynchronous programming by providing a new programming model for those scenarios. That&#8217;s very important in a world which becomes more and more async (Web, AJAX, Silverlight, Azure/Cloud, concurrency, many-core, &#8230;) and where present approaches (event-based programming with .NET events, Begin/Invoke) hit the wall. Program logic gets hidden in a sea of callback methods which leads to nasty <em><a href="http://en.wikipedia.org/wiki/Spaghetti_code">spaghetti code</a></em>. Those of you who are creating larger async programs know what I mean <img src='http://www.minddriven.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<h3>Basic ideas</h3>
<p>The main concept of Rx is <a href="http://en.wikipedia.org/wiki/Reactive_programming"><strong>reactive programming</strong></a> and that&#8217;s not new at all. It involves a distinction of data processing methods into <em>push</em> and <em>pull</em> scenarios:</p>
<ul>
<li>In a <strong><em>pull</em>-scenario</strong> your code/program is <em>interactively</em> asking for new data from the environment. In this case the actor is your program while it pulls new data from the environment.</li>
<li>In a <strong><em>push</em>-scenario</strong> your program is <em>reactive</em>. The environment in pushing data into your program which has to react on every new incoming data item (see illustration below). Reactive programs are ubiquitous: every event-handler (e.g. for UI events) is an example for a reaction in a push-scenario.</li>
</ul>
<p><a href="http://www.leading-edge-dev.de/wp-content/uploads/2009/10/Reactive_Programming1.png"><img class="alignnone size-full wp-image-504" title="Reactive Programming" src="http://www.leading-edge-dev.de/wp-content/uploads/2009/10/Reactive_Programming1.png" alt="Reactive Programming" width="400" height="206" /></a></p>
<p>The guys at Microsoft got a very important insight which builds the fundament of Rx: there&#8217;s a <strong><a href="http://en.wikipedia.org/wiki/Duality_%28mathematics%29"><em>dualism</em></a> between the <a href="http://en.wikipedia.org/wiki/Iterator_pattern">Iterator</a> and the <a href="http://en.wikipedia.org/wiki/Observer_pattern">Observer</a> pattern</strong>! This means that both patterns are essentially the same, if you dismiss their practical intentions for a moment.<br />
With the <em>Iterator</em> pattern you get a sequence of data which is iterated in the <em>pull</em>-mode: the Iterator is the actor and asks the iterable object for data.<br />
The <em>Observer</em> pattern can be interpreted equivalently: the environment pushes data into your program (e.g. through events), which has to react. As result with repeatedly fired events you get a sequence of data, which makes the relationship to the Iterator pattern obvious.</p>
<p>With this, an Observer in the push-scenario is equal to an Iterator in the pull-scenario and that&#8217;s the key insight, which has led to the development of the Reactive Framework. 14 years had to pass from the publication of the GoF <a href="http://www.amazon.com/dp/0201633612">Design Patterns</a> book until now to figure out this intense relationship of the Iterator and the Observer pattern.</p>
<h3>LINQ to Events</h3>
<p>Rx realizes the Observer pattern with the two interfaces <code>IObserver</code> and <code>IObservable</code> which are the pendants for <code>IEnumerator</code>/<code>IEnumerable</code> of the Iterator pattern. <code>IObservable</code> is a sort of &#8220;asynchronous collection&#8221;, which represents the occurrence of a certain event at different points in time. Thus it expresses a sequence of data, on which you can run arbitrary actions. In fact <code>IObservable</code> for <em>push</em>-scenarios is essentially the same as <code>IEnumerable</code> for <em>pull</em>-scenarios.</p>
<p>The interplay of <code>IObservable</code> and <code>IObserver</code> is the following: on an <code>IObservable</code> you can register (<code>Subscribe()</code>) an <code>IObserver</code> (Note the dualism to <code>IEnumerable</code>/<code>IEnumerator</code> here!). The <code>IObserver</code> has three methods <code>OnNext()</code>, <code>OnCompleted()</code> and <code>OnError()</code>. These methods are invoked when the <code>IObservable</code> gets new data, completes the data sequence or results in an error. Thus your <code>IObserver</code> implementations take care of the data processing which replaces your custom callback methods.</p>
<p>The real impressing thing with Rx is that with events as data sequences you can use <strong>LINQ</strong> syntax to process and transform these data sequences (that&#8217;s why it&#8217;s sometimes called <em>LINQ to Events</em>). To create instances of <code>IObservable</code> and for providing LINQ methods, Rx comes with the class <code>Observable</code>. If you want for example take the first 10 click events on a button but skip the first click, you could easily write:</p>
<pre class="brush:csharp">
Observable.FromEvent(button1, "Click")
    .Skip(1)
    .Take(9)
    .Subscribe(ev =&gt; MyEventAction(ev));
</pre>
<p><code>Subscribe()</code> has some overloads. In this example I&#8217;ve directly specified an action which is executed when an event (= a piece of data) comes in. Instead you could give it e.g. your custom implementations of <code>IObserver</code> as well.<br />
LINQ gives you real power in processing, composing and transforming your events as data stream. Even in the simple example above, if you would implement it by event-based programming without Rx, you would need some additional effort. You would have to use temporary variables to skip certain elements, take others and so forth. In general, more complex cases require complete <a href="http://en.wikipedia.org/wiki/Finite_state_machine"><em>finite state machines</em></a> which can be circumvented with Rx.</p>
<p>Composing events with LINQ is another typical and impressing example for Rx. Thus, a dragging event on a textblock can be implemented as:</p>
<pre class="brush:csharp">
IObservable&lt;Event&lt;MouseEventArgs&gt;&gt; draggingEvent =
    from mouseLeftDownEvent in Observable.FromEvent(textBlock1, "MouseLeftButtonDown")
    from mouseMoveEvent in Observable.FromEvent(textBlock1, "MouseMove")
        .Until(Observable.FromEvent(textBlock1, "MouseLeftButtonUp"))
    select mouseMoveEvent;
draggingEvent.Subscribe(...);
</pre>
<p>In this example, with the <code>from</code> keyword the two events <code>"MouseLeftButtonDown"</code> and <code>"MouseMove"</code> are chained together. Everytime the left mouse button is pressed on the textbox, the &#8220;gate&#8221; opens to react on mouse move events. The &#8220;gate&#8221; closes again when the left mouse button is released. So the composed stream includes all events where the left mouse button is pressed and the mouse is moved &#8211; the typical dragging event!</p>
<p>There are other possibilities to compose events, which for example consider the order of events differently. Those build the interesting parts of the Reactive Framework and clarify the use cases, where Rx has real advantages over present event-based .NET programming.</p>
<h3>Bottom line</h3>
<p>Personally I like the new way of thinking of events as <em>data sequence</em>! The <em>dualism</em> of the Iterator and the Observer pattern has nothing artificially constructed, but some sort of purity and mathematical <em>elegance</em> for me. But one big question remains: do we need this in our everyday&#8217;s developer life and which advantages come with it?</p>
<p>Erik Meijer himself says about Rx:</p>
<blockquote><p>Of all the work I&#8217;ve done in my career so far, this is the most exciting. [...] I know it&#8217;s a bold statement, but I really believe that the problem of asynchronous programming events has been solved.</p></blockquote>
<p>That&#8217;s a really strong message and it has some important weight since Erik is the creator of LINQ and has a big expertise in language design. Does Rx hold what he promises?</p>
<p>In my opinion Rx is really beautiful and valuable when you do <em>complex</em> asynchronous operations, where you have to <em>compose</em> and <em>orchestrate</em> events/data from <em>several sources</em>. With Rx you&#8217;re able to chain and filter events to easily create the <em>concrete event</em>, to which you want to react. That&#8217;s the power of <em>LINQ</em>, which allows transforming the resulting data as well. LINQ gives you the whole flexibility of processing the data stream that you already know from LINQ to Objects (on <code>IEnumerable</code>) etc.</p>
<p>Beyond that at the moment I don&#8217;t see a <em>real</em> big impact in many current development scenarios. If you have to handle <em>simple</em> events or do simple async computations, you are still fine with the <em>present</em> event-based programming model. Of course with Rx you can write your own observers to prevent a sea of callback methods, but <em>encapsulation</em> of handler logic can be done without that as well. Thus at the end I like the concepts of Rx (Observer, LINQ, &#8230;) and I&#8217;m curious to see how this whole thing develops after the release of .NET 4.0, but I&#8217;m not over-enthusiastic at the moment.</p>
<h3>Links</h3>
<p>Finally here is a list of links to some interesting websites regarding the Reactive Framework:</p>
<ul>
<li><a href="http://langnetsymposium.com/2009/talks/23-ErikMeijer-LiveLabsReactiveFramework.html">Lang.NET &#8211; Live Labs Reactive Framework</a></li>
<li><a href="http://channel9.msdn.com/shows/Going+Deep/Expert-to-Expert-Brian-Beckman-and-Erik-Meijer-Inside-the-NET-Reactive-Framework-Rx/">Channel9 &#8211; Inside the .NET Reactive Framework (Rx)</a></li>
<li><a href="http://channel9.msdn.com/shows/Going+Deep/Kim-Hamilton-and-Wes-Dyer-Inside-NET-Rx-and-IObservableIObserver-in-the-BCL-VS-2010/">Channel9- Inside .NET Rx and IObservable/IObserver in the BCL (VS 2010)</a></li>
<li><a href="http://channel9.msdn.com/shows/Going+Deep/E2E-Erik-Meijer-and-Wes-Dyer-Reactive-Framework-Rx-Under-the-Hood-1-of-2/">Channel9 &#8211; Reactive Framework Under the Hood Part1</a></li>
<li><a href="http://channel9.msdn.com/shows/Going+Deep/E2E-Erik-Meijer-and-Wes-Dyer-Reactive-Framework-Rx-Under-the-Hood-2-of-2/">Channel9 &#8211; Reactive Framework Under the Hood Part2</a></li>
<li><a href="http://themechanicalbride.blogspot.com/2009/07/introducing-rx-linq-to-events.html">unfold &#8211; Introducing Rx (Linq to Events)</a></li>
<li><a href="http://themechanicalbride.blogspot.com/2009/07/developing-with-rx-part-1-extension.html">unfold &#8211; The Joy of Rx: Extension Events</a></li>
<li><a href="http://themechanicalbride.blogspot.com/2009/07/developing-with-rx-part-2-converting.html">unfold &#8211; The Joy of Rx: The Event-Based Async Pattern vs. IObservable</a></li>
<li><a href="http://themechanicalbride.blogspot.com/2009/08/joy-of-rx-building-asynchronous-service.html">unfold &#8211; The Joy of Rx: Building an Asynchronous API&#8230;</a></li>
<li><a href="http://www.paulbatum.com/search/label/Reactive%20Framework">Paul Batum &#8211; Reacting to the Reactive Framework Series</a></li>
</ul>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.leading-edge-dev.de%2f%3fp%3d501"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.leading-edge-dev.de%2f%3fp%3d501" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.minddriven.de/index.php/technology/dot-net/reactive-framework-rx-first-look/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Is the Specification Pattern obsolete?</title>
		<link>http://www.minddriven.de/index.php/technology/dot-net/c-sharp/specification-pattern-obsolete</link>
		<comments>http://www.minddriven.de/index.php/technology/dot-net/c-sharp/specification-pattern-obsolete#comments</comments>
		<pubDate>Thu, 08 Oct 2009 16:59:14 +0000</pubDate>
		<dc:creator>Matthias Jauernig</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Design patterns]]></category>
		<category><![CDATA[expressions]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[specification pattern]]></category>

		<guid isPermaLink="false">http://www.leading-edge-dev.de/?p=466</guid>
		<description><![CDATA[I&#8217;m a guy who loves many of the new patterns that I get to know. But sometimes when I show that pattern to colleagues around me, they tilt their heads and say: &#8220;Arrrm, who needs this?&#8221;. Often they help me to get back to the ground and think again about intents and benefits of one [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m a guy who loves many of the new patterns that I get to know. But sometimes when I show that pattern to colleagues around me, they tilt their heads and say: &#8220;Arrrm, who needs this?&#8221;. Often they help me to get back to the ground and think again about intents and benefits of one or the other pattern.</p>
<p>Currently I&#8217;m rethinking the <a href="http://en.wikipedia.org/wiki/Specification_pattern">Specification Pattern</a>, which has been <a href="http://www.martinfowler.com/apsupp/spec.pdf">introduced</a> by Eric Evans and Martin Fowler some time ago and got some attention in the <a href="http://en.wikipedia.org/wiki/Domain-driven_design">DDD</a> community and beyond. The intent of the Specification Pattern is to separate the logic for (e.g.) filtering an entity from the entity itself. This responsibility is encapsulated in single classes &#8211; the specifications. Those specifications are given for example to a single method <code>Filter()</code> on a <em>repository</em>, which takes care of filtering the <em>domain model</em> by the specifications. Thus, you bypass the need for having several special methods in your repository which take care of the actual filter operation (such as <code>FilterByCustomerName()</code>, <code>FilterByCustomerAddress()</code> etc.).</p>
<p>An example interface snippet for a repository of persons with a specification filter method could then be:</p>
<pre class="brush:csharp">interface IPersonRepository
{
    IEnumerable&lt;Person&gt; Filter(ISpecification&lt;Person&gt; filterTerm);
    // ...
}</pre>
<p>Summarized, some key benefits of the Specification Pattern are:</p>
<ul>
<li><em>Loose coupling</em> of the filter logic from the objects being filtered,</li>
<li><em>Single responsibility</em>: Interface of repository/data provider isn&#8217;t polluted with lots of filter methods,</li>
<li>Callers can express in a <em>flexible</em> way by which criteria entities can be filtered,</li>
<li><em>Composition</em> of specifications (e.g. by a <a href="http://en.wikipedia.org/wiki/Fluent_interface">fluent interface</a>) yields to flexible filter queries, for example:<br />
[sourcecode language='c#']var filter = Filter
<person>.By<ageabove>(25).And<workingin>(&#8220;Frankfurt&#8221;)[/sourcecode]</workingin></ageabove></person></li>
</ul>
<p>But now the provocative question that one could come with: <strong>Who needs the Specification Pattern in times of C# 3.0 and Expressions?</strong> This might sound disturbing at first, but let me explain&#8230;<br />
C# 3.0 came up with the new concept of Expressions/Expression trees. This way, code can be treated as a kind of syntax tree in the program. Developers can extend the tree with additional code portions and then compile it into executable code which can be invoked.</p>
<p>Therefore Expressions seem to give us similar benefits for filtering as specifications do. By using Expressions, we are able to define a single <code>Filter()</code> method on the repository, which gets an appropriate Expression as argument. Consumers of the repository can call this method with their custom filter Expressions and thus we&#8217;ve got the same benefits: loose coupling of filter logic and objects to be filtered, flexibility for callers to provide custom filter criteria and the possibility to combine several filter criteria (several Expressions).<br />
One could argue that with specifications we&#8217;ve got better encapsulation of the filter logic into separate classes. But this can be done with Expressions as well (e.g. by separate wrapper classes or dedicated Expression providers), so that isn&#8217;t a good argument&#8230;</p>
<p>The interface of a repository of persons with a filter that uses Expressions might look like this:</p>
<pre class="brush:csharp">interface IPersonRepository
{
    IEnumerable&lt;Person&gt; Filter(Expression&lt;Predicate&lt;Person&gt;&gt; filterTerm);
    // ...
}</pre>
<p>This leads again to the question: Do we still need the Specification Pattern or is it already embedded with Expressions in the language (C# 3.0) itself?</p>
<h4>Pattern focus</h4>
<p>First I want to mention that the intent of a <em>pattern</em> is not (only) to provide a technical solution, but also a conceptual guideline for a problem at hand. Thus Expressions as technical solution don&#8217;t cover the intent of the Specification Pattern. The Specification Pattern can be implemented with the help of Expressions, but that&#8217;s another point. So, directly comparing the Specification Pattern with Expressions is like an apple-pear-comparison.</p>
<h4>Encapsulation focus</h4>
<p>Let&#8217;s come to use cases when I would prefer the use of dedicated specification classes rather than directly using Expressions.<br />
First as a team lead you could want to enforce the use of dedicated specification classes in your development team (thus enforce encapsulation of the filter logic). By giving Expressions or Predicates to filter methods directly,  developers would be allowed to define filter expressions whereever they want to. You don&#8217;t have the control over this process and please don&#8217;t trust your project guidelines: If developers are allowed to do something wrong, they will do.</p>
<p>With specifications you can force your team members to write specification classes for their requirements, which leads to enforced <em>encapsulation</em>. Furthermore you drive <em>reuse</em> of existing specification classes. Other developers are encouraged to use existing specifications, especially because of the additional effort for writing new specifications. By combining several specifications, the reusability aspect is pushed even more.</p>
<h4>Domain model focus</h4>
<p>Giving consumers the full flexibility of defining custom filter criteria with specifications can be very handsome in many situations. However, in other scenarios instead of giving full flexibility, you may want to restrict the set of filters for your domain model. If you focus on your domain, you perhaps want a restricted set of specifications, each with a very specific meaning in your domain! Binding such specifications to your domain model makes the purpose of your domain and how it can/should be used in terms of filtering much clearer.</p>
<p>Technically, in order to restrict access to a particular set of specifications, you could create sealed specification classes <em>inside</em> of your domain model services (same layer as repository). Consumers of the repository would be allowed to call the <code>Filter()</code> method on the repository with those specifications (and compositions of those), but they would not be able to create new specifications if you don&#8217;t mark the specification interface as public. This way you get two characteristics: Restricted filtering, which fits into your domain and your use cases on the one hand, and encapsulation/separation of filter logic and entities which should be filtered on the other hand.</p>
<h4>Bottom line</h4>
<p>This article started with an interesting and provocative question: Is the Specification Pattern obsolete? This question came up with a look at Expressions in C# 3.0. Technically you can achieve similar results when using Expressions instead of implementing the Specification classes by hand. But as the last sections have shown, in my opinion the Specification Pattern is <em>not</em> obsolete! As <em>pattern</em> it&#8217;s adding very specific value to the plain technical solution, when you take encapsulation and domains into account. Then it clearly goes beyond the technical aspect which many developers see at first sight.</p>
<p>Those are my current thoughts on specifications, but of course my opinions are not carved in stone. What do you think? What points I&#8217;ve missed perhaps? I&#8217;m eager for your comments!</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.leading-edge-dev.de%2f%3fp%3d466"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.leading-edge-dev.de%2f%3fp%3d466" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.minddriven.de/index.php/technology/dot-net/c-sharp/specification-pattern-obsolete/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Architektur erlernen</title>
		<link>http://www.minddriven.de/index.php/technology/development/architecture/architektur-erlernen</link>
		<comments>http://www.minddriven.de/index.php/technology/development/architecture/architektur-erlernen#comments</comments>
		<pubDate>Thu, 27 Nov 2008 14:16:26 +0000</pubDate>
		<dc:creator>Matthias Jauernig</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Design patterns]]></category>
		<category><![CDATA[Anforderungen]]></category>
		<category><![CDATA[KISS]]></category>
		<category><![CDATA[Rahmenbedingungen]]></category>

		<guid isPermaLink="false">http://www.leading-edge-dev.de/?p=72</guid>
		<description><![CDATA[Golo Roden hat einen netten Blog-Eintrag erstellt, in dem er beschreibt, wie man sich dem Thema Software-Architekturen nähern kann. Meiner Meinung nach hat Golo hier einige Dinge angesprochen, die für den Einstieg ganz nett sind und die Einstiegshürde nehmen. Auch bei mir stellte (und stellt sich immer wieder) die Frage, wie ich zu einem besseren [...]]]></description>
			<content:encoded><![CDATA[<p>Golo Roden hat einen netten <a href="http://www.des-eisbaeren-blog.de/post/2008/11/27/Architektur-lernen.aspx">Blog-Eintrag</a> erstellt, in dem er beschreibt, wie man sich dem Thema Software-Architekturen nähern kann. Meiner Meinung nach hat Golo hier einige Dinge angesprochen, die für den Einstieg ganz nett sind und die Einstiegshürde nehmen. Auch bei mir stellte (und stellt sich immer wieder) die Frage, wie ich zu einem besseren (oder überhaupt einem <img src='http://www.minddriven.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> ) Architekten werden kann. Meiner Meinung nach sind Leute sehr hilfreich, die einfach einen breiten Begriffsschatz zu dem Thema haben. Mit der Zeit schnappt man von diesen Leuten Begriffe auf, die mit dem Thema Architektur zu tun haben und durchsucht dann das Internet für weitere Informationen zu den jeweiligen Themen. Doch der beste Lehrmeister ist immernoch die Praxis. Man muss einfach selbst Erfahrungen sammeln (und das über Jahre hinweg), um feststellen zu können, welche Dinge funktionieren, welche nicht und <em>warum</em> sie das tun bzw. nicht tun. Dieses Hinterfragen ist essentiell und unerlässlich dafür, seine Lösung später auch vor anderen verteidigen zu können.</p>
<p>Zu guter Letzt noch ein Tipp: beim Thema Architektur sollte man 1.) nie auf der eigenen Meinung verharren und vor allem 2.) sein Design der zu erstellenden Anwendung anpassen. Bei 1.) sollte man begründen können, warum eine Architektur schlecht ist und das mit Gründen, die für das aktuelle Projekt auch relevant sind. Jedes Projekt ist anders und besitzt andere Rahmenbedingungen, die Frage nach einer &#8220;guten&#8221; Architektur ist daher sehr dynamisch und individuell verschieden! Auch ich bin hier gerade in einem Lernvorgang, umso wichtiger ist es mir diese Erfahrung als Tipp weiterzugeben. Zu 2.) ist zu sagen, dass man das KISS-Prinzip beherzigen sollte: <em>keep it solid and simple</em>! Eine abgefahrene Architektur macht nur dann Sinn, wenn das Projekt sie auch erfordert. Seine Kreativität ausleben zu können ist kein Grund dafür, wilde Architekturspielereien durchzuführen, z.B. durch den Einsatz von Mocking- oder Dependency-Injection-Frameworks. Austauschbarkeit von Komponenten wie dem Datenzugriff ist beispielsweise so eine Spielerei, die nur in wenigen Projekten auch sinnvoll ist. Erst wenn die fachliche Anforderung es konkret erfordert, sollte ein Aspekt in den Entwurf des Architekturdesigns mit einfließen. Man sollte sich immer wieder selber fragen: benötige ich es überhaupt, wenn ja aus welchem Grund und geht es vielleicht auch anders/einfacher? Hilfreich ist auch die Vorstellung, dass man seine Lösung und die einzelnen Teile bei seinem Auftraggeber verteidigen muss. Wenn hier als Argument nur übrigbleibt: &#8220;ja das ist jetzt schön austauschbar&#8221;, die Anforderungen es aber nicht erfordern, spätestens dann sollte man sich fragen, ob man nicht etwas falsch macht&#8230;</p>
<p>Wie gesagt, ich selbst sehe mich perspektivisch als Architekt und finde das ganze Thema sehr spannend, stehe aber 2 Monate nach meinem Studiumsabschluss selber noch ziemlich am Anfang <img src='http://www.minddriven.de/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.minddriven.de/index.php/technology/development/architecture/architektur-erlernen/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

