<?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>mhinze.com&#187; Aggregated specifications</title>
	<atom:link href="http://mhinze.com/category/domain-driven-design/feed/" rel="self" type="application/rss+xml" />
	<link>http://mhinze.com</link>
	<description>Matt Hinze, learning in public</description>
	<lastBuildDate>Tue, 20 Apr 2010 22:42:47 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Aggregated specifications</title>
		<link>http://mhinze.com/aggregated-specifications/</link>
		<comments>http://mhinze.com/aggregated-specifications/#comments</comments>
		<pubDate>Thu, 08 Oct 2009 11:07:53 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Domain-Driven Design]]></category>

		<guid isPermaLink="false">http://mhinze.com/aggregated-specifications/</guid>
		<description><![CDATA[An example from my inversion of control talk involves a message formatter.&#160; It applies formatting rules to a string. public interface IMessageFomatter { string Format(string message); } Instead of doing all the work in the implementation of this interface, the message formatter will aggregate several distinct rules.&#160; An inversion of control tool is configured to [...]]]></description>
			<content:encoded><![CDATA[<p>An example from my inversion of control talk involves a message formatter.&#160; It applies formatting rules to a string. </p>
<pre class="code"><span style="color: blue">public interface </span><span style="color: #2b91af">IMessageFomatter
</span>{
    <span style="color: blue">string </span>Format(<span style="color: blue">string </span>message);
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Instead of doing all the work in the implementation of this interface, the message formatter will aggregate several distinct rules.&#160; An inversion of control tool is configured to compose these rules and provide them to the formatter.</p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">MessageFomatter </span>: <span style="color: #2b91af">IMessageFomatter
</span>{
    <span style="color: blue">private readonly </span><span style="color: #2b91af">IFormatRule</span>[] _rules;

    <span style="color: blue">public </span>MessageFomatter(<span style="color: #2b91af">IFormatRule</span>[] rules)
    {
        _rules = rules;
    }

    <span style="color: blue">public string </span>Format(<span style="color: blue">string </span>message)
    {
        <span style="color: blue">foreach </span>(<span style="color: blue">var </span>action <span style="color: blue">in </span>_rules)
        {
            message = action.ApplyRule(message);
        }
        <span style="color: blue">return </span>message;
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>In this way each rule can be small, testable, and have only one job.&#160; I can add functionality to the formatting process without changing the formatter or any existing rule.&#160; </p>
<pre class="code"><span style="color: blue">public interface </span><span style="color: #2b91af">IFormatRule
</span>{
    <span style="color: blue">string </span>ApplyRule(<span style="color: blue">string </span>text);
}

<span style="color: blue">public class </span><span style="color: #2b91af">DisclaimerRule </span>: <span style="color: #2b91af">IFormatRule
</span>{
    <span style="color: blue">public string </span>ApplyRule(<span style="color: blue">string </span>text)
    {
        <span style="color: blue">return </span>text + <span style="color: #a31515">&quot;\nDisclaimer: This message will self-destruct&quot;</span>;
    }
}

<span style="color: blue">public class </span><span style="color: #2b91af">UppercaseRule </span>: <span style="color: #2b91af">IFormatRule
</span>{
    <span style="color: blue">public string </span>ApplyRule(<span style="color: blue">string </span>text)
    {
        <span style="color: blue">return </span>text.ToUpper();
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>This technique is extremely powerful and <a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/03/17/a-better-model-binder.aspx">we use it all over the place in our projects</a>.</p>
<p>Recently we were building a search screen.&#160; It has several text input boxes and select lists and radio button groups, you know, the standard enterprisey UI mess.&#160; Anyway, that&#8217;s what it was and it&#8217;s a common feature in the apps I work on. I&#8217;ve seen the scenario over and over. But armed with the above technique and LINQ to NHibernate, we were able to craft a much more elegant solution than we had previously created.</p>
<p>First we have a type that represents the search query.&#160; It could be implemented by the class that represents the user interface form or be built by the user interface layer.&#160; It&#8217;s sent to a service that will perform the query.</p>
<pre class="code"><span style="color: blue">public interface </span><span style="color: #2b91af">IProductSearchQuery
</span>{
    <span style="color: blue">decimal</span>? Price { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">int</span>? PriceRange { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">string </span>Name { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: #2b91af">ProductCategory </span>Category { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: green">// ...
</span>}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<pre class="code"><span style="color: blue">public interface </span><span style="color: #2b91af">IProductRepository
</span>{
    <span style="color: #2b91af">Product</span>[] Search(<span style="color: #2b91af">IProductSearchQuery </span>query);
    <span style="color: green">// ...
</span>}</pre>
<p>What we don&#8217;t want is a huge method that checks to see if a search criteria exists and then conditionally appends predicates to a database query.&#160; That&#8217;s the old school way, and it&#8217;s a beast to test and to change.&#160; Adding a user interface element, like a new text input field, would require us to change that big method by introducing repetitive and dangerous new code.</p>
<p>What we do want are <a href="http://ubik.com.au/article/named/implementing_the_specification_pattern_with_linq">small, isolated specifications</a> that we can aggregate like the message formatter.</p>
<pre class="code"><span style="color: blue">public interface </span><span style="color: #2b91af">IProductSearchFilter
</span>{
    <span style="color: blue">bool </span>ShouldApply(<span style="color: #2b91af">IProductSearchQuery </span>query);
    <span style="color: #2b91af">IQueryable</span>&lt;<span style="color: #2b91af">Product</span>&gt; Filter(<span style="color: #2b91af">IQueryable</span>&lt;<span style="color: #2b91af">Product</span>&gt; candidates, <span style="color: #2b91af">IProductSearchQuery </span>query);
}</pre>
<p>An example filter:</p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">PriceRangeFilter </span>: <span style="color: #2b91af">IProductSearchFilter
</span>{
    <span style="color: blue">public bool </span>ShouldApply(<span style="color: #2b91af">IProductSearchQuery </span>query)
    {
        <span style="color: blue">return </span>query.Price.HasValue &amp;&amp; query.PriceRange.HasValue;
    }

    <span style="color: blue">public </span><span style="color: #2b91af">IQueryable</span>&lt;<span style="color: #2b91af">Product</span>&gt; Filter(<span style="color: #2b91af">IQueryable</span>&lt;<span style="color: #2b91af">Product</span>&gt; candidates, <span style="color: #2b91af">IProductSearchQuery </span>query)
    {
        <span style="color: blue">return from </span>product <span style="color: blue">in </span>candidates
               <span style="color: blue">where </span>product.Price &lt;= (query.Price + query.PriceRange)
               &amp;&amp; product.Price &gt;= (query.Price - query.PriceRange)
               <span style="color: blue">select </span>product;
    }
}</pre>
<p>You can test drive this thing.&#160; It&#8217;s small and distinct.&#160; And using LINQ to NHibernate you can combine several of them in a way that produces one select.</p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">ProductRepository </span>: <span style="color: #2b91af">IProductRepository
</span>{
    <span style="color: blue">private readonly </span><span style="color: #2b91af">ISession </span>_session;
    <span style="color: blue">private readonly </span><span style="color: #2b91af">IProductSearchFilter</span>[] _filters;

    <span style="color: blue">public </span>ProductRepository(<span style="color: #2b91af">ISession </span>session, <span style="color: #2b91af">IProductSearchFilter</span>[] filters)
    {
        _session = session;
        _filters = filters;
    }

    <span style="color: blue">public </span><span style="color: #2b91af">Product</span>[] Search(<span style="color: #2b91af">IProductSearchQuery </span>query)
    {
        <span style="color: blue">var </span>products = _session.Linq&lt;<span style="color: #2b91af">Product</span>&gt;();
        <span style="color: blue">return </span>_filters
            .Where(x =&gt; x.ShouldApply(query))
            .Aggregate(products, (candidates, filter) =&gt;
                filter.Filter(candidates, query)).ToArray();
    }

    <span style="color: green">// ...
</span>}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>One tricky spot for a lot of people is that Aggregate call.&#160; It does the exact same thing as the foreach in the message formatter: passes the seed (products, in this case) through the filters aggregating the result.&#160; The lambda parameter variable candidates is the result of the previous filter (or the seed for the first filter).&#160; In other ecosystems besides .NET, Aggregate is called reduce.&#160; You can see why &#8211; each filter reduces the candidates according to its specification.</p>
<p>When you think about it, an <a href="http://www.google.com/webhp#hl=en&amp;q=mapreduce+architecture">entire architecture could be a reduce</a>. That would be <em>really</em> interesting.</p>
]]></content:encoded>
			<wfw:commentRss>http://mhinze.com/aggregated-specifications/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>More On Value Objects</title>
		<link>http://mhinze.com/more-on-value-objects/</link>
		<comments>http://mhinze.com/more-on-value-objects/#comments</comments>
		<pubDate>Thu, 19 Feb 2009 23:57:52 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[Domain-Driven Design]]></category>
		<category><![CDATA[ddd]]></category>
		<category><![CDATA[value objects]]></category>

		<guid isPermaLink="false">http://mhinze.com/more-on-value-objects/</guid>
		<description><![CDATA[A few days ago Dylan Beattie wrote a nice post about value objects.&#160; He explains the idea in a more palatable way than my attempt: If it’s not clear how to model a particular element in your model, try asking “which one?” If the question makes sense within your own scenario then you’re probably dealing [...]]]></description>
			<content:encoded><![CDATA[<p>A few days ago Dylan Beattie wrote a nice <a href="http://dylanbeattie.blogspot.com/2009/02/is-crisp-value-object.html">post about value objects</a>.&nbsp; He explains the idea in a more <em>palatable</em> way than <a href="http://mhinze.com/there-is-never-a-collection-of-value-objects/">my attempt</a>:</p>
<blockquote><p>If it’s not clear how to model a particular element in your model, try asking “which one?” If the question makes sense within your own scenario then you’re probably dealing with entities. If the question “which one” is meaningless <strong>in the context of your domain </strong>then you’re probably better off modeling the subject of the question as a value object.</p>
</blockquote>
<p> I suggest that if you&#8217;re <em>maintaining</em> a collection, you implicitly care <em>which one</em>.</p>
]]></content:encoded>
			<wfw:commentRss>http://mhinze.com/more-on-value-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>There is never a collection of Value Objects</title>
		<link>http://mhinze.com/there-is-never-a-collection-of-value-objects/</link>
		<comments>http://mhinze.com/there-is-never-a-collection-of-value-objects/#comments</comments>
		<pubDate>Sat, 10 Jan 2009 05:59:57 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[Domain-Driven Design]]></category>
		<category><![CDATA[ddd]]></category>
		<category><![CDATA[value objects]]></category>

		<guid isPermaLink="false">http://mhinze.com/there-is-never-a-collection-of-value-objects/</guid>
		<description><![CDATA[Adding to a Value Object property always adds to it, never adds another instance to it.&#160; Distinguishing Value Objects by maintaining a collection of them implies identity. It is a mistake to attempt to maintain a collection of Value Objects. Let&#8217;s take the near-canonical Address, a perfectly valid Value Object as described on page 98 [...]]]></description>
			<content:encoded><![CDATA[<p>Adding to a Value Object property always <em>adds to it</em>, <strong>never</strong> <em>adds another instance to it</em>.&nbsp; Distinguishing Value Objects by maintaining a collection of them <strong>implies identity</strong>. </p>
<p>It is a mistake to attempt to maintain a collection of Value Objects.</p>
<p>Let&#8217;s take the near-canonical Address, a perfectly valid Value Object as described on page 98 of the Big Blue Bible:</p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">Address </span>: <span style="color: #2b91af">ValueObject</span>&lt;<span style="color: #2b91af">Address</span>&gt;
{
    <span style="color: blue">public virtual string </span>StreetAddress1 { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public virtual string </span>StreetAddress2 { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public virtual string </span>City { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public virtual </span><span style="color: #2b91af">State </span>State { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public virtual string </span>ZipCode { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public virtual </span><span style="color: #2b91af">Country </span>Country { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
}</pre>
<p>And a perfectly valid usage of this Address Value Object is as a component of an Entity: </p>
<p><a href="http://11011.net/software/vspaste"></a>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">Customer </span>: <span style="color: #2b91af">Entity
</span>{
    <span style="color: blue">public </span><span style="color: #2b91af">Address </span>WorkAddress { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public </span><span style="color: #2b91af">Address </span>HomeAddress { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: green">// ...
</span>}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>This, on the other hand, is incorrect:</p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">Customer </span>: <span style="color: #2b91af">Entity</span>{
    <span style="color: blue">private readonly </span><span style="color: #2b91af">ISet</span>&lt;<span style="color: #2b91af">Address</span>&gt; _addresses = <span style="color: blue">new </span><span style="color: #2b91af">HashedSet</span>&lt;<span style="color: #2b91af">Address</span>&gt;();

    <span style="color: blue">public </span><span style="color: #2b91af">Address</span>[] GetAddresses()
    {
        <span style="color: blue">return </span>_addresses.ToArray();
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Again, distinguishing addresses by maintaining a collection of them <strong>implies identity</strong>. If you tried to edit one of the addresses respecting some immutable Value Object oriented thinking, you would clear the collection, find (somehow) the one you intended to edit, replace it along with all the others.&nbsp; This is not possible.&nbsp; When you only care about the values of an object, rather than a key, you cannot find the original one you intend to edit from an instance of an edited object.&nbsp; If you care about a key you have an Entity.</p>
<p>The original and the edited will never match. You might try to give the Value Object a database key so that it is easy to find.&nbsp; But if you do that, why again are you clearing all the rest and re-adding them?&nbsp; That doesn&#8217;t make sense &#8211; just edit it. </p>
<p>There&#8217;s another problem.&nbsp; In the &#8220;wallet&#8221; example you have paper money in your wallet, several pieces of paper.&nbsp; Your wallet is the Entity and the money is a Value Object.&nbsp; If you were to take some money out of your wallet, you would subtract from the Value Object, not remove an instance of the Value Object from a collection.&nbsp; You don&#8217;t care if you have five ones or one five, you just care that you have five.&nbsp; Value Objects never collect, they only aggregate.</p>
<p>If you care about each individual instance, you have an Entity.</p>
<p>The best way to model something like this is to use an Entity that has a Value Object component.&nbsp; If I am maintaining a collection of Addresses, I do actually care that each is different &#8211; the trick is to find out <strong>why</strong>.&nbsp; In my case I care because the Customer has an address history and I wish to maintain that history.&nbsp; I model that like this:</p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">HistoricalAddress </span>: <span style="color: #2b91af">Entity
</span>{
    <span style="color: blue">public </span><span style="color: #2b91af">Address </span>Address { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public </span><span style="color: #2b91af">DateTime</span>? Start { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public </span><span style="color: #2b91af">DateTime</span>? End { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public </span><span style="color: #2b91af">AddressType </span>Type { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>Now the HistoricalAddress Entity lives in the Customer Aggregate&#8230;</p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">Customer </span>: <span style="color: #2b91af">Entity
</span>{
    <span style="color: blue">private readonly </span><span style="color: #2b91af">ISet</span>&lt;<span style="color: #2b91af">HistoricalAddress</span>&gt; _addresses = <span style="color: blue">new </span><span style="color: #2b91af">HashedSet</span>&lt;<span style="color: #2b91af">HistoricalAddress</span>&gt;();

    <span style="color: blue">public </span><span style="color: #2b91af">HistoricalAddress</span>[] GetAddresses()
    {
        <span style="color: blue">return </span>_addresses.ToArray();
    }

    <span style="color: blue">public </span><span style="color: #2b91af">HistoricalAddress </span>GetAddress(<span style="color: #2b91af">Guid </span>historicalAddressId)
    {
        <span style="color: blue">return </span>_addresses.SingleOrDefault(x =&gt; x.Id == historicalAddressId);
    }

    <span style="color: green">//...
</span>}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>&#8230; and I am free to edit, list, and delete them with ease.</p>
<p>The one caveat is when you are maintaining a collection of Value Objects that represent all possible values.&nbsp; If you have a State Value Object you may want to represent a collection of all 50 U.S. States as a select list in the user interface.&nbsp; This works fine and is programmatically possible, until you are interested in maintaining this collection.</p>
]]></content:encoded>
			<wfw:commentRss>http://mhinze.com/there-is-never-a-collection-of-value-objects/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
	</channel>
</rss>
