<?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>Udi Dahan - The Software Simplist &#187; DDD</title>
	<atom:link href="http://www.udidahan.com/category/ddd/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.udidahan.com</link>
	<description>Enterprise Development Expert &#38; SOA Specialist</description>
	<lastBuildDate>Mon, 08 Mar 2010 14:34:24 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Progressive .NET Wrap-up</title>
		<link>http://www.udidahan.com/2009/09/07/progressive-net-wrap-up/</link>
		<comments>http://www.udidahan.com/2009/09/07/progressive-net-wrap-up/#comments</comments>
		<pubDate>Mon, 07 Sep 2009 06:06:30 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Business Rules]]></category>
		<category><![CDATA[Caching]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Databases]]></category>
		<category><![CDATA[ESB]]></category>
		<category><![CDATA[Messaging]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Pub/Sub]]></category>

		<guid isPermaLink="false">http://www.udidahan.com/?p=1103</guid>
		<description><![CDATA[So, I&#8217;ve gotten back from a most enjoyable couple of days in Sweden where I gave two half-day tutorials, the first being the SOA and UI composition talk I gave at the European Virtual ALT.NET meeting (which you can find online here) and the other on DDD in enterprise apps (the first time I&#8217;ve done [...]]]></description>
			<content:encoded><![CDATA[<p>So, I&#8217;ve gotten back from a most enjoyable couple of days in Sweden where I gave two half-day tutorials, the first being the SOA and UI composition talk I gave at the European Virtual ALT.NET meeting (which you can find online <a href="http://www.vimeo.com/5022174">here</a>) and the other on DDD in enterprise apps (the first time I&#8217;ve done this talk).</p>
<p>I&#8217;ve gotten some questions about my DDD presentation there based on <a href="http://codebetter.com/blogs/aaron.jensen/">Aaron Jensen&#8217;s</a> pictures:</p>
<p><img src="http://www.udidahan.com/wp-content/uploads/cqs_udi_dahan_presentation.jpg" alt="cqs_udi_dahan_presentation" title="cqs_udi_dahan_presentation" width="500" height="332" class="alignnone size-full wp-image-1104" /></p>
<p>Yes &#8211; I talk with my hands. All the time.</p>
<p>That slide is quite an important one &#8211; I talked about it for at least 2 hours.</p>
<p>Here it is again, this time in full:</p>
<p><img src="http://www.udidahan.com/wp-content/uploads/cqs.jpg" alt="cqs" title="cqs" width="500" height="374" class="alignnone size-full wp-image-1107" /></p>
<p>You may notice that the nice clean layered abstraction that the industry has gotten so comfortable with doesn&#8217;t quite sit right when looking at it from this perspective. The reason for that is that this perspective takes into account physical distribution while layers don&#8217;t.</p>
<p>I&#8217;ll have some more posts on this topic as well as giving a session in TechEd Europe this November.</p>
<p>Oh &#8211; and please do feel free to already send your questions in.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2009/09/07/progressive-net-wrap-up/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Don&#8217;t Delete &#8211; Just Don&#8217;t</title>
		<link>http://www.udidahan.com/2009/09/01/dont-delete-just-dont/</link>
		<comments>http://www.udidahan.com/2009/09/01/dont-delete-just-dont/#comments</comments>
		<pubDate>Tue, 01 Sep 2009 12:04:48 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Business Rules]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Databases]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://www.udidahan.com/?p=1097</guid>
		<description><![CDATA[]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.udidahan.com/wp-content/uploads/no_delete.png" style="float:right; margin-left:10px; margin-bottom:10px; alt="no deletes" title="no deletes" /><br />
After reading Ayende&#8217;s <a href="http://ayende.com/Blog/archive/2009/08/30/avoid-soft-deletes.aspx">post</a> advocating against &#8220;soft deletes&#8221; I felt that I should add a bit more to the topic as there were some important business semantics missing. As developers discuss the pertinence of using an IsDeleted column in the database to mark deletion, and the way this relates to reporting and auditing concerns is weighed, the core domain concepts rarely get a mention. Let&#8217;s first understand the business scenarios we&#8217;re modeling, the why behind them, before delving into the how of implementation.</p>
<h3>The real world doesn&#8217;t cascade</h3>
<p>Let&#8217;s say our marketing department decides to delete an item from the catalog. Should all previous orders containing that item just disappear? And cascading farther, should all invoices for those orders be deleted as well? Going on, would we have to redo the company&#8217;s profit and loss statements?</p>
<p>Heaven forbid.</p>
<p>So, is Ayende wrong? Do we really need soft deletes after all?</p>
<p>On the one hand, we don&#8217;t want to leave our database in an inconsistent state with invoices pointing to non-existent orders, but on the other hand, our users did ask us to delete an entity.</p>
<p>Or did they?</p>
<h3>When all you have is a hammer&#8230;</h3>
<p>We&#8217;ve been exposing users to entity-based interfaces with &#8220;create, read, update, delete&#8221; semantics in them for so long that they have started presenting us requirements using that same language, even though it&#8217;s an extremely poor fit.</p>
<p>Instead of accepting &#8220;delete&#8221; as a normal user action, let&#8217;s go into why users &#8220;delete&#8221; stuff, and what they actually intend to do.</p>
<p>The guys in marketing can&#8217;t actually make all physical instances of a product disappear &#8211; nor would they want to. In talking with these users, we might discover that their intent is quite different:</p>
<blockquote><p>“What I mean by &#8216;delete&#8217; is that the product should be discontinued. We don&#8217;t want to sell this line of product anymore. We want to get rid of the inventory we have, but not order any more from our supplier. The product shouldn&#8217;t appear any more when customers do a product search or category listing, but the guys in the warehouse will still need to manage these items in the interim. It&#8217;s much shorter to just say &#8216;delete&#8217; though.”</p></blockquote>
<p>There seem to be quite a few interesting business rules and processes there, but nothing that looks like it could be solved by a single database column.</p>
<h3>Model the task, not the data</h3>
<p>Looking back at the story our friend from marketing told us, his intent is to discontinue the product &#8211; not to delete it in any technical sense of the word. As such, we probably should provide a more explicit representation of this task in the user interface than just selecting a row in some grid and clicking the &#8216;delete&#8217; button (and &#8220;Are you sure?&#8221; isn&#8217;t it).</p>
<p>As we broaden our perspective to more parts of the system, we see this same pattern repeating:</p>
<blockquote><p>
Orders aren&#8217;t deleted &#8211; they&#8217;re cancelled. There may also be fees incurred if the order is canceled too late.</p>
<p>Employees aren&#8217;t deleted &#8211; they&#8217;re fired (or possibly retired). A compensation package often needs to be handled.</p>
<p>Jobs aren&#8217;t deleted &#8211; they&#8217;re filled (or their requisition is revoked).
</p></blockquote>
<p>In all cases, the thing we should focus on is the task the user wishes to perform, rather than on the technical action to be performed on one entity or another. In almost all cases, more than one entity needs to be considered.</p>
<h3>Statuses</h3>
<p>In all the examples above, what we see is a replacement of the technical action &#8216;delete&#8217; with a relevant business action. At the entity level, instead of having a (hidden) technical WasDeleted status, we see an explicit business status that users need to be aware of.</p>
<p>The manager of the warehouse needs to know that a product is discontinued so that they don&#8217;t order any more stock from the supplier. In today&#8217;s world of retail with Vendor Managed Inventory, this often happens together with a modification to an agreement with the vendor, or possibly a cancellation of that agreement. </p>
<p>This isn&#8217;t just a case of transactional or reporting boundaries &#8211; users in different contexts need to see different things at different times as the status changes to reflect the entity&#8217;s place in the business lifecycle. Customers shouldn&#8217;t see discontinued products at all. Warehouse workers should, that is, until the corresponding Stock Keeping Unit (SKU) has been revoked (another status) after we&#8217;ve sold all the inventory we wanted (and maybe returned the rest back to the supplier).</p>
<h3>Rules and Validation</h3>
<p>When looking at the world through over-simplified-delete-glasses, we may consider the logic dictating when we can delete to be quite simple: do some role-based-security checks, check that the entity exists, delete. Piece of cake.</p>
<p>The real world is a bigger, more complicated cake.</p>
<p>Let&#8217;s consider deleting an order, or rather, canceling it. On top of the regular security checks, we&#8217;ve got some rules to consider:</p>
<blockquote><p>
If the order has already been delivered, check if the customer isn&#8217;t happy with what they got, and go about <b>returning</b> the order. </p>
<p>If the order contained products &#8220;made to order&#8221;, charge the customer for a portion (or all) of the order (based on other rules).</p>
<p>And more&#8230;
</p></blockquote>
<p>Deciding what the next status should be may very well depend on the current business status of the entity. Deciding if that change of state is allowed is context and time specific &#8211; at one point in time the task may have been allowed, but later not. The logic here is not necessarily entirely related to the entity being &#8220;deleted&#8221; &#8211; there may be other entities which need to be checked, and whose status may also need  to be changed as well.</p>
<h3>Summary</h3>
<p>I know that some of you are thinking, &#8220;my system isn&#8217;t that complex &#8211; we can just delete and be done with it&#8221;.</p>
<p>My question to you would be, have you asked your users <b>why</b> they&#8217;re deleting things? Have you asked them about additional statuses and rules dictating how entities move as groups between them? You don&#8217;t want the success of your project to be undermined by that kind of unfounded assumption, do you?</p>
<p>The reason we&#8217;re given budgets to build business applications is because of the richness in business rules and statuses that ultimately provide value to users and a competitive advantage to the business. If that value wasn&#8217;t there, wouldn&#8217;t we be serving our users better by just giving them Microsoft Access?</p>
<p>In closing, given that you&#8217;re not giving your users MS Access, don&#8217;t think about deleting entities. Look for the reason why. Understand the different statuses that entities move between. Ask which users need to care about which status. I know it doesn&#8217;t show up as nicely on your resume as &#8220;3 years WXF&#8221;, but &#8220;saved the company $4 million in wasted inventory&#8221; does speak volumes.</p>
<p>One last sentence: Don&#8217;t delete. Just don&#8217;t.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2009/09/01/dont-delete-just-dont/feed/</wfw:commentRss>
		<slash:comments>56</slash:comments>
		</item>
		<item>
		<title>MSDN Magazine Domain Model Article</title>
		<link>http://www.udidahan.com/2009/08/02/msdn-magazine-domain-model-article/</link>
		<comments>http://www.udidahan.com/2009/08/02/msdn-magazine-domain-model-article/#comments</comments>
		<pubDate>Sun, 02 Aug 2009 14:11:45 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Databases]]></category>

		<guid isPermaLink="false">http://www.udidahan.com/?p=1063</guid>
		<description><![CDATA[
My article on “employing the domain model pattern” has been published in the August edition of MSDN Magazine.
Here’s a short excerpt:
“In this article, we’ll go through the reasons to (and not to) employ the domain model pattern, the benefits it brings, as well as provide some practical tips on keeping the overall solution as simple [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://msdn.microsoft.com/en-us/magazine/ee236415.aspx"><img title="MSDN magazine" style="border-right: 0px; border-top: 0px; display: inline; margin: 0px 0px 10px 10px; border-left: 0px; border-bottom: 0px" height="346" alt="MSDN magazine" src="http://www.udidahan.com/wp-content/uploads/msdn_magazine_domain_model.gif" width="263" align="right" border="0" /></a></p>
<p>My article on “employing the domain model pattern” has been published in the August edition of MSDN Magazine.</p>
<p>Here’s a short excerpt:</p>
<blockquote><p>“In this article, we’ll go through the reasons to (and not to) employ the domain model pattern, the benefits it brings, as well as provide some practical tips on keeping the overall solution as simple as possible.”</p></blockquote>
<p><a href="http://msdn.microsoft.com/en-us/magazine/ee236415.aspx">Continue reading… </a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2009/08/02/msdn-magazine-domain-model-article/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>Don&#8217;t Create Aggregate Roots</title>
		<link>http://www.udidahan.com/2009/06/29/dont-create-aggregate-roots/</link>
		<comments>http://www.udidahan.com/2009/06/29/dont-create-aggregate-roots/#comments</comments>
		<pubDate>Mon, 29 Jun 2009 11:52:37 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[DDD]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://www.udidahan.com/?p=1042</guid>
		<description><![CDATA[
My previous post on Domain Events left some questions about how aggregate roots should be created unanswered. It would actually be more accurate to say how aggregate roots should *not* be created. It turns out that this is one of the less intuitive parts of domain-driven design and has been the source of many arguments [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.udidahan.com/wp-content/uploads/roots.jpg" alt="roots" title="roots" width="143" height="150"  style="border-right: 0px; border-top: 0px; margin: 0px 10px; border-left: 0px; border-bottom: 0px" align="right"/></p>
<p>My previous post on <a href="http://www.udidahan.com/2009/06/14/domain-events-salvation">Domain Events</a> left some questions about how aggregate roots should be created unanswered. It would actually be more accurate to say how aggregate roots should *not* be created. It turns out that this is one of the less intuitive parts of domain-driven design and has been the source of many arguments on the matter. Let&#8217;s start with the wrong way:</p>
<p>
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">using</span> (ISession s = sf.OpenSession())</pre>
<pre><span class="lnum">   2:  </span><span class="kwrd">using</span> (ITransaction tx = s.BeginTransaction())</pre>
<pre class="alt"><span class="lnum">   3:  </span>{</pre>
<pre><span class="lnum">   4:  </span>    Customer c = <span class="kwrd">new</span> Customer();</pre>
<pre class="alt"><span class="lnum">   5:  </span>    c.Name = <span class="str">"udi dahan"</span>;</pre>
<pre><span class="lnum">   6:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">   7:  </span>    s.Save(c);</pre>
<pre><span class="lnum">   8:  </span>    tx.Commit();</pre>
<pre class="alt"><span class="lnum">   9:  </span>}</pre>
</div>
<p>I understand that the code above is representative of how much code is written when using an object-relational mapper. Many would consider this code to follow DDD principles &#8211; that Customer is an aggregate root. Unfortunately &#8211; that is not the case. The code above is missing the real aggregate root.</p>
<p>There&#8217;s also the inevitable question of validation &#8211; if the customer object isn&#8217;t willing to accept a name with a space in it, should we throw an exception? That would prevent an invalid entity from being saved, which is good. On the other hand, exceptions should be reserved for truly exceptional occurrences. But if we don&#8217;t use exceptions, using Domain Events instead, how do we prevent the invalid entity from being saved?</p>
<p>All of these issues are handled auto-magically once we have a true aggregate root.</p>
<h3>Always Get An Entity</h3>
<p>Let&#8217;s start with the technical guidance &#8211; always get an entity. At least one. Also, don&#8217;t add any objects to the session or unit of work explicitly &#8211; rather, have some other already persistent domain entity create the new entity and add it to a collection property.</p>
<p>Looking at the code above, we see that we&#8217;re not following the technical guidance.</p>
<p>But the question is, which entity could we possibly get from the database in this case? All we&#8217;re doing is adding a customer.</p>
<p>And that&#8217;s exactly where the technical guidance leads us to the business analysis that was missing in this scenario&#8230;</p>
<h3>Business Analysis</h3>
<p>Customers don&#8217;t just appear out of thin air.</p>
<p>Blindingly obvious &#8211; isn&#8217;t it.</p>
<p>So why would we technically model our system as if they did? My guess is that we never really thought about it &#8211; it wasn&#8217;t our job. So here&#8217;s the breaking news &#8211; if we want to successfully apply DDD we do need to think about it, it is our job.</p>
<p>Going back to the critical business question:</p>
<p>Where do customers come from?</p>
<p>In the real world, they stroll into the store. In our overused e-commerce example, they navigate to our website. New customers that haven&#8217;t used our site before don&#8217;t have any cookies or anything we can identify them with. They navigate around, browsing, maybe buying something in the end, maybe not.</p>
<p>Yet, the browsing process is interesting in its own right:</p>
<ul>
<li>Which products did they look at? </li>
<li>Did they use the search feature? </li>
<li>How long did they spend on each page? </li>
<li>Did they scroll down to see the reviews?</li>
</ul>
<p>If and when they do finally buy something, all that history is important and we&#8217;d like to maintain a connection to it.</p>
<p>Actually, even before they buy something, what they put in their cart is the interesting piece. The transition from cart to checkout is another interesting piece. Do they actually complete the checkout process, or do they abandon it midway through?</p>
<p>Add to that when we ask/force them to create a user/login in our system.</p>
<p>Are they actually a customer if they haven&#8217;t bought anything?</p>
<p>We&#8217;re beginning to get an inkling that almost every activity that results in the creation of an entity or storing of additional information can be traced to a transition from a previous business state.</p>
<p>In any transition, the previous state is the aggregate root.</p>
<h3>In the beginning&#8230;</h3>
<p>Let&#8217;s start at the very beginning then &#8211; someone came to our site. Either they navigated here from some other web page, they clicked on an email link someone sent them, or they typed in our URL. This can be designed as follows:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">using</span> (ISession s = sf.OpenSession())</pre>
<pre><span class="lnum">   2:  </span><span class="kwrd">using</span> (ITransaction tx = s.BeginTransaction())</pre>
<pre class="alt"><span class="lnum">   3:  </span>{</pre>
<pre><span class="lnum">   4:  </span>   var referrer = s.Get&lt;Referrer&gt;(msg.URL);</pre>
<pre class="alt"><span class="lnum">   5:  </span>   referrer.BroughtVisitorWithIp(msg.IpAddress);</pre>
<pre><span class="lnum">   6:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">   7:  </span>   tx.Commit();</pre>
<pre><span class="lnum">   8:  </span>}</pre>
<pre class="alt"><span class="lnum">   9:  </span>&nbsp;</pre>
</div>
<p>And our referrer code could look something like this:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">void</span> BroughtVisitorWithIp(<span class="kwrd">string</span> ipAddress)</pre>
<pre><span class="lnum">   2:  </span>{</pre>
<pre class="alt"><span class="lnum">   3:  </span>   <span class="kwrd">var</span> visitor = <span class="kwrd">new</span> Visitor(ipAddress);</pre>
<pre><span class="lnum">   4:  </span>   <span class="kwrd">this</span>.NewVisitors.Add(visitor);</pre>
<pre class="alt"><span class="lnum">   5:  </span>}</pre>
<pre><span class="lnum">   6:  </span>&nbsp;</pre>
</div>
<p>This follows the technical guidance we saw at the beginning.</p>
<p>It also allows us to track which referrer is bringing us which visitors, through tracking those visitors as they become shoppers (by putting stuff in their cart), finally seeing which become customers.</p>
<p>We can solve the situation of not having a referrer by implementing the null object pattern which is well supported by all the standard object-relational mappers these days.</p>
<h3>How it works internally</h3>
<p>When we call a method on a persistent entity retrieved by the object-relational mapper, and the entity modifies its state like when it adds a new entity to one of its collection properties, when the transaction commits, here&#8217;s what happens:</p>
<p>The mapper sees that the persistent entity is dirty, specifically, that its collection property was modified, and notices that there is an object in there that isn&#8217;t persistent. At that point, the mapper knows to persist the new entity without us ever having to explicitly tell it to do so. This is sometimes known as &#8220;persistence by reachability&#8221;.</p>
<h3>Where validation happens</h3>
<p>Let&#8217;s consider the relatively trivial rule that says that a user name can&#8217;t contain a space.</p>
<p>Also, keep in mind that a registered user is the result of a transition from a visitor.</p>
<p>Here&#8217;s *one* way of doing that:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">class</span> Visitor</pre>
<pre><span class="lnum">   2:  </span>{</pre>
<pre class="alt"><span class="lnum">   3:  </span>   <span class="kwrd">public</span> <span class="kwrd">void</span> Register(<span class="kwrd">string</span> username, <span class="kwrd">string</span> password)</pre>
<pre><span class="lnum">   4:  </span>   {</pre>
<pre class="alt"><span class="lnum">   5:  </span>      <span class="kwrd">if</span> (username.Contains(<span class="str">" "</span>))</pre>
<pre><span class="lnum">   6:  </span>      {</pre>
<pre class="alt"><span class="lnum">   7:  </span>         DomainEvents.Raise&lt;UsernameCantContainSpace&gt;();</pre>
<pre><span class="lnum">   8:  </span>         <span class="kwrd">return</span>;</pre>
<pre class="alt"><span class="lnum">   9:  </span>      }</pre>
<pre><span class="lnum">  10:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  11:  </span>      <span class="kwrd">var</span> user = <span class="kwrd">new</span> User(username, password);</pre>
<pre><span class="lnum">  12:  </span>      <span class="kwrd">this</span>.RegisteredUser = u;</pre>
<pre class="alt"><span class="lnum">  13:  </span>   }</pre>
<pre><span class="lnum">  14:  </span>}</pre>
<pre class="alt"><span class="lnum">  15:  </span>&nbsp;</pre>
</div>
<p>This actually isn&#8217;t representative of most of the rules that will be found in the domain model, but it illustrates a way of preventing an entity from being created without our service layer needing to know anything. All the service layer does is get the visitor object and call the Register method.</p>
<p>Validation of string lengths, data ranges, etc is not domain logic and is best handled elsewhere (and a topic for a different post). The same goes for uniqueness.</p>
<h3>Summary</h3>
<p>The most important thing to keep in mind is that if your service layer is newing up some entity and saving it &#8211; that entity isn&#8217;t an aggregate root *in that use case*. As we saw above, in the original creation of the Visitor entity by the Referrer, the visitor class wasn&#8217;t the aggregate root. Yet, in the user registration use case, the Visitor entity was the aggregate root.</p>
<p>Aggregate roots aren&#8217;t a structural property of the domain model.</p>
<p>And in any case, don&#8217;t go saving entities in your service layer &#8211; let the domain model manage its own state. The domain model doesn&#8217;t need any references to repositories, services, units of work, or anything else to manage its state.</p>
<p>If you do all this, you&#8217;ll also be able to harness the technique of fetching strategies to get the best performance out of your domain model by representing your use cases as interfaces on the domain model like IRegisterUsers (implemented by Visitor) and IBringVisitors (implemented by Referrer).</p>
<p>And spending some time on business analysis doesn&#8217;t hurt either &#8211; unless customers really do fall out of the sky in your world <img src='http://www.udidahan.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2009/06/29/dont-create-aggregate-roots/feed/</wfw:commentRss>
		<slash:comments>66</slash:comments>
		</item>
		<item>
		<title>Domain Events &#8211; Salvation</title>
		<link>http://www.udidahan.com/2009/06/14/domain-events-salvation/</link>
		<comments>http://www.udidahan.com/2009/06/14/domain-events-salvation/#comments</comments>
		<pubDate>Sun, 14 Jun 2009 06:25:31 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://www.udidahan.com/?p=1029</guid>
		<description><![CDATA[
I&#8217;ve been hearing from people that have had a great deal of success using the Domain Event pattern and the infrastructure I previously provided for it in Domain Events &#8211; Take 2. I&#8217;m happy to say that I&#8217;ve got an improvement that I think you&#8217;ll like. The main change is that now we&#8217;ll be taking [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.udidahan.com/wp-content/uploads/sphere1.jpg" alt="sphere" title="sphere" width="198" height="201"  style="border-right: 0px; border-top: 0px; margin: 0px 10px; border-left: 0px; border-bottom: 0px" align="right"/><br />
I&#8217;ve been hearing from people that have had a great deal of success using the Domain Event pattern and the infrastructure I previously provided for it in <a href="http://www.udidahan.com/2008/08/25/domain-events-take-2/">Domain Events &#8211; Take 2</a>. I&#8217;m happy to say that I&#8217;ve got an improvement that I think you&#8217;ll like. The main change is that now we&#8217;ll be taking an approach that is reminiscent to how events are published in <a href="http://www.NServiceBus.com">NServiceBus</a>.</p>
<h3>Background</h3>
<p>Before diving right into the code, I wanted to take a minute to recall how we got here.</p>
<p>It started by looking for <a href="http://www.udidahan.com/2008/02/29/how-to-create-fully-encapsulated-domain-models/">how to create fully encapsulated domain models</a>.</p>
<p>The main assertion being that you do *not* need to inject anything into your domain entities.</p>
<p>Not services. Not repositories. Nothing.</p>
<p>Just pure domain model goodness.</p>
<h3>Make Roles Explicit</h3>
<p>I&#8217;m going to take the advice I so often give. A domain event is a role, and thus should be represented explicitly:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">interface</span> IDomainEvent {}</pre>
</div>
<p>If this reminds you of the IMessage marker interface in nServiceBus, you&#8217;re beginning to see where this is going&#8230;</p>
<h3>How to define domain events</h3>
<p>A domain event is just a simple POCO that represents an interesting occurence in the domain. For example:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">class</span> CustomerBecamePreferred : IDomainEvent </pre>
<pre><span class="lnum">   2:  </span>{</pre>
<pre class="alt"><span class="lnum">   3:  </span>    <span class="kwrd">public</span> Customer Customer { get; set; }</pre>
<pre><span class="lnum">   4:  </span>}</pre>
</div>
<p>For those of you concerned about the number of events you may have, and therefore are thinking about bunching up these events by namespaces or things like that, slow down. The number of domain events and their cohesion is directly related to that of the domain model. </p>
<p>If you feel the need to split your domain events up, there&#8217;s a good chance that you should be looking at splitting your domain model too. This is the bottom-up way of identifying bounded contexts.</p>
<h3>How to raise domain events</h3>
<p>In your domain entities, when a significant state change happens you&#8217;ll want to raise your domain events like this:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">class</span> Customer</pre>
<pre><span class="lnum">   2:  </span>{</pre>
<pre class="alt"><span class="lnum">   3:  </span>    <span class="kwrd">public</span> <span class="kwrd">void</span> DoSomething()</pre>
<pre><span class="lnum">   4:  </span>    {</pre>
<pre class="alt"><span class="lnum">   5:  </span>        DomainEvents.Raise(<span class="kwrd">new</span> CustomerBecamePreferred() { Customer = <span class="kwrd">this</span> });</pre>
<pre><span class="lnum">   6:  </span>    }</pre>
<pre class="alt"><span class="lnum">   7:  </span>}</pre>
</div>
<p>We&#8217;ll look at the DomainEvents class in just a second, but I&#8217;m guessing that some of you are wondering &#8220;how did that entity get a reference to that?&#8221; The answer is that DomainEvents is a static class. &#8220;OMG, static?! But doesn&#8217;t that hurt testability?!&#8221; No, it doesn&#8217;t. Here, look:</p>
<h3>Unit testing with domain events</h3>
<p>One of the things we&#8217;d like to check when unit testing our domain entities is that the appropriate events are raised along with the corresponding state changes. Here&#8217;s an example:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">void</span> DoSomethingShouldMakeCustomerPreferred()</pre>
<pre><span class="lnum">   2:  </span>{</pre>
<pre class="alt"><span class="lnum">   3:  </span>    var c = <span class="kwrd">new</span> Customer();</pre>
<pre><span class="lnum">   4:  </span>    Customer preferred = <span class="kwrd">null</span>;</pre>
<pre class="alt"><span class="lnum">   5:  </span>&nbsp;</pre>
<pre><span class="lnum">   6:  </span>    DomainEvents.Register&lt;CustomerBecamePreferred&gt;(</pre>
<pre class="alt"><span class="lnum">   7:  </span>        p =&gt; preferred = p.Customer</pre>
<pre><span class="lnum">   8:  </span>            );</pre>
<pre class="alt"><span class="lnum">   9:  </span>&nbsp;</pre>
<pre><span class="lnum">  10:  </span>    c.DoSomething();</pre>
<pre class="alt"><span class="lnum">  11:  </span>    Assert(preferred == c &amp;&amp; c.IsPreferred);</pre>
<pre><span class="lnum">  12:  </span>}</pre>
</div>
<p>As you can see, the static DomainEvents class is used in unit tests as well. Also notice that you don&#8217;t need to mock anything &#8211; pure testable bliss.</p>
<h3>Who handles domain events</h3>
<p>First of all, consider that when some service layer object calls the DoSomething method of the Customer class, it doesn&#8217;t necessarily know which, if any, domain events will be raised. All it wants to do is its regular schtick:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">void</span> Handle(DoSomethingMessage msg)</pre>
<pre><span class="lnum">   2:  </span>{</pre>
<pre class="alt"><span class="lnum">   3:  </span>    <span class="kwrd">using</span> (ISession session = SessionFactory.OpenSession())</pre>
<pre><span class="lnum">   4:  </span>    <span class="kwrd">using</span> (ITransaction tx = session.BeginTransaction())</pre>
<pre class="alt"><span class="lnum">   5:  </span>    {</pre>
<pre><span class="lnum">   6:  </span>        var c = session.Get&lt;Customer&gt;(msg.CustomerId);</pre>
<pre class="alt"><span class="lnum">   7:  </span>        c.DoSomething();</pre>
<pre><span class="lnum">   8:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">   9:  </span>        tx.Commit();</pre>
<pre><span class="lnum">  10:  </span>    }</pre>
<pre class="alt"><span class="lnum">  11:  </span>}</pre>
</div>
<p>The above code complies with the Single Responsibility Principle, so the business requirement which states that when a customer becomes preferred, they should be sent an email belongs somewhere else. </p>
<p>Notice that the key word in the requirement &#8211; &#8220;when&#8221;.</p>
<p>Any time you see that word in relation to your domain, consider modeling it as a domain event.</p>
<p>So, here&#8217;s the handling code:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">class</span> CustomerBecamePreferredHandler : Handles&lt;CustomerBecamePreferred&gt;</pre>
<pre><span class="lnum">   2:  </span>{ </pre>
<pre class="alt"><span class="lnum">   3:  </span>   <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(CustomerBecamePreferred args)</pre>
<pre><span class="lnum">   4:  </span>   {</pre>
<pre class="alt"><span class="lnum">   5:  </span>      <span class="rem">// send email to args.Customer</span></pre>
<pre><span class="lnum">   6:  </span>   }</pre>
<pre class="alt"><span class="lnum">   7:  </span>} </pre>
</div>
<p>This code will run no matter which service layer object we came in through.</p>
<p>Here&#8217;s the interface it implements:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">interface</span> Handles&lt;T&gt; <span class="kwrd">where</span> T : IDomainEvent</pre>
<pre><span class="lnum">   2:  </span>{</pre>
<pre class="alt"><span class="lnum">   3:  </span>    <span class="kwrd">void</span> Handle(T args); </pre>
<pre><span class="lnum">   4:  </span>} </pre>
</div>
<p>Fairly simple.</p>
<p>Please be aware that the above code will be run on the same thread within the same transaction as the regular domain work so you should avoid performing any blocking activities, like using SMTP or web services. Instead, prefer using one-way messaging to communicate to something else which does those blocking activities.</p>
<p>Also, you can have multiple classes handling the same domain event. If you need to send email *and* call the CRM system *and* do something else, etc, you don&#8217;t need to change any code &#8211; just write a new handler. This keeps your system quite a bit more stable than if you had to mess with the original handler or, heaven forbid, service layer code.</p>
<h3>Where domain event handlers go</h3>
<p>These handler classes do not belong in the domain model.</p>
<p>Nor do they belong in the service layer.</p>
<p>Well, that&#8217;s not entirely accurate &#8211; you see, there&#8217;s no *the* service layer. There is the part that accepts messages from clients and calls methods on the domain model. And there is another, independent part that handles events from the domain. Both of these will probably make use of a message bus, but that implementation detail shouldn&#8217;t deter you from keeping each in their own package.</p>
<h3>The infrastructure</h3>
<p>I know you&#8217;ve been patient, reading through all my architectural blah-blah, so here it is:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> DomainEvents</pre>
<pre><span class="lnum">   2:  </span>{ </pre>
<pre class="alt"><span class="lnum">   3:  </span>    [ThreadStatic] <span class="rem">//so that each thread has its own callbacks</span></pre>
<pre><span class="lnum">   4:  </span>    <span class="kwrd">private</span> <span class="kwrd">static</span> List&lt;Delegate&gt; actions;</pre>
<pre class="alt"><span class="lnum">   5:  </span>&nbsp;</pre>
<pre><span class="lnum">   6:  </span>    <span class="kwrd">public</span> <span class="kwrd">static</span> IContainer Container { get; set; } <span class="rem">//as before</span></pre>
<pre class="alt"><span class="lnum">   7:  </span>&nbsp;</pre>
<pre><span class="lnum">   8:  </span>    <span class="rem">//Registers a callback for the given domain event</span></pre>
<pre class="alt"><span class="lnum">   9:  </span>    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Register&lt;T&gt;(Action&lt;T&gt; callback) <span class="kwrd">where</span> T : IDomainEvent</pre>
<pre><span class="lnum">  10:  </span>    {</pre>
<pre class="alt"><span class="lnum">  11:  </span>       <span class="kwrd">if</span> (actions == <span class="kwrd">null</span>)</pre>
<pre><span class="lnum">  12:  </span>          actions = <span class="kwrd">new</span> List&lt;Delegate&gt;();</pre>
<pre class="alt"><span class="lnum">  13:  </span>&nbsp;</pre>
<pre><span class="lnum">  14:  </span>       actions.Add(callback);</pre>
<pre class="alt"><span class="lnum">  15:  </span>   }</pre>
<pre><span class="lnum">  16:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  17:  </span>   <span class="rem">//Clears callbacks passed to Register on the current thread</span></pre>
<pre><span class="lnum">  18:  </span>   <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> ClearCallbacks ()</pre>
<pre class="alt"><span class="lnum">  19:  </span>   {</pre>
<pre><span class="lnum">  20:  </span>       actions = <span class="kwrd">null</span>;</pre>
<pre class="alt"><span class="lnum">  21:  </span>   }</pre>
<pre><span class="lnum">  22:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  23:  </span>   <span class="rem">//Raises the given domain event</span></pre>
<pre><span class="lnum">  24:  </span>   <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Raise&lt;T&gt;(T args) <span class="kwrd">where</span> T : IDomainEvent</pre>
<pre class="alt"><span class="lnum">  25:  </span>   {</pre>
<pre><span class="lnum">  26:  </span>      <span class="kwrd">if</span> (Container != <span class="kwrd">null</span>)</pre>
<pre class="alt"><span class="lnum">  27:  </span>         <span class="kwrd">foreach</span>(var handler <span class="kwrd">in</span> Container.ResolveAll&lt;Handles&lt;T&gt;&gt;())</pre>
<pre><span class="lnum">  28:  </span>            handler.Handle(args);</pre>
<pre class="alt"><span class="lnum">  29:  </span>&nbsp;</pre>
<pre><span class="lnum">  30:  </span>      <span class="kwrd">if</span> (actions != <span class="kwrd">null</span>)</pre>
<pre class="alt"><span class="lnum">  31:  </span>          <span class="kwrd">foreach</span> (var action <span class="kwrd">in</span> actions)</pre>
<pre><span class="lnum">  32:  </span>              <span class="kwrd">if</span> (action <span class="kwrd">is</span> Action&lt;T&gt;)</pre>
<pre class="alt"><span class="lnum">  33:  </span>                  ((Action&lt;T&gt;)action)(args);</pre>
<pre><span class="lnum">  34:  </span>   }</pre>
<pre class="alt"><span class="lnum">  35:  </span>} </pre>
</div>
<p>Notice that while this class *can* use a container, the container isn&#8217;t needed for unit tests which use the Register method.</p>
<p>When used server side, please make sure that you add a call to ClearCallbacks in your infrastructure&#8217;s end of message processing section. In nServiceBus this is done with a message module like the one below:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">class</span> DomainEventsCleaner : IMessageModule</pre>
<pre><span class="lnum">   2:  </span>{ </pre>
<pre class="alt"><span class="lnum">   3:  </span>    <span class="kwrd">public</span> <span class="kwrd">void</span> HandleBeginMessage() { }</pre>
<pre><span class="lnum">   4:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">   5:  </span>    <span class="kwrd">public</span> <span class="kwrd">void</span> HandleEndMessage()</pre>
<pre><span class="lnum">   6:  </span>    {</pre>
<pre class="alt"><span class="lnum">   7:  </span>        DomainEvents.ClearCallbacks();</pre>
<pre><span class="lnum">   8:  </span>    }</pre>
<pre class="alt"><span class="lnum">   9:  </span>}</pre>
</div>
<p>The main reason for this cleanup is that someone just might want to use the Register API in their original service layer code rather than writing a separate domain event handler.</p>
<h3>Summary</h3>
<p>Like all good things in life, 3rd time&#8217;s the charm.</p>
<p>It took a couple of iterations, and the API did change quite a bit, but the overarching theme has remained the same &#8211; keep the domain model focused on domain concerns. While some might say that there&#8217;s only a slight technical difference between calling a service (IEmailService) and using an event to dispatch it elsewhere, I beg to differ.</p>
<p>These domain events are a part of the ubiquitous language and should be represented explicitly.</p>
<p>CustomerBecamePreferred is nothing at all like IEmailService.</p>
<p>In working with your domain experts or just going through a requirements document, pay less attention to the nouns and verbs that Object-Oriented Analysis &#038; Design call attention to, and keep an eye out for the word &#8220;when&#8221;. It&#8217;s a critically important word that enables us to model important occurrences and state changes.</p>
<p>What do you think? Are you already using this approach? Have you already tried it and found it broken in some way? Do you have any suggestions on how to improve it?</p>
<p>Let me know &#8211; leave a comment below.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2009/06/14/domain-events-salvation/feed/</wfw:commentRss>
		<slash:comments>113</slash:comments>
		</item>
		<item>
		<title>ALT.NET DDD Podcast</title>
		<link>http://www.udidahan.com/2009/01/26/altnet-ddd-podcast/</link>
		<comments>http://www.udidahan.com/2009/01/26/altnet-ddd-podcast/#comments</comments>
		<pubDate>Mon, 26 Jan 2009 20:36:08 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[DDD]]></category>
		<category><![CDATA[OO]]></category>

		<guid isPermaLink="false">http://www.udidahan.com/2009/01/26/altnet-ddd-podcast/</guid>
		<description><![CDATA[ I finally got around to listening to the alt.net podcast on domain driven design and heard Rob Conery telling about his experiences with DDD. I&#8217;ve met a fair amount of developers that went through a similar process and thought that I could help fix some of the common misconceptions that pop up when developers [...]]]></description>
			<content:encoded><![CDATA[<p> I finally got around to listening to the alt.net podcast on domain driven design and heard Rob Conery telling about his experiences with DDD. I&#8217;ve met a fair amount of developers that went through a similar process and thought that I could help fix some of the common misconceptions that pop up when developers start down the DDD path.</p>
<p><img style="border-right: 0px; border-top: 0px; margin: 0px 0px 0px 20px; border-left: 0px; border-bottom: 0px" height="308" alt="fish_boy_cat_different_perspectives" src="http://www.udidahan.com/wp-content/uploads/fish-boy-cat-different-perspectives.jpg" width="504" border="0"></p>
<h3>Factory methods on repositories</h3>
<p>In the podcast, Rob describes an ecommerce application with orders, customers, products &#8211; all the stuff you&#8217;ve come to expect. In his pre-DDD design, the order class had multiple constructors representing different rules. Feeling the pain in testing and maintainability, Rob looked to use DDD principles. What he did to get rid of these constructors was to make use of the repository by creating methods for the various cases, like <font face="Courier New" size="2">OrderRepository.CreateOrderForGovernmentCustomer(/*data*/);</font> .</p>
<p>While this is better than the multiple constructors, it still has a way to go. Analyzing what&#8217;s going on here we understand that the way the order is created is dependent upon who the user is. The rules dictating terms of payment are probably different for government customers. Not only that but we know that the order created needs to be connected to that user.</p>
<h3>Aggregate Roots &amp; Polymorphism</h3>
<p>For all these reasons, it looks like user, or customer, is our aggregate root. Thus, rather than our service layer calling the above method on the repository, we first get the user object by id, then create the order like so:</p>
<blockquote><p><font face="Courier New" size="2">IUser u = session.Get&lt;IUser&gt;(IdOfUserLoggedIn);<br />u.CreateOrder(/* data */);</font></p></blockquote>
<p>This way, our service layer doesn&#8217;t need to perform all sorts of business logic (if the user is a gov&#8217;t user, do this, a corporate customer, do that, etc). All of that gets encapsulated by the domain. By leveraging some polymorphism, the session will return an instance of the correct class when we ask it for a user by id. Thus, logic relating to how gov&#8217;t users create orders is encapsulated in the GovernmentUser class.</p>
<p>I&#8217;ve found that this pattern of having polymorphic aggregate roots is very useful and broadly applicable.</p>
<h3>Bounded Contexts</h3>
<p>Further into the podcast, Rob talks about how separating his system into 2 bounded contexts simplified the code greatly. The understanding that accepting an order and fulfilling an order require different logic, different data, and thus, different domain model objects is DDD at its finest.</p>
<p>However, when talking about the total cost of the order, it wasn&#8217;t clear what was responsible for that. From a pure programming perspective, we might think that Total was simply a property on Order or, at most, a GetTotal() method. Yet by looking at what is involved in calculating the total of an order, a different picture emerges:</p>
<p>The total cost of an order obviously includes all relevant taxes. We need to take into account state and federal taxes, tax-free items at each level, etc. There&#8217;s a fair amount of logic here. Once we start to take into account promotions like &#8220;buy one, get one free&#8221;, things get even more involved. There are also cases where refunds are applied within the same order that impact the total and tax (no tax on refunds). Finally, when we include shipping charges, tax on shipping, and other rules between all of the above, it&#8217;s clear that if we put all of this in a single method, we&#8217;ve got ourselves a big bloated sack of &#8230; well, you get the picture.</p>
<p>Separating all of this logic into different bounded contexts makes sense.</p>
<p>That is, until you think about how you&#8217;re going to take these and stitch out of them a single result shown to the user. This is the advanced side of DDD and ties into SOA, so I&#8217;ll leave it for a different post.</p>
<h3>In Closing</h3>
<p>Working with DDD provides a great deal of value by tying our code much more closely to business concepts and encapsulating business rules in the domain model.</p>
<p>Starting down the DDD path is intuitive and the code that results (like u.CreateOrder) is very understandable. Yet, as more DDD principles like Bounded Contexts are put to use, developers often find themselves in unfamiliar, less-intuitive waters. This is to be expected. </p>
<p>Some developers (and vendors) look at DDD as nothing more than the domain model and repository patterns. The truth is that they&#8217;re just the beginning. </p>
<p>I hope that this post has given those of you just starting down the DDD path some feeling for how deep the rabbit hole goes, and I assure you that there are patterns in place to answer all your questions. While those beginning DDD often say that it gives names to things they&#8217;ve always been doing, or always wanted to do, I can assure you that the further down you go, that is less and less the case.</p>
<p>Be ready to have some basic architectural assumptions shaken <img src='http://www.udidahan.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2009/01/26/altnet-ddd-podcast/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>DDD &amp; Many to Many Object Relational Mapping</title>
		<link>http://www.udidahan.com/2009/01/24/ddd-many-to-many-object-relational-mapping/</link>
		<comments>http://www.udidahan.com/2009/01/24/ddd-many-to-many-object-relational-mapping/#comments</comments>
		<pubDate>Sat, 24 Jan 2009 19:47:02 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Databases]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://www.udidahan.com/2009/01/24/ddd-many-to-many-object-relational-mapping/</guid>
		<description><![CDATA[ The ability to map entity relationships is broadly supported by many O/RM tools. For some reason, though, many developers run into issues when trying to map a many-to-many relationship between entities. Although much has already been written about the technological aspects of it, I thought I&#8217;d take more of an architectural / DDD perspective [...]]]></description>
			<content:encoded><![CDATA[<p><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; margin: 0px 0px 10px 10px; border-right-width: 0px" height="150" alt="many to many" src="http://www.udidahan.com/wp-content/uploads/image52.png" width="150" align="right" border="0"> The ability to map entity relationships is broadly supported by many O/RM tools. For some reason, though, many developers run into issues when trying to map a many-to-many relationship between entities. Although much has already been written about the technological aspects of it, I thought I&#8217;d take more of an architectural / DDD perspective on it here.</p>
<h3>Value Objects Don&#8217;t Count</h3>
<p>While the canonical example presented is Customer -&gt; Address, and has a good treatment <a href="http://devlicio.us/blogs/billy_mccafferty/archive/2008/07/11/when-to-use-many-to-one-s-vs-many-to-many-with-nhibernate.aspx">here</a> for nHibernate, it isn&#8217;t architecturally representative.</p>
<p>Addresses are value objects. What this means is that if we have to instance of the Address class, and they both have the same business data, they are semantically equivalent. Customers, on the other had, are not value objects &#8211; they&#8217;re entities. If we have two customers with the same business data (both of them called Bob Smith), that does not mean they are semantically equivalent &#8211; they are not the same person.</p>
<h3>All Entities</h3>
<p>Therefore, for our purposes here we&#8217;ll use something different. Say we have an entity called Job which is something that a company wants to hire for. It has a title, description, skill level, and a bunch of other data. Say we also have another entity called Job Board which is where the company posts jobs so that applicants can see them, like Monster.com. A job board has a name, description, web site, referral fee, and a bunch of other data.</p>
<p>A job can be posted to multiple job boards. And a job board can have multiple jobs posted. A regular many to many relationship. At this point, we&#8217;re not even going to complicate the association.</p>
<p>This is simply represented in the DB with an association table containing two columns for each of the entity tables&#8217; ids. </p>
<p>In the domain model, developers can also represent this with the Job class containing a list of JobBoard instances, and the JobBoard class containing a list of jobs.</p>
<p>It&#8217;s intuitive. Simple. Easy to implement. And wrong.</p>
<p>In order to make intelligent DDD choices, we&#8217;re going to first take what may seem to be a tangential course, but I assure you that your aggregate roots depend on it.</p>
<h3>Moving forward with our example</h3>
<p>Let&#8217;s say the user picks a job, and then ticks off the job boards where they want the job posted, and clicks submit.</p>
<p>For simplicity&#8217;s sake, at this point, let&#8217;s ignore the communication with the actual job sites, assuming that if we can get the association into the DB, magic will happen later causing the job to appear on all the sites.</p>
<p>Our well-intentioned developer takes the job ID, and all the job board IDs, opens a transaction, gets the job object, gets the job board objects, adds all the job board objects to the job, and commits, as follows:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ -->
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span>        <span class="kwrd">public</span> <span class="kwrd">void</span> PostJobToBoards(Guid jobId, <span class="kwrd">params</span> Guid[] boardIds)</pre>
<pre><span class="lnum">   2:  </span>        {</pre>
<pre class="alt"><span class="lnum">   3:  </span>            <span class="kwrd">using</span> (ISession s = <span class="kwrd">this</span>.SessionFactory.OpenSession())</pre>
<pre><span class="lnum">   4:  </span>            <span class="kwrd">using</span> (ITransaction tx = s.BeginTransaction())</pre>
<pre class="alt"><span class="lnum">   5:  </span>            {</pre>
<pre><span class="lnum">   6:  </span>                var job = s.Get&lt;Job&gt;(jobId);</pre>
<pre class="alt"><span class="lnum">   7:  </span>                var boards = <span class="kwrd">new</span> List&lt;JobBoard&gt;();</pre>
<pre><span class="lnum">   8:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">   9:  </span>                <span class="kwrd">foreach</span>(Guid id <span class="kwrd">in</span> boardIds)</pre>
<pre><span class="lnum">  10:  </span>                    boards.Add(s.Get&lt;JobBoard&gt;(id));</pre>
<pre class="alt"><span class="lnum">  11:  </span>&nbsp;</pre>
<pre><span class="lnum">  12:  </span>                job.PostTo(boards);</pre>
<pre class="alt"><span class="lnum">  13:  </span>&nbsp;</pre>
<pre><span class="lnum">  14:  </span>                tx.Commit();</pre>
<pre class="alt"><span class="lnum">  15:  </span>            }</pre>
<pre><span class="lnum">  16:  </span>        }</pre>
</div>
<p>In this code, Job is our aggregate root. You can see that is the case since Job is the entry point that the service layer code uses to interact with the domain model. Soon we&#8217;ll see why this is wrong.</p>
<p>** Notice that in this service layer code, our well-intentioned developer is following the rule that while you can get as many objects as you like, you are only allowed one method call on one domain object. The code called in line 12 is what you&#8217;d pretty much expect:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span>        <span class="kwrd">public</span> <span class="kwrd">void</span> PostTo(IList&lt;JobBoard&gt; boards)</pre>
<pre><span class="lnum">   2:  </span>        {</pre>
<pre class="alt"><span class="lnum">   3:  </span>            <span class="kwrd">foreach</span>(JobBoard jb <span class="kwrd">in</span> boards)</pre>
<pre><span class="lnum">   4:  </span>            {</pre>
<pre class="alt"><span class="lnum">   5:  </span>                <span class="kwrd">this</span>.JobBoards.Add(jb);</pre>
<pre><span class="lnum">   6:  </span>                jb.Jobs.Add(<span class="kwrd">this</span>);</pre>
<pre class="alt"><span class="lnum">   7:  </span>            }</pre>
<pre><span class="lnum">   8:  </span>        }</pre>
</div>
<p>Only that as we were committing, someone deleted one of the job boards just then. Or that someone updated the job board causing a concurrency conflict. Or anything that would cause one single association to not be created.</p>
<p>That would cause the whole transaction to fail and all changes to roll back.</p>
<p>Rightly so, thinks our well-intentioned developer.</p>
<p>But users don&#8217;t think like well-intentioned developers.</p>
<h3>Partial Failures</h3>
<p>If I were to go to the grocery store with the list my wife gave me, finding that they&#8217;re out of hazelnuts (the last item on the list), would NOT buy all the other groceries and go home empty handed, what do you think would happen?</p>
<p>Right. That&#8217;s how users look at us developers. Before running off and writing a bunch of code, we need to understand the business semantics of users actions, including asking about partial failures.</p>
<p>The list isn&#8217;t a unit of work that needs to succeed or rollback atomically. It&#8217;s actually many units of work. I mean, I wouldn&#8217;t want my wife to send me to the store 10 times to buy 10 items, so the list is really just a kind of user shortcut. Therefore, in the job board scenario, each job to job board connection is its own transaction.</p>
<p>This is more common than you might think.</p>
<p>Once you go looking for cases where the domain is forgiving of partial failures, you may start seeing more and more of them.</p>
<h3>Aggregate Roots</h3>
<p>In the original transaction where we tried to connect many job boards to a single job, we saw that the single job is the aggregate root. However, once we have multiple transactions, each connecting one job and one job board, the job board is just as likely an aggregate root as the job.</p>
<p>We can do&nbsp;&nbsp; <font face="Courier">jobBoard.Post(job);</font>&nbsp;&nbsp;&nbsp; or&nbsp;&nbsp;&nbsp;&nbsp; <font face="Courier">job.PostTo(jobBoard);</font></p>
<p>But we need just a bit more analysis to come to the right decision.</p>
<p>While we could just leave the bi-directional/circular dependency between them, it would be preferable if we could make it uni-directional instead. To do that, we need to understand their relationship:</p>
<p>If there was no such thing as &#8220;job&#8221;, would there be meaning to &#8220;job board&#8221; ? Probably not.</p>
<p>If there was no such thing as &#8220;job board&#8221;, would there be meaning to &#8220;job&#8221; ? Probably. Yes. Our company can handle the hiring process of a job regardless of whether the candidate came in through Monster.com or not.</p>
<p>From this we understand that the uni-directional relationship can be modelled as one-to-many from job board to job. The Job class would no longer have a collection of Job Board objects. In fact, it could even be in an assembly separate from Job Board and not reference Job Board in any way. Job Board, on the other hand, would still have a collection of Job objects.</p>
<p>Going back to the code above we see that the right choice is&nbsp;&nbsp; <font face="Courier">jobBoard.Post(job);</font>&nbsp;&nbsp;&nbsp; </p>
<p>Job Board is the aggregate root in this case. Also, the many-to-many mapping has now dissolved, leaving behind a single one-to-many mapping.</p>
<p>Let that sink in a second.</p>
<h3>But Wait&#8230;</h3>
<p>While the GUI showing which jobs are posted on a given job board are well served by the above decision (simply traversing the object graph from Job Board to its collection of Jobs), that&#8217;s not the whole story. Another GUI needs to show administrative users which Job Boards a given Job has been posted to. Since we no longer have the domain-level connection, we can&#8217;t traverse myJob.JobBoards.</p>
<p>Our only option is to perform a query. That&#8217;s not so bad, but not as pretty as object traversal. </p>
<p>The real benefit is in chopping apart the Gordian M-to-N mapping knot and getting a cleaner, more well factored domain model. </p>
<p>That gives us much greater leverage for bigger, system-level decomposition.</p>
<p>We&#8217;re now all set to move up to a pub/sub solution between these aggregate roots, effectively upgrading them to Bounded Contexts. From there, we can move to full-blown internet-scale caching with REST for extra scalability on showing a job board with all its jobs.</p>
<h3>In Closing</h3>
<p>We often look at many-to-many relationships just like any other relationship. And from a purely technical perspective, we&#8217;re not wrong. However, the business reality around these relationships is often very different &#8211; forgiving of partial failures, to the point of actually requiring them.</p>
<p>Since the business folks who provide us with requirements rarely think of failure scenarios, they don&#8217;t specify that &#8220;between these two entities here, I don&#8217;t want transactional atomicity&#8221; (rolling our technical eyes &#8211; the idiots [sarcasm, just to make sure you don't misread me]).</p>
<p>Yet, if we were to spell out what the system will do under failure conditions when transactionally atomic, those same business folks will be rolling our eyes back to us.</p>
<p>What I&#8217;ve found surprises some DDD practitioners is how critical this issue really is to arriving at the correct aggregate roots and bounded contexts. </p>
<p>It&#8217;s also simple, and practical, so you won&#8217;t be offending the YAGNI police. </p>
<hr size="1">
<h3>Related Content</h3>
<blockquote>
<p><a href="http://www.udidahan.com/2008/02/15/from-crud-to-domain-driven-fluency/">From CRUD to Domain-Driven Fluency</a></p>
<p><a href="http://www.udidahan.com/2007/09/12/podcast-domain-models-soa-and-the-single-version-of-the-truth/">[Podcast] Domain Models, SOA, and The Single Version of the Truth</a></p>
</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2009/01/24/ddd-many-to-many-object-relational-mapping/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>Domain Events &#8211; Take 2</title>
		<link>http://www.udidahan.com/2008/08/25/domain-events-take-2/</link>
		<comments>http://www.udidahan.com/2008/08/25/domain-events-take-2/#comments</comments>
		<pubDate>Mon, 25 Aug 2008 13:40:41 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://www.udidahan.com/2008/08/25/domain-events-take-2/</guid>
		<description><![CDATA[Update: The next post in this series is now online here.
My previous post on how to create fully encapsulated domain models introduced the concept of events as a core pattern of communication from the domain back to the service layer. In that post, I put up enough code to get the idea across but didn&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p><b>Update:</b> The next post in this series is now online <a href="http://www.udidahan.com/2009/06/14/domain-events-salvation/">here</a>.</p>
<p>My previous post on <a href="http://www.udidahan.com/2008/02/29/how-to-create-fully-encapsulated-domain-models/">how to create fully encapsulated domain models</a> introduced the concept of events as a core pattern of communication from the domain back to the service layer. In that post, I put up enough code to get the idea across but didn&#8217;t address issues like memory leaks and multi-threading. This post will show the solution to those two critical points.</p>
<p> <center><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="63" alt="" src="http://www.udidahan.com/wp-content/uploads/image43.png" width="500" border="0"></center>
</p>
<p>I&#8217;ve snipped out one of the events in the previous example for brevity.</p>
<h3>Previous API</h3>
<p>The previous API looked like this:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ -->
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> DomainEvents</pre>
<pre><span class="lnum">   2:  </span>{</pre>
<pre class="alt"><span class="lnum">   3:  </span>     <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">event</span> EventHandler GameReportedLost;</pre>
<pre><span class="lnum">   4:  </span>     <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> RaiseGameReportedLostEvent()</pre>
<pre class="alt"><span class="lnum">   5:  </span>     {</pre>
<pre><span class="lnum">   6:  </span>           <span class="kwrd">if</span> (GameReportedLost != <span class="kwrd">null</span>)</pre>
<pre class="alt"><span class="lnum">   7:  </span>               GameReportedLost(<span class="kwrd">null</span>, <span class="kwrd">null</span>);</pre>
<pre><span class="lnum">   8:  </span>     }</pre>
<pre class="alt"><span class="lnum">   9:  </span>&nbsp;</pre>
<pre><span class="lnum">  10:  </span>     <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">event</span> EventHandler CartIsFull;</pre>
<pre class="alt"><span class="lnum">  11:  </span>     <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> RaiseCartIsFull()</pre>
<pre><span class="lnum">  12:  </span>     {</pre>
<pre class="alt"><span class="lnum">  13:  </span>           <span class="kwrd">if</span> (CartIsFull != <span class="kwrd">null</span>)</pre>
<pre><span class="lnum">  14:  </span>               CartIsFull(<span class="kwrd">null</span>, <span class="kwrd">null</span>);</pre>
<pre class="alt"><span class="lnum">  15:  </span>     }</pre>
<pre><span class="lnum">  16:  </span>}</pre>
</div>
<p>One thing that we want to keep in the solution is that all the code to define events, their names, and the parameters they bring will be in one place &#8211; in this case, the DomainEvents class. One thing that we&#8217;d like to fix is the amount of code needed to define an event.</p>
<h3>Previous Service Layer</h3>
<p>Here&#8217;s what our previous service layer code looked like:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">class</span> AddGameToCartMessageHandler :</pre>
<pre><span class="lnum">   2:  </span>    BaseMessageHandler&lt;AddGameToCartMessage&gt;</pre>
<pre class="alt"><span class="lnum">   3:  </span>{</pre>
<pre><span class="lnum">   4:  </span>    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Handle(AddGameToCartMessage m)</pre>
<pre class="alt"><span class="lnum">   5:  </span>    {</pre>
<pre><span class="lnum">   6:  </span>        <span class="kwrd">using</span> (ISession session = SessionFactory.OpenSession())</pre>
<pre class="alt"><span class="lnum">   7:  </span>        <span class="kwrd">using</span> (ITransaction tx = session.BeginTransaction())</pre>
<pre><span class="lnum">   8:  </span>        {</pre>
<pre class="alt"><span class="lnum">   9:  </span>            ICart cart = session.Get&lt;ICart&gt;(m.CartId);</pre>
<pre><span class="lnum">  10:  </span>            IGame g = session.Get&lt;IGame&gt;(m.GameId);</pre>
<pre class="alt"><span class="lnum">  11:  </span>&nbsp;</pre>
<pre><span class="lnum">  12:  </span>            Domain.DomainEvents.GameReportedLost +=</pre>
<pre class="alt"><span class="lnum">  13:  </span>              gameReportedLost;</pre>
<pre><span class="lnum">  14:  </span>            Domain.DomainEvents.CartIsFull +=</pre>
<pre class="alt"><span class="lnum">  15:  </span>              cartIsFull;</pre>
<pre class="alt"><span class="lnum">  16:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  17:  </span>            cart.Add(g);</pre>
<pre><span class="lnum">  18:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  19:  </span>            Domain.DomainEvents.GameReportedLost -=</pre>
<pre><span class="lnum">  20:  </span>              gameReportedLost;</pre>
<pre class="alt"><span class="lnum">  21:  </span>            Domain.DomainEvents.CartIsFull -=</pre>
<pre><span class="lnum">  22:  </span>              cartIsFull;</pre>
<pre class="alt"><span class="lnum">  23:  </span>&nbsp;</pre>
<pre><span class="lnum">  24:  </span>            tx.Commit();</pre>
<pre class="alt"><span class="lnum">  25:  </span>        }</pre>
<pre><span class="lnum">  26:  </span>    }</pre>
<pre class="alt"><span class="lnum">  27:  </span>&nbsp;</pre>
<pre><span class="lnum">  28:  </span>    <span class="kwrd">private</span> EventHandler gameReportedLost = <span class="kwrd">delegate</span> { </pre>
<pre class="alt"><span class="lnum">  29:  </span>          Bus.Return((<span class="kwrd">int</span>)ErrorCodes.GameReportedLost);</pre>
<pre><span class="lnum">  30:  </span>        };</pre>
<pre class="alt"><span class="lnum">  31:  </span>&nbsp;</pre>
<pre><span class="lnum">  32:  </span>    <span class="kwrd">private</span> EventHandler cartIsFull = <span class="kwrd">delegate</span> { </pre>
<pre class="alt"><span class="lnum">  33:  </span>          Bus.Return((<span class="kwrd">int</span>)ErrorCodes.CartIsFull);</pre>
<pre><span class="lnum">  34:  </span>        };</pre>
<pre class="alt"><span class="lnum">  35:  </span>    }</pre>
<pre><span class="lnum">  36:  </span>}</pre>
</div>
<p>Another thing that should be improved is the amount of code needed in the service layer.</p>
<p>Raising an event, though, should still be fairly simple &#8211; one line of code similar to DomainEvents.RaiseGameReportedLost().</p>
<h3>New API</h3>
<p>Here&#8217;s what the new API looks like:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> DomainEvents</pre>
<pre><span class="lnum">   2:  </span>{</pre>
<pre class="alt"><span class="lnum">   3:  </span>     <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> DomainEvent&lt;IGame&gt; GameReportedLost = </pre>
<pre><span class="lnum">   4:  </span>                                          <span class="kwrd">new</span> DomainEvent&lt;IGame&gt;;</pre>
<pre class="alt"><span class="lnum">   5:  </span>&nbsp;</pre>
<pre><span class="lnum">   6:  </span>     <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> DomainEvent&lt;ICart&gt; CartIsFull=</pre>
<pre class="alt"><span class="lnum">   7:  </span>                                          <span class="kwrd">new</span> DomainEvent&lt;ICart&gt;;</pre>
<pre><span class="lnum">   8:  </span>}</pre>
</div>
<p>It looks like we&#8217;ve managed to bring down the complexity of defining an event.</p>
<p>Raising an event is slightly different, but still only one line of code (&#8221;this&#8221; refers to the Cart class that is calling this API): DomainEvents.CartIsFull.Raise(<span class="kwrd">this</span>);</p>
<h3>New Service Layer</h3>
<p>The advantage of having a disposable domain event allows us to use the &#8220;using&#8221; construct for cleanup.</p>
<p><p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">class</span> AddGameToCartMessageHandler :</pre>
<pre><span class="lnum">   2:  </span>    BaseMessageHandler&lt;AddGameToCartMessage&gt;</pre>
<pre class="alt"><span class="lnum">   3:  </span>{</pre>
<pre><span class="lnum">   4:  </span>    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Handle(AddGameToCartMessage m)</pre>
<pre class="alt"><span class="lnum">   5:  </span>    {</pre>
<pre><span class="lnum">   6:  </span>        <span class="kwrd">using</span> (ISession session = SessionFactory.OpenSession())</pre>
<pre class="alt"><span class="lnum">   7:  </span>        <span class="kwrd">using</span> (ITransaction tx = session.BeginTransaction())</pre>
<pre><span class="lnum">   8:  </span>        <span class="kwrd">using</span> (DomainEvents.GameReportedLost.Register(gameReportedLost))</pre>
<pre class="alt"><span class="lnum">   9:  </span>        <span class="kwrd">using</span> (DomainEvents.CartIsFull.Register(cartIsFull))</pre>
<pre><span class="lnum">  10:   </span>       {</pre>
<pre class="alt"><span class="lnum">  11:  </span>            ICart cart = session.Get&lt;ICart&gt;(m.CartId);</pre>
<pre><span class="lnum">  12:  </span>            IGame g = session.Get&lt;IGame&gt;(m.GameId);</pre>
<pre class="alt"><span class="lnum">  13:  </span>&nbsp;</pre>
<pre><span class="lnum">  14:  </span>            cart.Add(g);</pre>
<pre class="alt"><span class="lnum">  15:  </span>&nbsp;</pre>
<pre><span class="lnum">  16:  </span>            tx.Commit();</pre>
<pre class="alt"><span class="lnum">  17:  </span>        }</pre>
<pre><span class="lnum">  18:  </span>    }</pre>
<pre class="alt"><span class="lnum">  19:  </span>&nbsp;</pre>
<pre><span class="lnum">  20:  </span>    <span class="kwrd">private</span> Action&lt;IGame&gt; gameReportedLost = <span class="kwrd">delegate</span> { </pre>
<pre class="alt"><span class="lnum">  21:  </span>          Bus.Return((<span class="kwrd">int</span>)ErrorCodes.GameReportedLost);</pre>
<pre><span class="lnum">  22:  </span>        };</pre>
<pre class="alt"><span class="lnum">  23:  </span>&nbsp;</pre>
<pre><span class="lnum">  24:  </span>    <span class="kwrd">private</span> Action&lt;ICart&gt; cartIsFull = <span class="kwrd">delegate</span> { </pre>
<pre class="alt"><span class="lnum">  25:  </span>          Bus.Return((<span class="kwrd">int</span>)ErrorCodes.CartIsFull);</pre>
<pre><span class="lnum">  26:  </span>        };</pre>
<pre class="alt"><span class="lnum">  27:  </span>    }</pre>
<pre><span class="lnum">  28:  </span>}</pre>
</div>
<p>I also want to mention that you don&#8217;t necessarily have to have the same service layer object handle these events as that which calls the domain objects. In other words, we can have singleton objects handling these events for things like sending emails, notifying external systems, and auditing.</p>
<h3>The Infrastructure</h3>
<p>The infrastructure that makes all this possible (in a thread-safe way) is quite simple and made up of two parts, the DomainEvent that we saw being used above, and the DomainEventRegistrationRemover which handles the disposing:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">using</span> System;</pre>
<pre><span class="lnum">   2:  </span><span class="kwrd">using</span> System.Collections.Generic;</pre>
<pre class="alt"><span class="lnum">   3:  </span>&nbsp;</pre>
<pre><span class="lnum">   4:  </span><span class="kwrd">namespace</span> DomainEventInfrastructure</pre>
<pre class="alt"><span class="lnum">   5:  </span>{</pre>
<pre><span class="lnum">   6:  </span>    <span class="kwrd">public</span> <span class="kwrd">class</span> DomainEvent&lt;E&gt; </pre>
<pre class="alt"><span class="lnum">   7:  </span>    {</pre>
<pre><span class="lnum">   8:  </span>        [ThreadStatic] </pre>
<pre class="alt"><span class="lnum">   9:  </span>        <span class="kwrd">private</span> <span class="kwrd">static</span> List&lt;Action&lt;E&gt;&gt; _actions; </pre>
<pre><span class="lnum">  10:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  11:  </span>        <span class="kwrd">protected</span> List&lt;Action&lt;E&gt;&gt; actions </pre>
<pre><span class="lnum">  12:  </span>        {</pre>
<pre class="alt"><span class="lnum">  13:  </span>            get { </pre>
<pre><span class="lnum">  14:  </span>                <span class="kwrd">if</span> (_actions == <span class="kwrd">null</span>) </pre>
<pre class="alt"><span class="lnum">  15:  </span>                    _actions = <span class="kwrd">new</span> List&lt;Action&lt;E&gt;&gt;(); </pre>
<pre><span class="lnum">  16:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  17:  </span>                <span class="kwrd">return</span> _actions; </pre>
<pre><span class="lnum">  18:  </span>            }</pre>
<pre class="alt"><span class="lnum">  19:  </span>        }</pre>
<pre><span class="lnum">  20:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  21:  </span>        <span class="kwrd">public</span> IDisposable Register(Action&lt;E&gt; callback) </pre>
<pre><span class="lnum">  22:  </span>        {</pre>
<pre class="alt"><span class="lnum">  23:  </span>            actions.Add(callback);</pre>
<pre><span class="lnum">  24:  </span>            <span class="kwrd">return</span> <span class="kwrd">new</span> DomainEventRegistrationRemover(<span class="kwrd">delegate</span></pre>
<pre class="alt"><span class="lnum">  25:  </span>                {</pre>
<pre><span class="lnum">  26:  </span>                    actions.Remove(callback);</pre>
<pre class="alt"><span class="lnum">  27:  </span>                }</pre>
<pre><span class="lnum">  28:  </span>            ); </pre>
<pre class="alt"><span class="lnum">  29:  </span>        }</pre>
<pre><span class="lnum">  30:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  31:  </span>        <span class="kwrd">public</span> <span class="kwrd">void</span> Raise(E args) </pre>
<pre><span class="lnum">  32:  </span>        {</pre>
<pre class="alt"><span class="lnum">  33:  </span>            <span class="kwrd">foreach</span> (Action&lt;E&gt; action <span class="kwrd">in</span> actions) </pre>
<pre><span class="lnum">  34:  </span>                action.Invoke(args);</pre>
<pre class="alt"><span class="lnum">  35:  </span>        }</pre>
<pre><span class="lnum">  36:  </span>    }</pre>
<pre class="alt"><span class="lnum">  37:  </span>}</pre>
<pre><span class="lnum">  38:  </span>&nbsp;</pre>
</div>
<p>Note that the invocation list of the domain event is thread static, meaning that each thread gets its own copy &#8211; even though they&#8217;re all working with the same instance of the domain event.</p>
<p>Here&#8217;s the DomainEventRegistrationRemover &#8211; even simpler:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">using</span> System;</pre>
<pre><span class="lnum">   2:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">   3:  </span><span class="kwrd">namespace</span> DomainEventInfrastructure</pre>
<pre><span class="lnum">   4:  </span>{</pre>
<pre class="alt"><span class="lnum">   5:  </span>    <span class="kwrd">public</span> <span class="kwrd">class</span> DomainEventRegistrationRemover : IDisposable </pre>
<pre><span class="lnum">   6:  </span>    {</pre>
<pre class="alt"><span class="lnum">   7:  </span>        <span class="kwrd">private</span> <span class="kwrd">readonly</span> Action CallOnDispose;</pre>
<pre><span class="lnum">   8:  </span> </pre>
<pre class="alt"><span class="lnum">   9:  </span>        <span class="kwrd">public</span> DomainEventRegistrationRemover(Action ToCall) </pre>
<pre><span class="lnum">  10:  </span>        {</pre>
<pre class="alt"><span class="lnum">  11:  </span>            <span class="kwrd">this</span>.CallOnDispose = ToCall; </pre>
<pre><span class="lnum">  12:  </span>        }</pre>
<pre class="alt"><span class="lnum">  13:  </span>&nbsp;</pre>
<pre><span class="lnum">  14:  </span>        <span class="kwrd">public</span> <span class="kwrd">void</span> Dispose() </pre>
<pre class="alt"><span class="lnum">  15:  </span>        {</pre>
<pre><span class="lnum">  16:  </span>            <span class="kwrd">this</span>.CallOnDispose.DynamicInvoke();</pre>
<pre class="alt"><span class="lnum">  17:  </span>        }</pre>
<pre><span class="lnum">  18:  </span>    }</pre>
<pre class="alt"><span class="lnum">  19:  </span>}</pre>
</div>
<p>For your convenience, I&#8217;ve made these available for <a href="http://www.udidahan.com/wp-content/uploads/domaineventinfrastructure.zip">download here</a>.</p>
<p>I also want to add that if you haven&#8217;t looked at the comments on the original post &#8211; there&#8217;s some really good stuff there (36 comments so far). <a href="http://www.udidahan.com/2008/02/29/how-to-create-fully-encapsulated-domain-models">Take a look</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2008/08/25/domain-events-take-2/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>How to create fully encapsulated Domain Models</title>
		<link>http://www.udidahan.com/2008/02/29/how-to-create-fully-encapsulated-domain-models/</link>
		<comments>http://www.udidahan.com/2008/02/29/how-to-create-fully-encapsulated-domain-models/#comments</comments>
		<pubDate>Fri, 29 Feb 2008 14:40:33 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Business Rules]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[Simplicity]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2008/02/29/how-to-create-fully-encapsulated-domain-models/</guid>
		<description><![CDATA[ Update: The new and improved solution is now available: Domain Events, Take 2.
Most people getting started with DDD and the Domain Model pattern get stuck on this. For a while I tried answering this on the discussion groups, but here we have a nice example that I can point to next time.
The underlying problem [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://udidahan.weblogs.us/wp-content/uploads/image8.png"><img style="border-right: 0px; border-top: 0px; margin: 0px 10px; border-left: 0px; border-bottom: 0px" height="192" alt="image" src="http://udidahan.weblogs.us/wp-content/uploads/image-thumb6.png" width="150" align="right" border="0"></a> <b>Update:</b> The new and <i>improved</i> solution is now available: <a href="http://www.udidahan.com/2008/08/25/domain-events-take-2/">Domain Events, Take 2</a>.</p>
<p>Most people getting started with DDD and the Domain Model pattern get stuck on this. For a while I tried answering this on the discussion groups, but here we have a nice example that I can point to next time.</p>
<p>The underlying problem I&#8217;ve noticed over the past few years is that developers are still thinking in terms of querying when they need more data. When moving to the Domain Model pattern, you have to &#8220;simply&#8221; represent the domain concepts in code &#8211; in other words, see things you aren&#8217;t used to seeing. I&#8217;ll highlight that part in the question below so that you can see where I&#8217;m going to go with this in my answer:</p>
<blockquote><p>I have an instance where I believe I need access to a service or repository from my entity to evaluate a business rule but I&#8217;m using NHibernate for persistence so I don&#8217;t have a real good way to inject services into my entity. Can I get some viewpoints on just passing the services to my entity vs. using a facade?</p>
<p>Let me explain my problem to provide more context to the problem.</p>
<p>The core domain revolves around renting video games. I am working on a new feature to allow customers to trade in old video games. <font color="#ff0000">Customers</font> can trade in multiple games at a time so we have a TradeInCart entity that works similar to most shopping carts that everybody is familiar with. However there are several rules that limit the items that can be placed into the TradeInCart. The core rules are:</p>
<p>1. Only 3 games of the same title can be added to the cart.<br />2. The total number of items in the cart cannot exceed 10.<br />3. No games can be added to the cart that the <font color="#ff0000">customer had previously reported lost</font> with regards to their rental membership.<br />&nbsp;&nbsp;&nbsp; a. If an attempt is made to add a previously reported lost game, then we need to log a BadQueueStatusAddAttempt to the persistence store.</p>
<p>So the first 2 rules are easily handled internally by the cart through an Add operation. Sample cart interface is below.</p>
<p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">class</span> TradeInCart{</pre>
<pre><span class="lnum">   2:  </span>    Account Account{get;}</pre>
<pre class="alt"><span class="lnum">   3:  </span>    LineItem Add(Game game);</pre>
<pre><span class="lnum">   4:  </span>    ValidationResult CanAdd(Game game);</pre>
<pre class="alt"><span class="lnum">   5:  </span>    IList&lt;LineItems&gt; LineItems{get;}</pre>
<pre><span class="lnum">   6:  </span>}</pre>
</div>
<p>However the #3 rule is much more complicated and can&#8217;t be handled internally by the cart, so I have to depend on external services. Splitting up the validation logic for a cart add operation doesn&#8217;t seem very appealing to me at all. So I have the option of passing in a repository to get the previously reported lost games and a service to log bad attempts. This makes my cart interface ugly real quick.</p>
<p><div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">class</span> TradeInCart{</pre>
<pre><span class="lnum">   2:  </span>    Account Account{get;}</pre>
<pre class="alt"><span class="lnum">   3:  </span>    LineItem Add(</pre>
<pre><span class="lnum">   4:  </span>        Game game, </pre>
<pre class="alt"><span class="lnum">   5:  </span>        IRepository&lt;QueueHistory&gt; repository, </pre>
<pre><span class="lnum">   6:  </span>        LoggingService service);</pre>
<pre class="alt"><span class="lnum">   7:  </span>&nbsp;</pre>
<pre><span class="lnum">   8:  </span>    ValidationResult CanAdd(</pre>
<pre class="alt"><span class="lnum">   9:  </span>        Game game, </pre>
<pre><span class="lnum">  10:  </span>        IRepository&lt;QueueHistory&gt; repository, </pre>
<pre class="alt"><span class="lnum">  11:  </span>        LoggingService service);</pre>
<pre><span class="lnum">  12:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  13:  </span>    IList&lt;LineItems&gt; LineItems{get;}</pre>
<pre><span class="lnum">  14:  </span>}</pre>
</div>
<p>The alternative option is to have a TradeInCartFacade that handles the validations and adding the items to the cart. The façade can have the repository and services injected though DI which is nice, but the big negative is that the cart ends up totally anemic.</p>
<p>Any thought on this would be greatly appreciated.</p>
<p>Thanks,<br />Jesse</p>
</blockquote>
<p>As I highlighted above, the thing that will help you with your business rules is to introduce the Customer object (that you probably already have) with the property GamesReportedLost (an IList&lt;Game&gt;). Your TradeInCart would have a reference to the Customer object and could then check the rule in the Add method.</p>
<p>Before I go into the code, it looks like your Account object might be used the same way, but your description of the domain doesn&#8217;t mention accounts, so I&#8217;m going to assume that that&#8217;s unrelated for now:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public class</span> Customer{</pre>
<pre><span class="lnum">   2:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">   3:  </span>    <span class="rem">/* other properties and methods */</span></pre>
<pre><span class="lnum">   4:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">   5:  </span>    <span class="kwrd">private</span> IList&lt;Game&gt; gamesReportedLost;</pre>
<pre><span class="lnum">   6:  </span>    <span class="kwrd">public</span> <span class="kwrd">virtual</span> IList&lt;Game&gt; GamesReportedLost </pre>
<pre class="alt"><span class="lnum">   7:  </span>    { </pre>
<pre><span class="lnum">   8:  </span>        get</pre>
<pre class="alt"><span class="lnum">   9:  </span>        {</pre>
<pre><span class="lnum">  10:  </span>            <span class="kwrd">return</span> gamesReportedLost;</pre>
<pre class="alt"><span class="lnum">  11:  </span>        }</pre>
<pre><span class="lnum">  12:  </span>        set</pre>
<pre class="alt"><span class="lnum">  13:  </span>        {</pre>
<pre><span class="lnum">  14:  </span>            gamesReportedLost = <span class="kwrd">value</span>;</pre>
<pre class="alt"><span class="lnum">  15:  </span>        }</pre>
<pre><span class="lnum">  16:  </span>    }</pre>
<pre class="alt"><span class="lnum">  17:  </span>}</pre>
</div>
<p>Keep in mind that the GamesReportedLost is a persistent property of Customer. Every time a customer reports a game lost, this list needs to be kept up to date. Here&#8217;s the TradeInCart now:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">class</span> TradeInCart</pre>
<pre><span class="lnum">   2:  </span>{</pre>
<pre class="alt"><span class="lnum">   3:  </span>    <span class="rem">/* other properties and methods */</span></pre>
<pre><span class="lnum">   4:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">   5:  </span>    <span class="kwrd">private</span> Customer customer;</pre>
<pre><span class="lnum">   6:  </span>    <span class="kwrd">public</span> <span class="kwrd">virtual</span> Customer Customer</pre>
<pre class="alt"><span class="lnum">   7:  </span>    { </pre>
<pre><span class="lnum">   8:  </span>        get { <span class="kwrd">return</span> customer; }</pre>
<pre class="alt"><span class="lnum">   9:  </span>        set { customer = <span class="kwrd">value</span>; }</pre>
<pre><span class="lnum">  10:  </span>    }</pre>
<pre class="alt"><span class="lnum">  11:  </span>&nbsp;</pre>
<pre><span class="lnum">  12:  </span>    <span class="kwrd">private</span> IList&lt;LineItem&gt; lineItems;</pre>
<pre class="alt"><span class="lnum">  13:  </span>    <span class="kwrd">public</span> <span class="kwrd">virtual</span> IList&lt;LineItem&gt; LineItems</pre>
<pre><span class="lnum">  14:  </span>    {</pre>
<pre class="alt"><span class="lnum">  15:  </span>        get { <span class="kwrd">return</span> lineItems; }</pre>
<pre><span class="lnum">  16:  </span>        set { lineItems = <span class="kwrd">value</span>; }</pre>
<pre class="alt"><span class="lnum">  17:  </span>    }</pre>
<pre><span class="lnum">  18:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  19:  </span>    <span class="kwrd">public</span> <span class="kwrd">void</span> Add(Game game)</pre>
<pre><span class="lnum">  20:  </span>    {</pre>
<pre class="alt"><span class="lnum">  21:  </span>        <span class="kwrd">if</span> (lineItems.Count &gt;= CONSTANTS.MaxItemsPerCart)</pre>
<pre><span class="lnum">  22:  </span>        {</pre>
<pre class="alt"><span class="lnum">  23:  </span>            FailureEvents.RaiseCartIsFullEvent();</pre>
<pre><span class="lnum">  24:  </span>            <span class="kwrd">return</span>;</pre>
<pre class="alt"><span class="lnum">  25:  </span>        }</pre>
<pre><span class="lnum">  26:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  27:  </span>        <span class="kwrd">if</span> (NumberOfGameAlreadyInCart(game) &gt;=</pre>
<pre><span class="lnum">  28:  </span>            CONSTANTS.MaxNumberOfSameGamePerCart)</pre>
<pre class="alt"><span class="lnum">  29:  </span>        {</pre>
<pre><span class="lnum">  30:  </span>            FailureEvents</pre>
<pre class="alt"><span class="lnum">  31:  </span>              .RaiseMaxNumberOfSameGamePerCartReachedEvent();</pre>
<pre><span class="lnum">  32:  </span>            <span class="kwrd">return</span>;</pre>
<pre class="alt"><span class="lnum">  33:  </span>        }</pre>
<pre><span class="lnum">  34:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  35:  </span>        <span class="kwrd">if</span> (customer.GamesReportedLost.Contains(game))</pre>
<pre><span class="lnum">  36:  </span>            FailureEvents.RaiseGameReportedLostEvent();</pre>
<pre class="alt"><span class="lnum">  37:  </span>        <span class="kwrd">else</span></pre>
<pre><span class="lnum">  38:  </span>            <span class="kwrd">this</span>.lineItems.Add(<span class="kwrd">new</span> LineItem(game));</pre>
<pre class="alt"><span class="lnum">  39:  </span>    }</pre>
<pre><span class="lnum">  40:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  41:  </span>    <span class="kwrd">private</span> <span class="kwrd">int</span> NumberOfGameAlreadyInCart(Game game)</pre>
<pre><span class="lnum">  42:  </span>    {</pre>
<pre class="alt"><span class="lnum">  43:  </span>        <span class="kwrd">int</span> result = 0;</pre>
<pre><span class="lnum">  44:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  45:  </span>        <span class="kwrd">foreach</span>(LineItem li <span class="kwrd">in</span> <span class="kwrd">this</span>.lineItems)</pre>
<pre><span class="lnum">  46:  </span>            <span class="kwrd">if</span> (li.Game == game)</pre>
<pre class="alt"><span class="lnum">  47:  </span>                result++;</pre>
<pre><span class="lnum">  48:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  49:  </span>        <span class="kwrd">return</span> result;</pre>
<pre><span class="lnum">  50:  </span>    }</pre>
<pre class="alt"><span class="lnum">  51:  </span>}</pre>
<pre><span class="lnum">  52:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  53:  </span><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> FailureEvents</pre>
<pre><span class="lnum">  54:  </span>{</pre>
<pre class="alt"><span class="lnum">  55:  </span>    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">event</span> EventHandler GameReportedLost;</pre>
<pre><span class="lnum">  56:  </span>    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> RaiseGameReportedLostEvent()</pre>
<pre class="alt"><span class="lnum">  57:  </span>    {</pre>
<pre><span class="lnum">  58:  </span>         <span class="kwrd">if</span> (GameReportedLost != <span class="kwrd">null</span>)</pre>
<pre class="alt"><span class="lnum">  59:  </span>             GameReportedLost(<span class="kwrd">null</span>, <span class="kwrd">null</span>);</pre>
<pre><span class="lnum">  60:  </span>    }</pre>
<pre class="alt"><span class="lnum">  61:  </span>&nbsp;</pre>
<pre><span class="lnum">  62:  </span>    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">event</span> EventHandler CartIsFull;</pre>
<pre class="alt"><span class="lnum">  63:  </span>    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> RaiseCartIsFullEvent()</pre>
<pre><span class="lnum">  64:  </span>    {</pre>
<pre class="alt"><span class="lnum">  65:  </span>         <span class="kwrd">if</span> (CartIsFull != <span class="kwrd">null</span>)</pre>
<pre><span class="lnum">  66:  </span>             CartIsFull(<span class="kwrd">null</span>, <span class="kwrd">null</span>);</pre>
<pre class="alt"><span class="lnum">  67:  </span>    }</pre>
<pre><span class="lnum">  68:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  69:  </span>    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">event</span> EventHandler MaxNumberOfSameGamePerCartReached;</pre>
<pre><span class="lnum">  70:  </span>    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> RaiseMaxNumberOfSameGamePerCartReachedEvent()</pre>
<pre class="alt"><span class="lnum">  71:  </span>    {</pre>
<pre><span class="lnum">  72:  </span>         <span class="kwrd">if</span> (MaxNumberOfSameGamePerCartReached != <span class="kwrd">null</span>)</pre>
<pre class="alt"><span class="lnum">  73:  </span>             MaxNumberOfSameGamePerCartReached(<span class="kwrd">null</span>, <span class="kwrd">null</span>);</pre>
<pre><span class="lnum">  74:  </span>    }</pre>
<pre class="alt"><span class="lnum">  75:  </span>}</pre>
</div>
<p><a href="http://udidahan.weblogs.us/wp-content/uploads/image9.png"><img style="border-right: 0px; border-top: 0px; margin: 0px 10px; border-left: 0px; border-bottom: 0px" height="244" alt="image" src="http://udidahan.weblogs.us/wp-content/uploads/image-thumb7.png" width="184" align="right" border="0"></a> Your service layer class that calls the Add method of TradeInCart would first subscribe to the relevant events in FailureEvents. If one of those events is raised, it would do the necessary logging, external system calls, etc.</p>
<p>As you can see, the API of TradeInCart doesn&#8217;t need to make use of any external repositories, nor do you need to inject any other external dependencies in.</p>
<p>One thing I didn&#8217;t do in the above code to keep it &#8220;short&#8221; is to define the relevant custom EventArgs for bubbling up the information as to <em>which</em> game was reported lost or already have 3 of those in the cart. That is something that definitely should be done so that the service layer can pass this information back to the client.</p>
<p>Here&#8217;s a look at Service Layer code:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">class</span> AddGameToCartMessageHandler :</pre>
<pre><span class="lnum">   2:  </span>    BaseMessageHandler&lt;AddGameToCartMessage&gt;</pre>
<pre class="alt"><span class="lnum">   3:  </span>{</pre>
<pre><span class="lnum">   4:  </span>    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Handle(AddGameToCartMessage m)</pre>
<pre class="alt"><span class="lnum">   5:  </span>    {</pre>
<pre><span class="lnum">   6:  </span>        <span class="kwrd">using</span> (ISession session = SessionFactory.OpenSession())</pre>
<pre class="alt"><span class="lnum">   7:  </span>        <span class="kwrd">using</span> (ITransaction tx = session.BeginTransaction())</pre>
<pre><span class="lnum">   8:  </span>        {</pre>
<pre class="alt"><span class="lnum">   9:  </span>            TradeInCart cart = session.Get&lt;TradeInCart&gt;(m.CartId);</pre>
<pre><span class="lnum">  10:  </span>            Game g = session.Get&lt;Game&gt;(m.GameId);</pre>
<pre class="alt"><span class="lnum">  11:  </span>&nbsp;</pre>
<pre><span class="lnum">  12:  </span>            Domain.FailureEvents.GameReportedLost +=</pre>
<pre class="alt"><span class="lnum">  13:  </span>              gameReportedLost;</pre>
<pre><span class="lnum">  14:  </span>            Domain.FailureEvents.CartIsFull +=</pre>
<pre class="alt"><span class="lnum">  15:  </span>              cartIsFull;</pre>
<pre><span class="lnum">  16:  </span>            Domain.FailureEvents.MaxNumberOfSameGamePerCartReached +=</pre>
<pre class="alt"><span class="lnum">  17:  </span>              maxNumberOfSameGamePerCartReached;</pre>
<pre><span class="lnum">  18:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  19:  </span>            cart.Add(g);</pre>
<pre><span class="lnum">  20:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  21:  </span>            Domain.FailureEvents.GameReportedLost -=</pre>
<pre><span class="lnum">  22:  </span>              gameReportedLost;</pre>
<pre class="alt"><span class="lnum">  23:  </span>            Domain.FailureEvents.CartIsFull -=</pre>
<pre><span class="lnum">  24:  </span>              cartIsFull;</pre>
<pre class="alt"><span class="lnum">  25:  </span>            Domain.FailureEvents.MaxNumberOfSameGamePerCartReached -=</pre>
<pre><span class="lnum">  26:  </span>              maxNumberOfSameGamePerCartReached;</pre>
<pre class="alt"><span class="lnum">  27:  </span>&nbsp;</pre>
<pre><span class="lnum">  28:  </span>            tx.Commit();</pre>
<pre class="alt"><span class="lnum">  29:  </span>        }</pre>
<pre><span class="lnum">  30:  </span>    }</pre>
<pre class="alt"><span class="lnum">  31:  </span>&nbsp;</pre>
<pre><span class="lnum">  32:  </span>    <span class="kwrd">private</span> EventHandler gameReportedLost = <span class="kwrd">delegate</span> { </pre>
<pre class="alt"><span class="lnum">  33:  </span>          Bus.Return((<span class="kwrd">int</span>)ErrorCodes.GameReportedLost);</pre>
<pre><span class="lnum">  34:  </span>        };</pre>
<pre class="alt"><span class="lnum">  35:  </span>&nbsp;</pre>
<pre><span class="lnum">  36:  </span>    <span class="kwrd">private</span> EventHandler cartIsFull = <span class="kwrd">delegate</span> { </pre>
<pre class="alt"><span class="lnum">  37:  </span>          Bus.Return((<span class="kwrd">int</span>)ErrorCodes.CartIsFull);</pre>
<pre><span class="lnum">  38:  </span>        };</pre>
<pre class="alt"><span class="lnum">  39:  </span>&nbsp;</pre>
<pre><span class="lnum">  40:  </span>    <span class="kwrd">private</span> EventHandler maxNumberOfSameGamePerCartReached = <span class="kwrd">delegate</span> { </pre>
<pre class="alt"><span class="lnum">  41:  </span>          Bus.Return((<span class="kwrd">int</span>)ErrorCodes.MaxNumberOfSameGamePerCartReached);</pre>
<pre><span class="lnum">  42:  </span>        };</pre>
<pre class="alt"><span class="lnum">  43:  </span>    }</pre>
<pre><span class="lnum">  44:  </span>}</pre>
</div>
<p><img style="margin: 0px 10px 5px" src="http://www.familyportraitpainting.com/images/grandfather_sample.jpg" align="right">It&#8217;s important to remember to clean up your event subscriptions so that your Service Layer objects get garbage collected. This is one of the primary causes of memory leaks when using static events in your Domain Model. I&#8217;m hoping to find ways to use lambdas to decrease this repetitive coding pattern. You might be thinking to yourself that non-static events on your Domain Model objects would be easier, since those objects would get collected, freeing up the service layer objects for collection as well. There&#8217;s just on small problem:</p>
<p>The problem is that if an event is raised by a child (or grandchild object), the service layer object may not even know that that grandchild was involved and, as such, would not have subscribed to that event. The only way the service layer could work was by knowing how the Domain Model worked internally &#8211; in essence, breaking encapsulation.</p>
<p>If you&#8217;re thinking that using exceptions would be better, you&#8217;d be right in thinking that that won&#8217;t break encapsulation, <em>and</em> that you wouldn&#8217;t need all that subscribe/unsubscribe code in the service layer. The only problem is that the Domain Model needs to know that the service layer had a default catch clause so that it wouldn&#8217;t blow up. Otherwise, the service layer (or WCF, or nServiceBus) may end up flagging that message as a poison message (<a href="http://udidahan.weblogs.us/2007/02/15/it%e2%80%99s-poison-i-tell-you-poison/">Read more about poison messages</a>). You&#8217;d also have to be extremely careful about in which environments you used your Domain Model &#8211; in other words, your reuse is shot. </p>
<h3>Conclusion</h3>
<p>I never said it would be easy <img src='http://www.udidahan.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>However, the solution is simple (not complex). The same patterns occur over and over. The design is consistent. By focusing on the dependencies we now have a domain model that is reusable across many environments (server, client, sql clr, silverlight). The domain model is also testable without resorting to any fancy mock objects.</p>
<p>One closing comment &#8211; while I do my best to write code that is consistent with production quality environments, this code is more about demonstrating design principles. As such, I focus more on the self-documenting aspects of the code and have elided many production concerns. </p>
<p>Do you have a better solution? </p>
<p>Something that I haven&#8217;t considered?</p>
<p>Do me a favour &#8211; leave me a comment. Tell me what you think.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2008/02/29/how-to-create-fully-encapsulated-domain-models/feed/</wfw:commentRss>
		<slash:comments>59</slash:comments>
		</item>
		<item>
		<title>From CRUD to Domain-Driven Fluency</title>
		<link>http://www.udidahan.com/2008/02/15/from-crud-to-domain-driven-fluency/</link>
		<comments>http://www.udidahan.com/2008/02/15/from-crud-to-domain-driven-fluency/#comments</comments>
		<pubDate>Fri, 15 Feb 2008 15:58:19 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[ADO.NET]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Databases]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[Simplicity]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2008/02/15/from-crud-to-domain-driven-fluency/</guid>
		<description><![CDATA[I got a question about how to stay away from CRUD based service interfaces when the logic itself is like that, and I’ve found that this shift in thinking really needs more examples, so I’ve decided to put this out there:

For instance, in an HR system, the process of interviewing candidates &#8211; wouldn’t you just [...]]]></description>
			<content:encoded><![CDATA[<p>I got a question about how to stay away from CRUD based service interfaces when the logic itself is like that, and I’ve found that this shift in thinking really needs more examples, so I’ve decided to put this out there:<br />
<blockquote>
<p>For instance, in an HR system, the process of interviewing candidates &#8211; wouldn’t you just insert, update, and delete these Appointment objects?</p>
</blockquote>
<p>If I were to put on my domain-driven hat, I would describe those requirements differently – interview appointments have a lifecycle: proposed, accepted, cancelled, etc. It seems that only a user of the role HR Interviewer should be able to make appointments for themselves, so the service layer code would probably look something like this:
<p><!-- code formatted by http://manoli.net/csharpformat/ --><br />
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}</p>
<p>.csharpcode pre { margin: 0em; }</p>
<p>.csharpcode .rem { color: #008000; }</p>
<p>.csharpcode .kwrd { color: #0000ff; }</p>
<p>.csharpcode .str { color: #006080; }</p>
<p>.csharpcode .op { color: #0000c0; }</p>
<p>.csharpcode .preproc { color: #cc6633; }</p>
<p>.csharpcode .asp { background-color: #ffff00; }</p>
<p>.csharpcode .html { color: #800000; }</p>
<p>.csharpcode .attr { color: #ff0000; }</p>
<p>.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}</p>
<p>.csharpcode .lnum { color: #606060; }
</style>
<pre class="csharpcode"><span class="kwrd">using</span> (ISession session = SessionFactory.OpenSession())
<span class="kwrd">using</span> (ITransaction tx = session.BeginTransaction())
{
    ICandidateInterviewer interviewer = session.Get&lt;ICandidateInterviewer&gt;(message.InterviewerId);
    ICandidate candidate = session.Get&lt;ICandidate&gt;(message.CandidateId);

    interviewer.ScheduleInterviewWith(candidate).At(message.RequestedTime);
    tx.Commit();
}
</pre>
<p>The “ScheduleInterviewWith” method accepts an ICandidate and returns an IAppointment. IAppointment has a method “At” which accepts a DateTime parameter and returns void – just changes the data of the appointment. The state of the appointment at creation time would probably be proposed. The appointment object would probably be added to the list of appointments for that interviewer – that’s what will cause it to be persisted automatically. </p>
<p>Later, when the candidate accepts the meeting, we could have the following method on ICandidate – void Accept(IAppointment); that would obviously check that the candidate is the right person for that interview, the appointment’s current state (not cancelled), etc – finally updating its state. What part of this looks like create, update, delete? If that’s what your service layer to domain interaction looks like, do you now know what your messages will be looking like?CRUD seems to be what most of us are familiar with. Moving to domain-driven thinking takes time and practice, but is well worth it. Contrast this with a more traditional O/R mapping solution: </p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}</p>
<p>.csharpcode pre { margin: 0em; }</p>
<p>.csharpcode .rem { color: #008000; }</p>
<p>.csharpcode .kwrd { color: #0000ff; }</p>
<p>.csharpcode .str { color: #006080; }</p>
<p>.csharpcode .op { color: #0000c0; }</p>
<p>.csharpcode .preproc { color: #cc6633; }</p>
<p>.csharpcode .asp { background-color: #ffff00; }</p>
<p>.csharpcode .html { color: #800000; }</p>
<p>.csharpcode .attr { color: #ff0000; }</p>
<p>.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}</p>
<p>.csharpcode .lnum { color: #606060; }
</style>
<pre class="csharpcode"><span class="kwrd">using</span> (ISession session = SessionFactory.OpenSession())
<span class="kwrd">using</span> (ITransaction tx = session.BeginTransaction())
{
    ICandidateInterviewer interviewer = session.Get&lt;ICandidateInterviewer&gt;(message.InterviewerId);
    ICandidate candidate = session.Get&lt;ICandidate&gt;(message.CandidateId); 

    Appointment a = <span class="kwrd">new</span> Appointment(); 

    a.Interviewer = interviewer;
    interviewer.Appointments.Add(a); 

    a.Candidate = candidate;
    candidate.Appointments.Add(a); 

    a.Time = message.RequestedTime; 

    session.Save(a);  

    tx.Commit();
} 
</pre>
<p>As you can see, we’ve got simpler, more expressive, and more testable code when employing the domain model pattern, than using “just” O/R mapping. I’m not saying that the domain model pattern doesn’t need O/R mapping in the background for it to work. But that’s just it &#8211; the persistence gunk needs to be in the background and the business logic needs to be encapsulated. </p>
<p>So, while I’ll agree with Dave that the Domain Model is <a href="http://laribee.com/blog/2007/05/08/domain-model-less-pattern-more-lifestyle/">more lifestyle than pattern</a>, I would argue against these conclusions: </p>
<blockquote>
<p>If this post had a point, it’s only to share the idea that Domain Model is a big, big thing. It’s probably overkill in a lot of cases where you have simple applications that have very simple purposes.</p>
</blockquote>
<p>As you just saw in the example above, there is no “overkill” to be seen. The domain model in the example wasn’t “a big, big thing”. </p>
<p>The domain model. Use it. </p>
<p>Why not have a better lifestyle?&nbsp;&nbsp; <img alt=";-)" src="http://udidahan.weblogs.us/wp-includes/images/smilies/icon_wink.gif"></p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2008/02/15/from-crud-to-domain-driven-fluency/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>[Podcast] Domain Models, SOA, and The Single Version of the Truth</title>
		<link>http://www.udidahan.com/2007/09/12/podcast-domain-models-soa-and-the-single-version-of-the-truth/</link>
		<comments>http://www.udidahan.com/2007/09/12/podcast-domain-models-soa-and-the-single-version-of-the-truth/#comments</comments>
		<pubDate>Wed, 12 Sep 2007 08:56:12 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Ask Udi Podcast]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[SOA]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/09/12/podcast-domain-models-soa-and-the-single-version-of-the-truth/</guid>
		<description><![CDATA[In this podcast we&#8217;ll try to describe some of the pitfalls of trying to split a domain model between multiple services, as well as how SOA side-steps the &#8220;single version of the truth&#8221; issue found in reporting.
Rishi asks:

Hi Udi,
First of all, thanks for all the posts and info you share, it is very insightful compared [...]]]></description>
			<content:encoded><![CDATA[<p>In this podcast we&#8217;ll try to describe some of the pitfalls of trying to split a domain model between multiple services, as well as how SOA side-steps the &#8220;single version of the truth&#8221; issue found in reporting.</p>
<p>Rishi asks:</p>
<blockquote><p>
Hi Udi,<br />
First of all, thanks for all the posts and info you share, it is very insightful compared to loads n&#8217; loads of marketing bull and vendor whitepapers. Ok, I have two questions for you.</p>
<p>1. I want to create a SOA-based LOB application/platform and I generally understand the &#8216;tenets of services&#8217; and reasons for the same. However, as you may well know, there is a lot of interdependency between business constructs (such as a customer with an order, or a delivery with a product construct). Now, should we share these constructs within a tightly-coupled and domain-based &#8220;system&#8221; which exposes a number of services to the outside world and use the constructs directly inside the so-called &#8220;system&#8221; boundary. Or on the opposite spectrum have a number of autonomous and independent services that expose, own, and share certain business constructs or at least part of the data that represents them as a whole. For example, an order service will need to interact with a customer construct, which primarily/essentially is (or should be?) owned by a customer profile service &#8211; in this context, with clear, direct, and immediate inter-dependency what is preferable? Where do we draw the enclosing line?</p>
<p>2. In a line of business application, reporting and shaping data are a given necessity. Now, with autonomous and independent services which define business constructs in their contextual ways, how do we practically shape, combine, and filter data across various services? We certainly can&#8217;t do joins over multiple services in a practical way? And as some suggest, if we are to maintain duplicate or master data elsewhere, it just seems very messy to me &#8211; just consider having 3 versions of an order services, with 2 versions of support services, and &#8216;n&#8217; number of other services to comb data from. Further, for reporting and also analytical purposes we really need to have business data structured in a well-defined manner, which for all purposes needs to be the &#8220;single version of the truth&#8221;. I can&#8217;t see granular services, with all its tenets, sitting nicely with such other requirements of the business &#8211; and yet I am not even asking them to be real-time. How do we meet such business requirements in your view with SOA?</p>
<p>Hope the above makes sense!</p>
<p>Cheers,<br />
Rishi</p>
<p>PS: I use the word business construct purposefully, and it does not directly attribute to a well-defined programmable entity (in object-oriented way, that is).
</p></blockquote>
<p><a href="http://www.ddj.com/architect/201805549">Download via the Dr. Dobb&#8217;s site.</a></p>
<p>Or download directly <a href="http://www.dobbsprojects.com/media/newengine/dynamp.php/070911ud01.mp3?podcast=070911ud01.mp3">here</a>.</p>
<p><b>Additional References</b></p>
<ul>
<li><a href="http://udidahan.weblogs.us/2006/05/26/podcast-does-soa-mean-the-end-of-oo/">Ask Udi Podcast #000&#8211;Does SOA mean the end of OO?</a></li>
<li><a href="http://udidahan.weblogs.us/2007/03/08/podcast-master-data-management-and-soa/">Ask Udi Podcast #009&#8211;Master Data Management and SOA</a></li>
<li><a href="http://udidahan.weblogs.us/2007/05/20/podcast-how-does-extract-transform-load-fit-with-soa/">Ask Udi Podcast #016&#8211;How does Extract, Transform, Load fit with SOA?</a></li>
</ul>
<p><b>Want more?</b></p>
<p>Check out the <a href="/ask-udi/">&#8220;Ask Udi&#8221; archives</a>.</p>
<p><b>Got a question?</b></p>
<p><a href="mailto:podcast@UdiDahan.com">Send Udi your question to answer on the show.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/09/12/podcast-domain-models-soa-and-the-single-version-of-the-truth/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
<enclosure url="http://www.dobbsprojects.com/media/newengine/dynamp.php/070911ud01.mp3?podcast=070911ud01.mp3" length="9831013" type="audio/mp3" />
		</item>
		<item>
		<title>Performant and Explicit Domain Models</title>
		<link>http://www.udidahan.com/2007/06/04/performant-and-explicit-domain-models/</link>
		<comments>http://www.udidahan.com/2007/06/04/performant-and-explicit-domain-models/#comments</comments>
		<pubDate>Mon, 04 Jun 2007 20:31:34 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Business Rules]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Databases]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Simplicity]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/06/04/performant-and-explicit-domain-models/</guid>
		<description><![CDATA[Some Technical Difficulties

Ayende and I had an email conversation that started with me asking what would happen if I added an Order to a Customer’s &#8220;Orders&#8221; collection, when that collection was lazy loaded. My question was whether the addition of an element would result in NHibernate hitting the database to fill that collection. His answer [...]]]></description>
			<content:encoded><![CDATA[<h4>Some Technical Difficulties</h4>
<p style="padding: 0em 1em;">
Ayende and I had an email conversation that started with me asking what would happen if I added an Order to a Customer’s &#8220;Orders&#8221; collection, when that collection was lazy loaded. My question was whether the addition of an element would result in NHibernate hitting the database to fill that collection. His answer was a simple &#8220;yes&#8221;. In the case where a customer can have many (millions) of Orders, that’s just not a feasible solution. The technical solution was simple – just define the Orders collection on the Customer as &#8220;inverse=true&#8221;, and then to save a new Order, just write:
</p>
<div style="border: solid black 1px; padding: 0em 1em; background-color:beige; font-family:courier; ">session.Save( new Order(myCustomer) );</div>
<p style="padding: 0em 1em;">
Although it works, it’s not &#8220;DDD compliant&#8221; <img src='http://www.udidahan.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />
</p>
<p style="padding: 0em 1em;">
In Ayende’s post <a href="http://ayende.com/Blog/archive/2007/05/29/Architecting-for-Performance.aspx">Architecting for Performance</a> he quoted a part of our email conversation.  The conclusion I reached was that in order to design performant domain models, you need to know the kinds of data volumes you’re dealing with. It affects both internals and the API of the model – when can you assume cascade, and when not. It’s important to make these kinds of things explicit in the Domain Model’s API.
</p>
<h4>How do you make &#8220;transparent persistence&#8221; explicit?</h4>
<p style="padding: 0em 1em;">
The problem occurs around &#8220;transparent persistence&#8221;. If we were to assume that the Customer object added the Order object to its Orders collection, then we wouldn’t have to explicitly save orders it creates, so we would write service layer code like this:
</p>
<div style="border: solid black 1px; background-color:beige; padding: 0em 1em; overflow:auto; width:600; font-family:courier">
using (IDBScope scope = this.DbServices.GetScope(TransactionOption.On))<br />
{<br />
	IOrderCreatingCustomer c = this.DbServices.Get&lt;IOrderCreatingCustomer&gt;(msg.CustomerId);<br />
	c.CreateOrder(message.OrderAmount);</p>
<p>	scope.Complete();<br />
}
</p></div>
<p style="padding: 0em 1em;">
On the other hand, if we designed our Domain Model around the million orders constraint, we would need to explicitly save the order, so we would write service layer code like this:
</p>
<div style="border: solid black 1px; background-color:beige; padding: 0em 1em; overflow:auto; width:600; font-family:courier">
using (IDBScope scope = this.DbServices.GetScope(TransactionOption.On))<br />
{<br />
	IOrderCreatingCustomer c = this.DbServices.Get&lt;IOrderCreatingCustomer&gt;(msg.CustomerId);<br />
	IOrder o = c.CreateOrder(message.OrderAmount);<br />
	this.DbServices.Save(o);</p>
<p>	scope.Complete();<br />
}
</p></div>
<p style="padding: 0em 1em;">
But the question remains, how do we communicate these guidelines to service layer developers from the Domain Model? There are a number of ways, but it’s important to decide on one and use it consistently. Performance and correctness require it.
</p>
<h4>Solution 1: Explicitness via Return Type</h4>
<p style="padding: 0em 1em;">
The first way is a little subtle, but you can do it with the return type of the &#8220;CreateOrder&#8221; method call. In the case where the Domain Model wishes to communicate that it handles transparent persistence by itself, have the method return &#8220;void&#8221;. Where the Domain Model wishes to communicate that it will not handle transparent persistence, have the method return the Order object created.
</p>
<p style="padding: 0em 1em;">
Another way to communicate the fact that an Order has been created that needs to be saved is with events. There are two sub-ways to do so:
</p>
<h4>Solution 2: Explicitness via Events on Domain Objects</h4>
<p style="padding: 0em 1em;">
The first is to just define the event on the customer object and have the service layer subscribe to it. It’s pretty clear that when the service layer receives a &#8220;OrderCreatedThatRequiresSaving&#8221; event, it should save the order passed in the event arguments.
</p>
<p style="padding: 0em 1em;">
The second realizes that the call to the customer object may come from some other domain object and that the service layer doesn’t necessarily know what can happen as the result of calling some method on the aggregate root. The change of state as the result of that method call may permeate the entire object graph. If each object in the graph raises its own events, its calling object will have to propagate that event to its parent – resulting in defining the same events  in multiple places, and each object being aware of all things possible with its great-grandchild objects. That is clearly bad.
</p>
<h4>What [ThreadStatic] is for</h4>
<p style="padding: 0em 1em;">
So, the solution is to use thread-static events.
</p>
<p style="padding: 0em 1em;">
[Sidebar] Thread-static events are just static events defined on a static class, where each event has the ThreadStaticAttribute applied to it. This attribute is important for server-side scenarios where multiple threads will be running through the Domain Model at the same time. The easiest thread-safe way to use static data is to apply the ThreadStaticAttribute.
</p>
<h4>Solution 3: Explicitness via Static Events</h4>
<p style="padding: 0em 1em;">
Each object raises the appropriate static event according to its logic. In our example, Customer would call:
</p>
<div style="border: solid black 1px; background-color:beige; padding: 0em 1em; font-family:courier">
DomainModelEvents.RaiseOrderCreatedThatRequiresSavingEvent(newOrder);
</div>
<p style="padding: 0em 1em;">And the service layer would write:</p>
<div style="border: solid black 1px; background-color:beige; padding: 0em 1em; font-family:courier">
DomainModelEvents.OrderCreatedThatRequiresSaving +=<br />
	delegate(object sender, OrderEventArgs e) { this.DbServices.Save(e.Order); };
</div>
<p style="padding: 0em 1em;">
The advantage of this solution is that it requires minimal knowledge of the Domain Model for the Service Layer to correctly work with it. It also communicates that anything that doesn’t raise an event will be persisted transparently behind the appropriate root object.
</p>
<h4>Statics and Testability</h4>
<p style="padding: 0em 1em;">
I know that many of you are wondering if I am really advocating the use of statics. The problem with most static classes is that they hurt testability because they are difficult to mock out. Often statics are used as Facades to hide some technological implementation detail. In this case, the static class is an inherent part of the Domain Model and does not serve as a Facade for anything.
</p>
<p style="padding: 0em 1em;">
When it comes to testing the Domain Model, we don’t have to mock anything out since the Domain Model is independent of all other concerns. This leaves us with unit testing at the single Domain Class level, which is pretty useless unless we’re TDD-ing the design of the Domain Model, in which case we’ll still be fiddling around with a bunch of classes at a time. Domain Models are best tested using State-Based Testing; get the objects into a given state, call a method on one of them, assert the resulting state. The static events don’t impede that kind of testing at all.
</p>
<h4>What if we used Injection instead of Statics?</h4>
<p style="padding: 0em 1em;">
Also, you’ll find that each Service Layer class will need to subscribe to all the Domain Model’s events, something that is easily handled by a base class. I will state that I have tried doing this without a static class, and injecting that singleton object into the Service Layer classes, and in that setter having them subscribe to its events. This was also pulled into a base class. The main difference was that the Dependency Injection solution required injecting that object into Domain Objects as well. Personally, I’m against injection for domain objects. So all in all, the static solution comes with less overhead than that based on injection.
</p>
<h4>Summary</h4>
<p style="padding: 0em 1em;">
In summary, beyond the &#8220;technical basics&#8221; of being aware of your data volumes and designing your Domain Model to handle each use case performantly, I’ve found these techniques useful for designing its API as well as communicating my intent around persistence transparency. So give it a try. I’d be grateful to hear your thoughts on the matter as well as what else you’ve found that works.
</p>
<p><u style="padding: 0em 1em;">Related posts:</u></p>
<ul style="padding: 0em 1em;">
<li>
<a href="http://udidahan.weblogs.us/2007/04/23/fetching-strategy-design/">Fetching Strategy Design</a> &#8211; showing how to separate the concern of eager loading from both your Domain Model and your Service Layer.
</li>
<li>
<a href="http://udidahan.weblogs.us/2007/03/06/better-domain-driven-design-implementation/">Better Domain-Driven Design Implementation</a> &#8211; showing the basics of how valuable interfaces between your Domain Model and the Service Layer can be.
</li>
<li>
<a href="http://udidahan.weblogs.us/2007/04/15/lazy-loading-and-how-messaging-fixes-everything-again/">Lazy Loading, and how messaging fixes everything again</a> &#8211; describing the advantage of O/R mapping your message classes as well.
</li>
<li>
<a href="http://udidahan.weblogs.us/2007/03/28/query-objects-vs-methods-on-a-repository/">Query Objects vs Methods on a Repository</a> &#8211; discussing the scalability (in terms of number of developers and queries) of Query Objects.
</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/06/04/performant-and-explicit-domain-models/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>NHibernate will rule, because Ayende already does</title>
		<link>http://www.udidahan.com/2007/05/20/nhibernate-will-rule-because-ayende-already-does/</link>
		<comments>http://www.udidahan.com/2007/05/20/nhibernate-will-rule-because-ayende-already-does/#comments</comments>
		<pubDate>Sun, 20 May 2007 21:56:30 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[ADO.NET]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Business Rules]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Databases]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[OO]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/05/20/nhibernate-will-rule-because-ayende-already-does/</guid>
		<description><![CDATA[First I find out that NHibernate does support &#8220;Persistence by Reachability&#8221;, even though the docs say it doesn&#8217;t. Next, Ayende makes it support multiple queries in a single DB roundtrip, something I&#8217;ve been asking all the other O/R mappers out there to do. To top it off, he&#8217;s got his sights set on solving the [...]]]></description>
			<content:encoded><![CDATA[<p>First I find out that <a href="http://udidahan.weblogs.us/category/nhibernate/">NHibernate</a> does support &#8220;Persistence by Reachability&#8221;, even though the docs say it doesn&#8217;t. Next, Ayende makes it support <a href="http://ayende.com/Blog/archive/2007/05/20/NHibernate-Multi-Criteria.aspx">multiple queries in a single DB roundtrip</a>, something I&#8217;ve been asking all the other O/R mappers out there to do. To top it off, he&#8217;s got his sights set on solving the issues I raised in my talk on Complex Business Logic with DDD and O/R Mapping at DevTeach. That&#8217;s right, he&#8217;s going to give me my decorators and state machines.</p>
<p>I love you, Oren.</p>
<p>I know that the ADO.NET Entity Framework guys are open to this as well, but I&#8217;m pretty sure that the &#8220;Entity Model&#8221; thinking will hold them back. You just can&#8217;t divorce data and behavior &#8211; not when employing state machines or decorators.</p>
<p>I&#8217;m sold.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/05/20/nhibernate-will-rule-because-ayende-already-does/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fetching Strategy Design</title>
		<link>http://www.udidahan.com/2007/04/23/fetching-strategy-design/</link>
		<comments>http://www.udidahan.com/2007/04/23/fetching-strategy-design/#comments</comments>
		<pubDate>Mon, 23 Apr 2007 20:18:56 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[OO]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/04/23/fetching-strategy-design/</guid>
		<description><![CDATA[Following up on my previous post on Better Domain-Driven Design Implementation, I wanted to show some more detail on how this actually works. There are two main concepts here.
The first is that of keeping Service Layer classes independent of Domain Model classes. The reason this is desirable is that the two families change on independent [...]]]></description>
			<content:encoded><![CDATA[<p>Following up on my previous post on <a href="http://udidahan.weblogs.us/2007/03/06/better-domain-driven-design-implementation/">Better Domain-Driven Design Implementation</a>, I wanted to show some more detail on how this actually works. There are two main concepts here.</p>
<p>The first is that of keeping Service Layer classes independent of <a href="http://udidahan.weblogs.us/2007/04/21/domain-model-pattern/">Domain Model</a> classes. The reason this is desirable is that the two families change on independent axis. Service Layer classes are affected by changes to the service&#8217;s external interface, as well as the interfaces of other services it depends on. Domain Model classes change to support changing business rules internal to the service. The solution is quite simply to introduce a set of interfaces between the two.</p>
<p>The second is tied to performance. When retrieving data from the database, we&#8217;d like to cross the wire only once bringing with us all the data we need in order to perform the work required. Lazy loading helps us in one way while hurting us in another. For connected objects that we don&#8217;t need when retrieving our target object, lazy loading prevents them from being loaded. However, for connected objects that we do need, lazy loading will cause us to return to the database to retrieve each of those objects in turn (sets of the same kind of object are still one DB call). If those objects need to be traversed as well in order to retrieve other objects, we can see that one simple request can cause many (MANY!) calls to the DB. These problems of latency and throughput are solved by eagerly (in one DB call) fetching and loading all the objects we need.</p>
<p>Here&#8217;s the package diagram for the solution so that we&#8217;ll have a reference for the following discussion.</p>
<p><a href="http://udidahan.weblogs.us/wp-content/uploads/ea2.png" target="_blank"><img src='http://udidahan.weblogs.us/wp-content/uploads/ea2.thumbnail.png' title='fetching strategy package diagram' alt='fetching strategy package diagram - opens in a new window' /></a></p>
<p>Now, the class that is best suited to issue this call to eagerly load all objects is the service layer class, since it is aware of what specific use case we&#8217;re in. However, the service layer class does not necessarily know exactly what classes will be used in the domain to handle that request. Obviously, this set of classes may change as the domain model and the database schema change. We can therefore say that is not the service layer class&#8217; responsibility to handle the definition of which classes need to be loaded. Only the Domain Model has that knowledge. So we need some way to pass the knowledge of the request type into the Domain Model.</p>
<p>In Object/Role Modeling terms, we represent that request type as a role. And roles are represented by interfaces. So we create an interface in the Domain Model which represents the request type. That interface will most likely contain only one method &#8211; the method which the service layer class will call.</p>
<p>After we have the first role, we can build other things around it, like fetching strategies. We can then define other classes who fullfil the role of &#8220;I&#8217;m his fetching strategy&#8221;. Those classes will expose a property defining the exact set of classes to load, when using <a href="http://udidahan.weblogs.us/category/nhibernate/">NHibernate</a> we use HQL.</p>
<p>Here&#8217;s the sequence diagram showing how this works.</p>
<p><a href="http://udidahan.weblogs.us/wp-content/uploads/ea12.png" target="_blank"><img src='http://udidahan.weblogs.us/wp-content/uploads/ea12.thumbnail.png' title='fetching strategy sequence diagram' alt='fetching strategy sequence diagram - opens in a new window' /></a></p>
<p>One question that you might ask is what if there is more than one class that implements the same interface? How could the infrastructure know which class it should be loading? The answer is simple. You shouldn&#8217;t do that. Having two classes fulfilling the same role will get you in trouble even if you don&#8217;t use this design. The Single Responsibility Principle should be our guiding light.</p>
<p>In summary, achieving high performance is possible when using Domain Models and Object/Relational Mapping, but requires minimizing calls to the database. This design decreases coupling between all the cooperating parts of the solution without giving up the ability to optimize over a specific technology.</p>
<p><a href="http://udidahan.weblogs.us/wp-content/uploads/fetching-strategy-design.zip" class="attachmentlink">Download the full detailed design (in HTML format)</a>. I&#8217;ll be offering the edittable <a href="http://www.sparxsystems.com/">Enterprise Architect</a> format shortly.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/04/23/fetching-strategy-design/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Domain Model Pattern</title>
		<link>http://www.udidahan.com/2007/04/21/domain-model-pattern/</link>
		<comments>http://www.udidahan.com/2007/04/21/domain-model-pattern/#comments</comments>
		<pubDate>Sat, 21 Apr 2007 14:53:38 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Business Rules]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[DataSets]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/04/21/domain-model-pattern/</guid>
		<description><![CDATA[When implementing a domain model, often object-relational mapping technologies are used. Like many tools, with their use comes the danger of abuse &#8211; abuse to the point of invalidating the benefits of the pattern itself.
From some pointers about how to use (and not to use) these tools, see why object-relational mapping sucks.
Martin Fowler&#8217;s has this [...]]]></description>
			<content:encoded><![CDATA[<p>When implementing a domain model, often object-relational mapping technologies are used. Like many tools, with their use comes the danger of abuse &#8211; abuse to the point of invalidating the benefits of the pattern itself.</p>
<p>From some pointers about how to use (and not to use) these tools, see <a href="http://udidahan.weblogs.us/2008/06/25/object-relational-mapping-sucks/">why object-relational mapping sucks</a>.</p>
<p>Martin Fowler&#8217;s has this to say about the <a href="http://martinfowler.com/eaaCatalog/domainModel.html">Domain Model Pattern</a>:</p>
<blockquote><p>
At its worst business logic can be very complex. Rules and logic describe many different cases and slants of behavior, and it&#8217;s this complexity that objects were designed to work with. A Domain Model creates a web of interconnected objects, where each object represents some meaningful individual, whether as large as a corporation or as small as a single line on an order form.
</p></blockquote>
<p>In short, using <a href="http://udidahan.weblogs.us/category/oo/">Object-Oriented techniques</a> to handle the complexity.</p>
<p>A more comprehensive discussion about what happens when it is not used can be found under the <a href="http://www.martinfowler.com/bliki/AnemicDomainModel.html">Anemic Domain Model Anti-Pattern</a>:</p>
<blockquote><p>
The basic symptom of an Anemic Domain Model is that at first blush it looks like the real thing. There are objects, many named after the nouns in the domain space, and these objects are connected with the rich relationships and structure that true domain models have. The catch comes when you look at the behavior, and you realize that there is very little behavior on these objects. Indeed often these models come with design rules that say that you are not to put any domain logic in the the domain objects. Instead there are a set of service objects which capture all the domain logic. These services live on top of the domain model and use the domain model for data.</p>
<p>The fundamental horror of this anti-pattern is that it&#8217;s so contrary to the basic idea of object-oriented design; which is to combine data and process together. The anemic domain model is really just a procedural style design&#8230;
</p></blockquote>
<p>In terms of <a href="http://udidahan.weblogs.us/category/ddd/">Domain-Driven Design</a>, this pattern is also known as Domain Layer.</p>
<p>Domain Models do a lot for encapsulating <a href="http://udidahan.weblogs.us/category/business-rules/">Business Rules</a>, thus making them amenable to automated testing. This hinges on keeping the Domain Model independent of things related to <a href="http://udidahan.weblogs.us/category/data-access/">Data Access</a>.</p>
<p>It is therefore almost required to use some kind of <a href="http://udidahan.weblogs.us/category/nhibernate/">Object/Relational Mapping</a> tool to make it possible to persist objects belonging to the domain model to databases and other kinds of storage.</p>
<p>The use of <a href="http://udidahan.weblogs.us/category/datasets/">DataSets</a> in .NET is often a sign of the Anemic Domain Model Anti-Pattern.</p>
<p>One thing to keep in mind when working on a domain model is that you probably won&#8217;t get it &#8220;right&#8221; the first time, and will have re-work the division of responsibility a couple of times. Techniques like <a href="http://udidahan.weblogs.us/category/tdd/">Test-Driven Development</a> help out immensely for that.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/04/21/domain-model-pattern/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Object/Relational Mapping and Scalability</title>
		<link>http://www.udidahan.com/2007/04/21/objectrelational-mapping-and-scalability/</link>
		<comments>http://www.udidahan.com/2007/04/21/objectrelational-mapping-and-scalability/#comments</comments>
		<pubDate>Sat, 21 Apr 2007 14:19:56 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Caching]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Scalability]]></category>
		<category><![CDATA[Smart Client]]></category>
		<category><![CDATA[Usability]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/04/21/objectrelational-mapping-and-scalability/</guid>
		<description><![CDATA[&#8220;How come there is no talk about scaling these ORMs?&#8221;.
The answer is simple.
You don&#8217;t have to.
Or, if you think you do, you&#8217;re probably using them wrong.
An O/R mapper should NOT live in its own tier.
Object/Relational Mappers never stand alone. They are used to provide persistence for something else &#8211; either for the Domain Model Pattern [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://codeliability.blogspot.com/2007/04/orm-and-when-query-plans-go-bad.html">&ldquo;How come there is no talk about scaling these ORMs?&rdquo;</a>.</p>
<p>The answer is simple.</p>
<p>You don&rsquo;t have to.</p>
<p>Or, if you think you do, you&rsquo;re probably using them wrong.</p>
<p>An O/R mapper should NOT live in its own <a href="http://udidahan.weblogs.us/2007/03/24/fear-those-tiers-iasa/">tier</a>.</p>
<p><a href="http://udidahan.weblogs.us/category/nhibernate/">Object/Relational Mappers</a> never stand alone. They are used to provide persistence for something else &ndash; either for the <a href="http://udidahan.weblogs.us/2007/04/21/domain-model-pattern/">Domain Model Pattern</a> or for the Active Record pattern.</p>
<p>In terms of <a href="http://udidahan.weblogs.us/category/scalability/">scalability</a>, again these patterns usually don&rsquo;t stand by themselves, but rather are hosted by something else. When used on the client side, say in a <a href="http://udidahan.weblogs.us/category/smart-client/">smart client</a> application, then scalability isn&rsquo;t often considered. There are some kinds of smart clients where hitting the database on most <a href="http://udidahan.weblogs.us/category/usability/">user interactions</a> will bring the system to its knees, but that&rsquo;s again an issue of database scalability. The common solution is some kind of client-side <a href="http://udidahan.weblogs.us/category/caching/">caching</a>.</p>
<p>Anyway, the two main parameters you need to look at for your common and high-load scenarios when using an O/R mapper are these:</p>
<ul>
<li>How many times do you hit the DB per business action.</li>
<li>How many objects/records/rows/columns do you bring into memory per business action.</li>
</ul>
<p>You should be looking at appropriate uses of <a href="http://udidahan.weblogs.us/2007/04/15/lazy-loading-and-how-messaging-fixes-everything-again/">Lazy Loading</a> for both of them.</p>
<p>Finally, keep in mind that O/R mappers are only part of your solution. Measure and optimize wisely.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/04/21/objectrelational-mapping-and-scalability/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Lazy-Loading and How Messaging Fixes Everything Again</title>
		<link>http://www.udidahan.com/2007/04/15/lazy-loading-and-how-messaging-fixes-everything-again/</link>
		<comments>http://www.udidahan.com/2007/04/15/lazy-loading-and-how-messaging-fixes-everything-again/#comments</comments>
		<pubDate>Sun, 15 Apr 2007 22:33:03 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/04/15/lazy-loading-and-how-messaging-fixes-everything-again/</guid>
		<description><![CDATA[In a previous post I described the two common scenarios for fetching an object from the database. More importantly, I showed the importance of having a different fetching strategy in the case of retrieving data for the purposes of passing it to someone else, and in the case of going to update that same data. [...]]]></description>
			<content:encoded><![CDATA[<p><P class=MsoNormal style="MARGIN: 0cm 0cm 10pt"><SPAN lang=EN-US style="mso-ansi-language: EN-US"><FONT face=Calibri>In a previous post I described the </FONT><A href="http://udidahan.weblogs.us/2007/03/06/better-domain-driven-design-implementation/"><FONT face=Calibri>two common scenarios for fetching an object from the database</FONT></A><FONT face=Calibri>. More importantly, I showed the importance of having a different fetching strategy in the case of retrieving data for the purposes of passing it to someone else, and in the case of </FONT><A href="http://udidahan.weblogs.us/2007/01/22/realistic-concurrency/"><FONT face=Calibri>going to update that same data</FONT></A><FONT face=Calibri>. Ayende and others looked at the solution I described and </FONT><A href="http://ayende.com/Blog/archive/2007/04/15/Lazy-loading-The-Good-The-Bad-And-The-Evil-Witch.aspx"><FONT face=Calibri>wanted something simpler</FONT></A><FONT face=Calibri>. So here it is.<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /><o:p></o:p></FONT></SPAN></P><br />
<P class=MsoNormal style="MARGIN: 0cm 0cm 10pt"><SPAN lang=EN-US style="mso-ansi-language: EN-US"><FONT face=Calibri>When working in a tiered deployment, client code needs to talk to some “service” (and I use the term lightly) to get the data. That same service may also contain a rich </FONT><A href="http://udidahan.weblogs.us/2007/04/21/domain-model-pattern/"><FONT face=Calibri>domain model</FONT></A><FONT face=Calibri> which handles the business logic around updating its data. In this case, the lazy loading behavior of the domain model will be such as to bring the highest performance to the business logic of updating the data. The question then becomes, how do we retrieve that same data with lazy-loading behavior that will yield high performance or is suitable for serializing and sending back to the client.<o:p></o:p></FONT></SPAN></P><br />
<P class=MsoNormal style="MARGIN: 0cm 0cm 10pt"><SPAN lang=EN-US style="mso-ansi-language: EN-US"><FONT face=Calibri>Were we to model the interaction between client and service using message-exchange patterns, and used a </FONT><A href="http://udidahan.weblogs.us/2006/06/02/can-indigo-be-my-bus/"><FONT face=Calibri>design that kept those messages (and their data structures) independent of any other implementation details</FONT></A><FONT face=Calibri> (POJO/POCO/PONO style), we could just O/R map those classes too.<o:p></o:p></FONT></SPAN></P><br />
<P class=MsoNormal style="MARGIN: 0cm 0cm 10pt"><SPAN lang=EN-US style="mso-ansi-language: EN-US"><FONT face=Calibri>What this means is that the class GetAllCustomersMessageHandler would respond with a CustomersDataMessage that contained a list of CustomerInfo objects. The CustomerInfo class is separate from the Customer class found within the service’s domain model. However, this does not mean that the message handler cannot write the following line of code:<o:p></o:p></FONT></SPAN></P><br />
<P class=MsoNormal style="MARGIN: 0cm 0cm 10pt"><SPAN lang=EN-US style="mso-ansi-language: EN-US"><FONT face=Calibri>IList&lt;CustomerInfo&gt; customersToSerialize = mySession.GetAll&lt;CustomerInfo&gt;();<o:p></o:p></FONT></SPAN></P><br />
<P class=MsoNormal style="MARGIN: 0cm 0cm 10pt"><SPAN lang=EN-US style="mso-ansi-language: EN-US"><FONT face=Calibri>This is Message/Relational Mapping without going all the way to XML/Relational Mapping as Jesse suggest </FONT><A href="http://weblogs.asp.net/jezell/archive/2007/04/13/who-needs-orm-i-ve-got-sql-2005.aspx"><FONT face=Calibri>here</FONT></A><FONT face=Calibri> (although he ignores the whole issue of implementing <a href="http://udidahan.weblogs.us/2007/04/21/domain-model-pattern/">Domain Models</a> or Active Records using an <a href="http://udidahan.weblogs.us/category/nhibernate/">O/R Mapper</a>).<o:p></o:p></FONT></SPAN></P><br />
<P class=MsoNormal style="MARGIN: 0cm 0cm 10pt"><SPAN lang=EN-US style="mso-ansi-language: EN-US"><FONT face=Calibri>What this solution enables us to do is to define different lazy-loading behaviors for the Customer and CustomerInfo classes. Other things that are nice about this solution is that it builds on all the existing design patterns already found in a message-based, <a href="http://udidahan.weblogs.us/category/ddd/">domain-driven</a> system without adding anything new. On the other hand, if you do require numerous lazy-loading behaviors for performance reasons, the more </FONT><A href="http://udidahan.weblogs.us/2007/03/06/better-domain-driven-design-implementation/"><FONT face=Calibri>generic fetching strategy</FONT></A><FONT face=Calibri> I described before is your best bet.<o:p></o:p></FONT></SPAN></P></p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/04/15/lazy-loading-and-how-messaging-fixes-everything-again/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Query Objects vs Methods on a Repository</title>
		<link>http://www.udidahan.com/2007/03/28/query-objects-vs-methods-on-a-repository/</link>
		<comments>http://www.udidahan.com/2007/03/28/query-objects-vs-methods-on-a-repository/#comments</comments>
		<pubDate>Wed, 28 Mar 2007 20:59:30 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[DDD]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/archives/436</guid>
		<description><![CDATA[Given that we have some interface/class that we use to communicate with the persistence mechanism, in NHibernate terms this would be ISession, although that could be wrapper by some more technology-agnostic interface like IDbConversation &#8211; holding the generic methods: Insert, Update, Delete, GetById&#60;T&#62;, GetAll&#60;T&#62;, etc. 
What design issues are better handled by option one (query [...]]]></description>
			<content:encoded><![CDATA[<p>Given that we have some interface/class that we use to communicate with the persistence mechanism, in NHibernate terms this would be ISession, although that could be wrapper by some more technology-agnostic interface like IDbConversation &#8211; holding the generic methods: Insert, Update, Delete, GetById&lt;T&gt;, GetAll&lt;T&gt;, etc. </p>
<p>What design issues are better handled by option one (query objects) or option two (methods on a repository)?</p>
<p>Option 1:</p>
<p>No custom repository per persistence type. All calls are done on IDbConversation. Fetching objects with custom queries is done like so:</p>
<p>IList&lt;T&gt; IDbConversation.PerformQuery(IQuery&lt;T&gt; query);</p>
<p>and then specific classes implement IQuery&lt;T&gt;, for instance, GetCustomersWithOutstandingDebtForLastQuarter which implements IQuery&lt;ICustomer&gt;. This implementation is responsible for translating the query into the appropriate representation for the persistence framework &#8211; say a chain of ICriteria in terms of NHibernate. </p>
<p>This results in loose coupling between queries, such that changing the interface of one would not touch code used by another.</p>
<p>By putting all queries in the same parent namespace &#8220;Queries&#8221;, we get the nice intellisense support of typing &#8220;IList&lt;ICustomer&gt; customers = this.IDbConversation.PerformQuery(Queries.&#8221; and getting the list of available options. </p>
<p>Option 2: (the more common)</p>
<p>One custom repository per persistence type. The repository talks with IDbConversation. The repository exposes methods for custom queries.</p>
<p>IList&lt;Customer&gt; CustomerRepository.GetCustomersWithOutstandingDebtForLastQuarter();</p>
<p>The repository translates the query to the specific persistence framework.</p>
<p>This results in less moving parts. In order to find a specific query you just type &#8220;this.CustomerRepository.&#8221; and the list of available methods shows up with intellisense.</p>
<p>Since all code is in the same class, changing the implementation/interface of one query/method may cause unintended side effects.</p>
<p>&#8211;</p>
<p>As you can probably tell, I&#8217;m for option one. It also fits nicely with <a href="http://udidahan.weblogs.us/2007/03/06/better-domain-driven-design-implementation/">my fetching strategy design</a>, which I&#8217;m going to post the detailed design for shortly. </p>
<p>What are your thoughts?</p>
<p>[Also posted on the Domain Driven Design group <a href="http://tech.groups.yahoo.com/group/domaindrivendesign/message/5162">here</a>.]</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/03/28/query-objects-vs-methods-on-a-repository/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Are DSLs the cure to OO’s ails?</title>
		<link>http://www.udidahan.com/2007/03/27/are-dsls-the-cure-to-oo%e2%80%99s-ails/</link>
		<comments>http://www.udidahan.com/2007/03/27/are-dsls-the-cure-to-oo%e2%80%99s-ails/#comments</comments>
		<pubDate>Tue, 27 Mar 2007 20:21:26 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[DDD]]></category>
		<category><![CDATA[Simplicity]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/archives/432</guid>
		<description><![CDATA[I very much enjoy the podcasts put out by No Fluff, Just Stuff and while I may not agree with all that is said, it is always a pleasant way to spend my commute. While listening to the recent conversation with Neal Ford (blog), I found myself wanting to respond. This further strengthened itself today [...]]]></description>
			<content:encoded><![CDATA[<p><P class=MsoNormal style="MARGIN: 0cm 0cm 10pt"><SPAN lang=EN-US style="mso-ansi-language: EN-US"><FONT face=Calibri>I very much enjoy the podcasts put out by No Fluff, Just Stuff and while I may not agree with all that is said, it is always a pleasant way to spend my commute. While listening to the recent conversation with </FONT><A href="http://www.nofluffjuststuff.com/speaker_view.jsp?speakerId=21"><FONT face=Calibri>Neal Ford</FONT></A><FONT face=Calibri> (</FONT><A href="http://memeagora.blogspot.com/"><FONT face=Calibri>blog</FONT></A><FONT face=Calibri>), I found myself wanting to respond. This further strengthened itself today after coming out of a design review where objects were used, but no object-orientation was to be found. I’m beginning to think the solutions being presented by </FONT><A href="http://www.martinfowler.com/bliki/DomainSpecificLanguage.html"><FONT face=Calibri>Domain Specific Languages</FONT></A><FONT face=Calibri> (DSL) are for the same problems that OO solves. The fact that OO is practiced so little, even when using languages that support its concepts well, makes me think that DSLs might suffer a similar fate.<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /><o:p></o:p></FONT></SPAN></P><br />
<P class=MsoNormal style="MARGIN: 0cm 0cm 10pt"><SPAN lang=EN-US style="mso-ansi-language: EN-US"><FONT face=Calibri>Around the basis of OO, many other design elements have sprouted and grown. Ideas like “once, and only once”, also known as <a href="http://codebetter.com/blogs/jeremy.miller/archive/2007/03/21/The-Don_2700_t-Repeat-Yourself-Principle-and-the-Wormhole-Anti_2D00_Pattern.aspx">Don’t Repeat Yourself</a> (DRY – </FONT><A href="http://www.pragmaticprogrammer.com/ppbook/extracts/rule_list.html"><FONT face=Calibri>by the pragmatic programmers</FONT></A><FONT face=Calibri>) have crystallized into principles like the Single Responsibility Principle. Yardsticks of design like the </FONT><A href="http://en.wikipedia.org/wiki/Law_of_Demeter"><FONT face=Calibri>Law of Demeter</FONT></A><FONT face=Calibri>, used in conjunction with “Tell, Don’t Ask” (see IEEE Software,Jan./Feb. 2003, p. 10) have served practitioners well. Larger efforts like </FONT><A href="http://domaindrivendesign.org/"><FONT face=Calibri>Domain-Driven Design</FONT></A><FONT face=Calibri> are taking us to the next level in terms of IT/Business alignment. Maybe the most interesting thing is that all this has been occurring in a highly disconnected way from developments in code generation, one of the ancestors of DSLs. New, exciting developments are still growing in the shadow of the great OO oak tree – </FONT><A href="http://behaviour-driven.org/"><FONT face=Calibri>Behavior-Driven Development</FONT></A><FONT face=Calibri> (BDD) is building on </FONT><A href="http://www.testdriven.com/"><FONT face=Calibri>Test-Driven Development</FONT></A><FONT face=Calibri> (TDD) which, itself, is still in the “early adopter” phase.<o:p></o:p></FONT></SPAN></P></p>
<table width="100%" border="0">
<tr>
<td valign="top"><center><br />
<iframe src="http://rcm.amazon.com/e/cm?t=thesoftwaresi-20&#038;o=1&#038;p=8&#038;l=as1&#038;asins=0321125215&#038;fc1=000000&#038;IS2=1&#038;lt1=_blank&#038;lc1=0000FF&#038;bc1=000000&#038;bg1=FFFFFF&#038;f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe><br />
</center></td>
<td valign="top"><center><br />
<iframe src="http://rcm.amazon.com/e/cm?t=thesoftwaresi-20&#038;o=1&#038;p=8&#038;l=as1&#038;asins=0321268202&#038;fc1=000000&#038;IS2=1&#038;lt1=_blank&#038;lc1=0000FF&#038;bc1=000000&#038;bg1=EEEEEE&#038;f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe><br/><br />
[Full Disclosure] I <a href="/books">authored</a> a chapter in this book.<br />
</center></td>
</tr>
</table>
<p><br/><br />
<P class=MsoNormal style="MARGIN: 0cm 0cm 10pt"><SPAN lang=EN-US style="mso-ansi-language: EN-US"><FONT face=Calibri>I am worried that in the rush to embrace DSLs as the new “silver bullet”, the baby will be thrown out with the bathwater – and 2 to 3 decades of learning will have to be re-learned. It’s either that or jumping to the next silver bullet that comes along.<o:p></o:p></FONT></SPAN></P></p>
<p><a name="link"></a></p>
<p><P class=MsoNormal style="MARGIN: 0cm 0cm 10pt"><SPAN lang=EN-US style="mso-ansi-language: EN-US"><FONT face=Calibri>Of the two kinds of DSL, internal and external, I believe internal DSLs, described by Paul Graham as </FONT><A href="http://www.paulgraham.com/progbot.html"><FONT face=Calibri>Programming Bottom-Up</FONT></A><FONT face=Calibri>, and </FONT><A href="http://www.martinfowler.com/bliki/FluentInterface.html"><FONT face=Calibri>Fluent Interfaces</FONT></A><FONT face=Calibri> to continue in the tradition of OO evolution.<o:p></o:p></FONT></SPAN></P><br />
<P class=MsoNormal style="MARGIN: 0cm 0cm 10pt"><SPAN lang=EN-US style="mso-ansi-language: EN-US"><FONT face=Calibri>I don’t think there will be any one practice that will bring about a dramatic jump in productivity as I look </FONT><A href="http://www.infoq.com/interviews/jaoo-future-of-software-development-panel"><FONT face=Calibri>10 years down the road</FONT></A><FONT face=Calibri>. I do believe that by embracing our collective lessons learned we can do just that. The best programmers aren’t 10, 20, 100 times more productive than the average because they type faster, if anything, they type a lot less. An ounce of prevention is worth a pound of cure, so too with design and debugging. <o:p></o:p></FONT></SPAN></P></p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/03/27/are-dsls-the-cure-to-oo%e2%80%99s-ails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Better Domain-Driven Design Implementation</title>
		<link>http://www.udidahan.com/2007/03/06/better-domain-driven-design-implementation/</link>
		<comments>http://www.udidahan.com/2007/03/06/better-domain-driven-design-implementation/#comments</comments>
		<pubDate>Tue, 06 Mar 2007 14:52:22 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Simplicity]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/archives/389</guid>
		<description><![CDATA[I just ran into a great example for explaining DDD in Ayende’s post “Entities, Services, and what goes between them”. Let’s just jump right into the code:

public class Order
{
       public virtual Money CalculateCost()
       {
              Money cost = Money.Zero;
              foreach (OrderLine line in OrderLines)
                     cost = cost.Add(line.Cost);   
              cost = cost.Add(this.ShippingCosts);
              return ApplyTaxes(cost);
       }
}
 

public class OrderService
{
       public [...]]]></description>
			<content:encoded><![CDATA[<p><span lang="EN-US"><font face="Calibri" size="3">I just ran into a great example for explaining DDD in Ayende’s post </font><a href="http://ayende.com/Blog/archive/2007/02/27/Entities-Services-and-what-goes-between-them.aspx"><font face="Calibri" size="3">“Entities, Services, and what goes between them”</font></a><font size="3"><font face="Calibri">. Let’s just jump right into the code:</font></font></span></p>
<p><span lang="EN-US"><font size="3"><font face="Calibri"><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><span lang="EN-US"><font size="3"><font face="Calibri" /><font size="3"><font face="Calibri"><font size="3"><span lang="EN-US"><font size="3"><font face="Calibri" /></font></span></font></font><font size="3"><font face="Calibri"><font size="3"><font face="Calibri"><font size="3"><span lang="EN-US"><font size="3"><font face="Calibri" /></font></span></font></font></font></font></font></font><font size="3"><font face="Calibri"><font size="3"><font size="3"><font face="Calibri"><font size="3"><font face="Calibri"><font size="3"><span lang="EN-US"><font size="3"><font face="Calibri" /></font></span></font></font></font></font></font></font></font></font></font></span></font><font size="3"><font face="Calibri"><font size="3"><font size="3"><font face="Calibri"><font size="3"><font size="3"><font face="Calibri"><font size="3"><font face="Calibri"><font size="3"><span lang="EN-US"><font size="3"><font face="Calibri" /></font></span></font></font></font></font></font></font></font></font></font></font></font></font></font></span></font></font></span><font size="3"><font face="Calibri"><font size="3"><font face="Calibri"><font size="3"><font face="Calibri"><font size="3"><font size="3"><font face="Calibri"><font size="3"><font size="3"><font face="Calibri"><font size="3"><font face="Calibri"><font size="3"><span lang="EN-US"><font size="3"><font face="Calibri"></p>
<div>public class Order<br />
{<br />
       public virtual Money CalculateCost()<br />
       {<br />
              Money cost = Money.Zero;<br />
              foreach (OrderLine line in OrderLines)<br />
                     cost = cost.Add(line.Cost);<span lang="EN">   </p>
<div>              cost = cost.Add(this.ShippingCosts);<br />
              return ApplyTaxes(cost);<br />
       }<br />
}</div>
<p> </p>
<p /></span></div>
<p>public class OrderService<br />
{<br />
       public virtual Money CalculateCostForOrder(int orderId)<br />
       {<br />
              Order order = Repository&lt;Order&gt;.FindOne(<br />
                     (Where.Order.Id == orderId).ToDetachedCriteria()<br />
                           .SetFetchMode(&#8221;OrderLines&#8221;, FetchMode.Eager));</p>
<p>               return order.CalculateCost();<br />
       }<br />
}</p>
<p><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><span lang="EN-US"><font size="3"><font face="Calibri">I’d like to improve this already great code.</font></font></span></font></font></font></span></p>
<p><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><span lang="EN-US" /></font></font></font></span><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><span lang="EN-US"><font size="3"><font face="Calibri">First of all, the fact that the OrderService just calls the CalculateCost method on the Order object is great. What is interesting is how it knows that the implementation of that method requires the OrderLines to be fetched. From a performance perspective, this is absolutely correct. We want to hit the database only once, so eager fetching is good. What I would like to do is to take this knowledge a collocate it with who should know it.</font></font></span></font></font></font></span></p>
<p><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><span lang="EN-US" /></font></font></font></span><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><span lang="EN-US"><font size="3"><font face="Calibri">Well, the class that absolutely knows about the fact that OrderLines are required for the CalculateCost method is the Order class. However, the OrderService is the one that needs to make use of the fetching strategy, so there needs to be some way for us to communicate this. I usually use an interface to represent a role that (9 times out of 10) has a single fetching strategy.</font></font></span></font></font></font></span></p>
<p><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><span lang="EN-US" /></font></font></font></span><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><span lang="EN-US"><font size="3"><font face="Calibri">The two common cases where fetching strategy differs is when fetching the object “for read” – in other words, to show data to the user, and the other is “for write” – in essence calling methods on the object which change its state. The third, somewhat less common case is “for calculation” which is described above. We could model these as IOrderInfo, IOrder, and IOrderCalculator respectively – with each of them exposing the relevant properties, methods, and events. By and large, we would have one class implement all these interfaces, but this isn’t a hard and fast rule.</font></font></span></font></font></font></span><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"> </font></font></font></span><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><span lang="EN-US"><font size="3"><font face="Calibri"> </font></font></span></font></font></font></span></p>
<p><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><span lang="EN-US"><font size="3"><font face="Calibri">Now, imagine that there was an interface called IFetchingStrategy. Also, imagine we had a factory which created objects implementing it based on some type we gave them – let’s call that IFetchingStrategyFactory. In it we could find that under the type IOrderCalculator was a fetching strategy describing eager loading for OrderLines. Our generic repository could go to the IFetchingStrategyFactory automatically, without the service getting involved. This would simplify the service code:</font></font></span></font></font></font></span><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"> </font></font></font></span><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><font size="3"><font face="Calibri"><br />
</font></font></font></font></font></span></p>
<p><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><font size="3"><font face="Calibri" /></font></font></font></font></span></p>
<p><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><font size="3"><font face="Calibri">public class OrderService<br />
{<br />
       public virtual Money CalculateCostForOrder(int orderId)<br />
       {<br />
              IOrderCalculator order = Repository&lt;IOrderCalculator&gt;.FindOne(<br />
                     (Where.Order.Id == orderId));<br />
<span lang="EN">                           </span><span lang="EN"><br />
</span>              return order.CalculateCost();<br />
       }<br />
}<span lang="EN"><br />
</span></font></font><font size="3"><font face="Calibri"><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><span lang="EN-US"><font size="3"><font face="Calibri"> </font></font></span></font></font></font></span></font></font></font></font></font></span></p>
<p><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><font size="3"><font face="Calibri"><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><span lang="EN-US"><font size="3"><font face="Calibri">But the issue here isn’t just simplicity, but the Single Responsibility Principle – or that each class should have only one reason to change. Should the fetching strategy change, the OrderService class would not have to change.</font></font></span></font></font></font></span><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><span lang="EN-US" /></font></font></font></span><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><span lang="EN-US"><font size="3"><font face="Calibri">Moving forward with this, we realize that when OrderLines are loaded for an IOrderCalculator, they don’t need their connection to the Product. In which case, it might make sense for us to have a separate class, OrderCalculator, and not just Order. OrderCalculator would contain a list of OrderLines, but not as IList, but rather IList&lt;IOrderLineForCalculation&gt;. Using a sufficiently intelligent O/R mapper, we could map the class OrderLine with a fetching strategy as well, so that when it is requested as IOrderLineForCalculation, the Product association would not be traversed. Of course, when using simpler O/R mappers we might have to create a new class.</font></font></span></font></font></font></span></font></font></font></font></font></span><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><font size="3"><font face="Calibri"> </font></font></font></font></font></span><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><font size="3"><font face="Calibri" /></font></font></font></font></span><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><font size="3"><font face="Calibri" /></font></font></font></font></span><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><font size="3"><font face="Calibri"> </p>
<p></font></font><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><span lang="EN-US" /></font></font></font></span><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><span lang="EN-US"><font size="3"><font face="Calibri">This may seem like a lot of trouble to go to. It actually isn’t. It’s pretty much just a different way to package the code you already wrote. Yes, there are more interfaces, and probably more classes, but the amount of business logic code is the same. I’ve been able to keep performance high with this design, but increase its maintainability. I measure maintainability as both the amount of time, and number of changes that need to be made by a programmer familiar with the design. Learnability (?) is often called maintainability, but I think that it’s something else. This design may not be as learnable– meaning it would take a given programmer longer to learn this design than the previous one. I submit that the increased maintainability outweighs the increased learnability substantially.</font></font></span></font></font></font></span><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"> </font></font></font></span> </p>
<p><span lang="EN-US" /><span lang="EN-US"><font size="3"><font face="Calibri"><font size="3"><span lang="EN-US"><font size="3"><font face="Calibri">I would love to see some standardization around these principles, making it easier to change O/R mapping tools and decreasing the learning curve for developers changing tools. In my opinion, these principles are key to moving the implementation and adoption of <a href="http://udidahan.weblogs.us/category/ddd/">Domain-Driven Design</a> and <a href="http://udidahan.weblogs.us/category/nhibernate/">O/R mapping</a> forwards, specifically in handling the problematic performance perception in data-driven environments like most enterprises.</font></font></span></font></font></font></span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/03/06/better-domain-driven-design-implementation/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>Paratechnological value</title>
		<link>http://www.udidahan.com/2007/03/06/paratechnological-value/</link>
		<comments>http://www.udidahan.com/2007/03/06/paratechnological-value/#comments</comments>
		<pubDate>Tue, 06 Mar 2007 09:28:23 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/archives/388</guid>
		<description><![CDATA[Technological churn &#8211; it&#8217;s a killer. It appears that as time goes by, the deluge just increases. I almost went into management because of it. Well, to be more precise, I do (kinda) manage, but I mean that I almost left the whole technology/engineering side of things. Luckily there&#8217;s more to software than that. Specifically [...]]]></description>
			<content:encoded><![CDATA[<p><span style="font-size: 11pt; font-family: 'Calibri','sans-serif'; mso-ascii-theme-font: minor-latin; mso-hansi-theme-font: minor-latin">Technological churn &#8211; it&#8217;s a killer. It appears that as time goes by, the <a href="http://ayende.com/Blog/archive/2007/03/06/How-are-you-keeping-up-with-this-deluge-of-technology.aspx">deluge just increases</a>. I almost went into management because of it. Well, to be more precise, I do (kinda) manage, but I mean that I almost left the whole technology/engineering side of things. Luckily there&#8217;s more to software than that. Specifically the things around technology that aren&#8217;t technology dependent &#8211; paratechnological (from paralegal) if you will.</span></p>
<p><span style="font-size: 11pt; font-family: 'Calibri','sans-serif'; mso-ascii-theme-font: minor-latin; mso-hansi-theme-font: minor-latin">The most interesting thing is that the knowledge investment you make in paratechnology has a (much) longer lifespan than that in technology directly. Those of us who have perfected our skills in VB6 found that .NET obseleted much of that. The same is true for Microsoft&#8217;s Web Service Enhancements, EJBs, etc. Even the languages themselves are changing substantially &#8211; as are their runtimes. However, object-orientation seems to be holding its own well into its 3rd decade. I suspect Domain-Driven Design (DDD) to enjoy a long life as well. </span><span style="font-size: 11pt; font-family: 'Calibri','sans-serif'; mso-ascii-theme-font: minor-latin; mso-hansi-theme-font: minor-latin"><span style="font-size: 11pt; font-family: 'Calibri','sans-serif'; mso-ascii-theme-font: minor-latin; mso-hansi-theme-font: minor-latin">Beyond just being a lifetime issue, these paratechnological entities just seem to build on each other more and more. In order to understand higher order patterns, lower one need to be understood first. These patterns increase the scale of the problems that can be solved repeatably. </span></p>
<p></span><span style="font-size: 11pt; font-family: 'Calibri','sans-serif'; mso-ascii-theme-font: minor-latin; mso-hansi-theme-font: minor-latin">It has been my experience that those developers with similar experience-in-years, but only technological knowledge, are less productive than their peers with more paratechnological knowledge. I measure productivity in terms of number of feature points per unit of time. I understand that this is biased against infrastructure developers in application development teams &#8211; but I haven&#8217;t figured out how to measure them yet (at least, not well enough to say anything about it).</span></p>
<p><span style="font-size: 11pt; font-family: 'Calibri','sans-serif'; mso-ascii-theme-font: minor-latin; mso-hansi-theme-font: minor-latin">Therefore, it is my thesis that developers should spend <em><span style="font-family: 'Calibri','sans-serif'; mso-ascii-theme-font: minor-latin; mso-hansi-theme-font: minor-latin">at least</span></em> the same amount of time investing in paratechnological learning as technological learning. It is my suggestion that a 3-to-1 ratio would be even better &#8211; as in only a quarter of your time on technological study. I submit that the on-the-job work done with a given technology, including the figuring out how to do something that you haven&#8217;t done before, is enough. When I&#8217;m talking about &#8220;study&#8221;, I&#8217;m referring to courses, conferences, books read (not when looking sometime up). </span></p>
<p><span style="font-size: 11pt; font-family: 'Calibri','sans-serif'; mso-ascii-theme-font: minor-latin; mso-hansi-theme-font: minor-latin">For me, the way that I find out (most) of what I need to know about a technology (not necessarily new), is to grill an expert on it. For instance, at TechEd Developers Barcelona 2006, I had the good fortune to sit with the <a href="http://ayende.com/Blog/archive/2007/03/06/How-are-you-keeping-up-with-this-deluge-of-technology.aspx">Workflow Foundation guys for at least an hour</a>, the WCF guys for about 3 hours total, WPF for half an hour, and the CAB guys for almost 4 hours &#8211; not all in one sitting <img src='http://www.udidahan.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Anyway, it was mostly me asking how to solve thorny issues I&#8217;m having difficulty with in my projects, and them trying to explain to me, in a way I&#8217;d understand, that most people don&#8217;t have my problems. Personally, I think that, if that&#8217;s true, &#8220;most people&#8221; just haven&#8217;t noticed yet <img src='http://www.udidahan.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  There were also numerous new ways of doing things that I didn&#8217;t consider to be an issue, so I tried to focus my learning on other things.</span></p>
<p><span style="font-size: 11pt; font-family: 'Calibri','sans-serif'; mso-ascii-theme-font: minor-latin; mso-hansi-theme-font: minor-latin">And I guess that that&#8217;s my bottom line. When new technology comes along, you shouldn&#8217;t need to &#8220;start over&#8221;. The way that I design my systems, most technology is hidden away. WPF changes how my views are implemented &#8211; but that&#8217;s tucked behind an interface so that my supervising controllers don&#8217;t care. WCF changes how messages are transferred over the network, but that&#8217;s tucked away behind an &#8220;IBus&#8221; interface; message dispatch is also abstracted with &#8220;IMessageHandler&#8221; and &#8220;IMessage&#8221;. </span><span style="font-size: 11pt; font-family: 'Calibri','sans-serif'; mso-ascii-theme-font: minor-latin; mso-hansi-theme-font: minor-latin"> </span><span style="font-size: 11pt; font-family: 'Calibri','sans-serif'; mso-ascii-theme-font: minor-latin; mso-hansi-theme-font: minor-latin">By the way, I find WPF to be very interesting in improving the human-to-human interface between Human-Computer Interaction (HCI) professionals and developers. </span></p>
<p><span style="font-size: 11pt; font-family: 'Calibri','sans-serif'; mso-ascii-theme-font: minor-latin; mso-hansi-theme-font: minor-latin">So&#8230; Invest wisely. Compound interest is your friend.</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/03/06/paratechnological-value/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Was I unclear about DDD?</title>
		<link>http://www.udidahan.com/2006/10/19/was-i-unclear-about-ddd/</link>
		<comments>http://www.udidahan.com/2006/10/19/was-i-unclear-about-ddd/#comments</comments>
		<pubDate>Fri, 20 Oct 2006 05:34:52 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[DDD]]></category>

		<guid isPermaLink="false">http://wp_630.weblogs.us/archives/336</guid>
		<description><![CDATA[Thomas Wagner gave me some apparently undue <a href="http://wagnerblog.com/wp-trackback.php/678">props</a> around my recent post <a href="http://udidahan.weblogs.us/archives/036972.html">"DDD - why bother?"</a>. If I wasn't clear about the bottom line around DDD, here it is again:
<br/><br/>
"if you are the one tasked with building the right system, you just won’t be able to do it unless you build the system right – DDD won’t be a bother, but a necessity."
<br/><br/>
I read the entire <a href="http://toolsandhacks.com/?page_id=15">"rant"</a> on Thomas' site and can't say that I disagree with a lot of it. On the other hand, that doesn't mean it's the whole truth - if there even is such a thing. As one of the co-authors of Jimmy's book, “Applying Domain Driven Design and Patterns”, as well as a technical reviewer on it, I came away with a very different view on DDD than Thomas did.
<br/><br/>
Finally, I think that it's good that we have names for things. DDD makes a point of naming and connecting various patterns - new and existing. The value comes in being able to identify a practice as well as have meaningful discussions about it. How would our conversations sound without named patterns? 
<br/><br/>
"That thing where you got objects that aren't dependent on persistence - no, the one where they don't have the save method on them..."
<br/><br/>
Also, patterns are meant to evolve. I hope that Thomas will be able to take his considerable experience and move forwards the level of conversations we are having around large-scale systems design.]]></description>
			<content:encoded><![CDATA[<p>Thomas Wagner gave me some apparently undue <a href="http://wagnerblog.com/wp-trackback.php/678">props</a> around my recent post <a href="http://udidahan.weblogs.us/2006/10/07/ddd-%e2%80%93-why-bother/">&#8220;DDD &#8211; why bother?&#8221;</a>. If I wasn&#8217;t clear about the bottom line around DDD, here it is again:</p>
<p>&#8220;if you are the one tasked with building the right system, you just won’t be able to do it unless you build the system right – DDD won’t be a bother, but a necessity.&#8221;</p>
<p>I read the entire <a href="http://toolsandhacks.com/?page_id=15">&#8220;rant&#8221;</a> on Thomas&#8217; site and can&#8217;t say that I disagree with a lot of it. On the other hand, that doesn&#8217;t mean it&#8217;s the whole truth &#8211; if there even is such a thing. As one of the co-authors of Jimmy&#8217;s book, “Applying Domain Driven Design and Patterns”, as well as a technical reviewer on it, I came away with a very different view on DDD than Thomas did.</p>
<p>Finally, I think that it&#8217;s good that we have names for things. DDD makes a point of naming and connecting various patterns &#8211; new and existing. The value comes in being able to identify a practice as well as have meaningful discussions about it. How would our conversations sound without named patterns? </p>
<p>&#8220;That thing where you got objects that aren&#8217;t dependent on persistence &#8211; no, the one where they don&#8217;t have the save method on them&#8230;&#8221;</p>
<p>Also, patterns are meant to evolve. I hope that Thomas will be able to take his considerable experience and move forwards the level of conversations we are having around large-scale systems design.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2006/10/19/was-i-unclear-about-ddd/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>DDD – why bother?</title>
		<link>http://www.udidahan.com/2006/10/07/ddd-%e2%80%93-why-bother/</link>
		<comments>http://www.udidahan.com/2006/10/07/ddd-%e2%80%93-why-bother/#comments</comments>
		<pubDate>Sun, 08 Oct 2006 05:49:08 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Business Rules]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[OO]]></category>

		<guid isPermaLink="false">http://wp_630.weblogs.us/archives/332</guid>
		<description><![CDATA[Domain Driven Design (DDD), alongside its growing popularity, is experiencing some growing pains. The Domain Model pattern, documented in the Patterns of Enterprise Application Architecture book, is at the heart of DDD yet the division of responsibility between it and other DDD patterns like Service Layer isn’t quite clear. To make matters worse, the value of the Domain Model pattern relative to simpler code-generation techniques remains vague. The one thing that has reached a wide consensus is that it requires a higher level of skill to employ these techniques than continue using the widespread procedural programming practices. There is one overwhelming reason to do it anyway, though, and that is that it is the cheapest way to get a system up and running right. The reasoning behind this has to do with business rules...]]></description>
			<content:encoded><![CDATA[<p>Domain Driven Design (DDD), alongside its growing popularity, is experiencing some growing pains. The <a href="http://udidahan.weblogs.us/2007/04/21/domain-model-pattern/">Domain Model pattern</a>, documented in the Patterns of Enterprise Application Architecture book, is at the heart of DDD yet the division of responsibility between it and other DDD patterns like Service Layer isn’t quite clear. To make matters worse, the value of the Domain Model pattern relative to simpler code-generation techniques remains vague. The one thing that has reached a wide consensus is that it requires a higher level of skill to employ these techniques than continue using the widespread procedural programming practices. There is one overwhelming reason to do it anyway, though, and that is that it is the cheapest way to get a system up and running right. The reasoning behind this has to do with <a href="http://udidahan.weblogs.us/category/business-rules/">business rules</a>.</p>
<p>An exceedingly large number of systems are being built and modified today in order to support business rules. Beyond just computerizing the management of data in the enterprise, today’s systems are required to computerize the business processes that use that data, and these processes are built upon business rules.</p>
<p>A rule is composed of two main elements, a clause and an action. The clause defines under what circumstances the action is to be activated. An example of a rule employed in the business environment might be “if the customer is a preferred customer, then give them a 5% discount on all orders”. The rich behavior of an enterprise is governed by these interacting rules. Consider the result of adding another business rule like “if the customer has ordered $100,000 or more in the last year, then they are to be considered a preferred customer”. If a customer is not preferred, but then sends in a new order that puts them over the limit, how is the system to behave? Conversely, what if a preferred customer cancels an order bringing them under the limit?</p>
<p>I’ve seen too many projects that have been tasked with implementing these kinds of behaviors yet were unable to get the system running right. Customers that should have gotten discounts didn’t in some cases, and those that should not have enjoyed a discount did at times. After much time was spent trying to track down what part of the code was wrong, changing some code, testing, over and over again, an executive decision was made to put the system into production as is. The harm to the business was deemed cheaper in this case then not putting the system in production. Is it any wonder that business is skeptical of IT’s ability to handle the agile enterprise of the future where, not only will the business rules be more complex, they will be changing all the time.</p>
<p>The Domain Model pattern encapsulates these business rules in such a way that they will be run even when not directly invoked. This is especially critical when one rule triggers another. Intelligent use of <a href="http://udidahan.weblogs.us/category/oo/">OO principles</a> when designing the domain can help you altogether avoid the jump in complexity found in Business Rules Engines.</p>
<p>Finally, we need to understand that supporting techniques like <a href="http://udidahan.weblogs.us/category/nhibernate/">Object/Relational (O/R) mapping</a> are but a means, and not the end. The discussions around DDD often get mired down in the relative costs of O/R mapping and procedural code generation. Persistence is a solved problem, a technical problem that has no meaning to business. Is it not time to raise the discussion to the level of business? If the only problem you are trying to solve is the manipulation of data in a database, then don’t bother with DDD and its descendents. It won’t make your life any easier. If, on the other hand, business has gotten sick of IT deciding for them how to run their business; if you are the one tasked with building the right system, you just won’t be able to do it unless you build the system right – DDD won’t be a bother, but a necessity.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2006/10/07/ddd-%e2%80%93-why-bother/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>DDD the opposite of SOA? Uh, no.</title>
		<link>http://www.udidahan.com/2006/09/04/ddd-the-opposite-of-soa-uh-no/</link>
		<comments>http://www.udidahan.com/2006/09/04/ddd-the-opposite-of-soa-uh-no/#comments</comments>
		<pubDate>Tue, 05 Sep 2006 02:37:04 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[DDD]]></category>

		<guid isPermaLink="false">http://wp_630.weblogs.us/archives/313</guid>
		<description><![CDATA[Just recently the .Net Rocks crew <a href="http://www.dotnetrocks.com/default.aspx?showID=194">interviewed</a> <a href="http://www.jnsk.se/weblog">Jimmy Nilsson</a> on <a href="http://domaindrivendesign.org/">Domain Driven Design</a> (DDD). In the first half, <a href="http://www.campbellassociates.ca/blog">Richard Campbell</a> describes SOA as the opposite of DDD, where SOA "very much is a set of technologies, that are going around trying to find a problem to solve", and DDD is based on focusing on the problem and designing a solution for that problem. 
<br/><br/>
Despite my high regard for Richard, I must say that he missed the boat on this one. Maybe the only thing that has achieved industry-wide agreement in terms of SOA is that it is NOT a technology.
<br/><br/>
Just so as there's full disclosure here, I was the person to write the section on SOA for Jimmy's book <a href="http://www.amazon.com/exec/obidos/tg/detail/-/0321268202">"Applying Domain Driven Design &#038; Patterns"</a>.
<br/><br/>
As for the relationship between DDD and SOA, they are not opposites. It would be more appropriate to say that they are orthogonal. You can employ DDD on an application without SOA, and conversely you could employ SOA without DDD. Although I believe that many principles of service-orientation are applicable in most distributed systems, I feel that DDD has much broader applicability and would suggest training your staff in DDD before going to SOA.
<br/><br/>
As for the question "where would you see DDD in a service-oriented solution?" Well, my answer would be that the domain model would be nicely encapsulated by a single service. The activities exposed by the domain model could also impact the message-exchange patterns that the service supports, although sometimes higher level constructs are needed. Paul Gielens' <a href="http://weblogs.asp.net/pgielens/archive/2006/09/03/Domain-Model-Service.aspx">last post on the subject</a>, as well as <a href="http://weblogs.asp.net/pgielens/archive/2006/05/31/Applying-the-Application-Layer-in-Domain-Driven-Design.aspx">a bit of the discussion on an eariler post</a> shows just how trivial it ISN'T :)
<br/><br/>
Anyhow, I just wanted to straighten that out.]]></description>
			<content:encoded><![CDATA[<p>Just recently the .Net Rocks crew <a href="http://www.dotnetrocks.com/default.aspx?showID=194">interviewed</a> <a href="http://www.jnsk.se/weblog">Jimmy Nilsson</a> on <a href="http://domaindrivendesign.org/">Domain Driven Design</a> (DDD). In the first half, <a href="http://www.campbellassociates.ca/blog">Richard Campbell</a> describes SOA as the opposite of DDD, where SOA &#8220;very much is a set of technologies, that are going around trying to find a problem to solve&#8221;, and DDD is based on focusing on the problem and designing a solution for that problem. </p>
<p>Despite my high regard for Richard, I must say that he missed the boat on this one. Maybe the only thing that has achieved industry-wide agreement in terms of SOA is that it is NOT a technology.</p>
<p>Just so as there&#8217;s full disclosure here, I was the person to write the section on SOA for Jimmy&#8217;s book <a href="http://www.amazon.com/exec/obidos/tg/detail/-/0321268202">&#8220;Applying Domain Driven Design &amp; Patterns&#8221;</a>.</p>
<p>As for the relationship between DDD and SOA, they are not opposites. It would be more appropriate to say that they are orthogonal. You can employ DDD on an application without SOA, and conversely you could employ SOA without DDD. Although I believe that many principles of service-orientation are applicable in most distributed systems, I feel that DDD has much broader applicability and would suggest training your staff in DDD before going to SOA.</p>
<p>As for the question &#8220;where would you see DDD in a service-oriented solution?&#8221; Well, my answer would be that the domain model would be nicely encapsulated by a single service. The activities exposed by the domain model could also impact the message-exchange patterns that the service supports, although sometimes higher level constructs are needed. Paul Gielens&#8217; <a href="http://weblogs.asp.net/pgielens/archive/2006/09/03/Domain-Model-Service.aspx">last post on the subject</a>, as well as <a href="http://weblogs.asp.net/pgielens/archive/2006/05/31/Applying-the-Application-Layer-in-Domain-Driven-Design.aspx">a bit of the discussion on an eariler post</a> shows just how trivial it ISN&#8217;T <img src='http://www.udidahan.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Anyhow, I just wanted to straighten that out.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2006/09/04/ddd-the-opposite-of-soa-uh-no/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>To map, or not to map?</title>
		<link>http://www.udidahan.com/2006/03/11/to-map-or-not-to-map/</link>
		<comments>http://www.udidahan.com/2006/03/11/to-map-or-not-to-map/#comments</comments>
		<pubDate>Sun, 12 Mar 2006 04:22:00 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[ADO.NET]]></category>
		<category><![CDATA[Business Rules]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[OO]]></category>

		<guid isPermaLink="false">http://wp_630.weblogs.us/archives/267</guid>
		<description><![CDATA[I had this discussion with Clemens when he was last here in Israel - his position, as was so eloquently stated <a href="http://friends.newtelligence.net/clemensv/CommentView,guid,0fbf07a9-9e7a-4db4-a305-58250ac57a73.aspx">here</a>, was against, while I was pro. The question he raised "To map, or not to map?" he himself answered, "to map". The question remaining was how to map; write the sql yourself, or let some tool write/generate it for you.
<br/><br/>
The overarching question is: what do you REALLY gain by O/R mapping?
<br/><br/>
(As an aside, among the comments of his post are those using the acronym ORM. Please stop - that acronym is already taken by Object Role Modeling.)
<br/><br/>
I've been using O/R mapping techniques on mission critical projects for some time now, and if I wanted to compare it to what I did before, it would not be to writing all the sql by hand. I don't remember ever doing that - there was always code generation involved. Because, let's face it - there's a lot of drudgery involved for things that aren't performance critical. No reason to do THAT by hand.
<br/><br/>
So, for me, the ONE THING that O/R mapping gives me better than what I did before is this:
<br/><br/>
O/R mapping gets me better object-oriented business logic.
<br/><br/>
That's it.
<br/><br/>
Like Clemens said, if you "don't know SQL and RDBMS technology in any reasonable depth", don't expect to get good performance. Obviously this is true for any technique. But I guess that empirically speaking, the percentage of people without said knowledge is larger in the group where you don't HAVE to write sql.
<br/><br/>
So, I'll bet you're asking yourself, "if that's all Udi gets from O/R mapping, why does he keep doing it?" Or maybe you're asking yourself "should I get a beer? This is getting long..."
<br/><br/>
The fact of the matter is that I don't know a better way to write business logic than by using OO techniques. I grant that data is important, but the reason that many applications are built is business logic - there's something that this new system can/should do, that the old systems couldn't (often using the same data).
<br/><br/>
If I could sum up my understanding of Clemens position, it would be this: 
<br/><br/>
A lot of developers probably aren't experienced, or knowledgeable enough the use O/R mapping well. Therefore writing the sql yourself is better.
<br/><br/>
While I agree with the first statement, and I think that the same could be said about communication, threading, .net and many other things, I don't think that the conclusion logically follows.
<br/><br/>
So, I guess I would sum up my position like this:
<br/><br/>
If you would like to develop a persistent domain model, O/R mapping techniques will probably help you. If you would like your solution to perform well, you should probably learn how databases work, as well as what the O/R mapping tool does under the covers.]]></description>
			<content:encoded><![CDATA[<p>I had this discussion with Clemens when he was last here in Israel &#8211; his position, as was so eloquently stated <a href="http://friends.newtelligence.net/clemensv/CommentView,guid,0fbf07a9-9e7a-4db4-a305-58250ac57a73.aspx">here</a>, was against, while I was pro. The question he raised &#8220;To map, or not to map?&#8221; he himself answered, &#8220;to map&#8221;. The question remaining was how to map; write the sql yourself, or let some tool write/generate it for you.</p>
<p>The overarching question is: what do you REALLY gain by O/R mapping?</p>
<p>(As an aside, among the comments of his post are those using the acronym ORM. Please stop &#8211; that acronym is already taken by Object Role Modeling.)</p>
<p>I&#8217;ve been using O/R mapping techniques on mission critical projects for some time now, and if I wanted to compare it to what I did before, it would not be to writing all the sql by hand. I don&#8217;t remember ever doing that &#8211; there was always code generation involved. Because, let&#8217;s face it &#8211; there&#8217;s a lot of drudgery involved for things that aren&#8217;t performance critical. No reason to do THAT by hand.</p>
<p>So, for me, the ONE THING that O/R mapping gives me better than what I did before is this:</p>
<p>O/R mapping gets me better object-oriented business logic.</p>
<p>That&#8217;s it.</p>
<p>Like Clemens said, if you &#8220;don&#8217;t know SQL and RDBMS technology in any reasonable depth&#8221;, don&#8217;t expect to get good performance. Obviously this is true for any technique. But I guess that empirically speaking, the percentage of people without said knowledge is larger in the group where you don&#8217;t HAVE to write sql.</p>
<p>So, I&#8217;ll bet you&#8217;re asking yourself, &#8220;if that&#8217;s all Udi gets from O/R mapping, why does he keep doing it?&#8221; Or maybe you&#8217;re asking yourself &#8220;should I get a beer? This is getting long&#8230;&#8221;</p>
<p>The fact of the matter is that I don&#8217;t know a better way to write business logic than by using OO techniques. I grant that data is important, but the reason that many applications are built is business logic &#8211; there&#8217;s something that this new system can/should do, that the old systems couldn&#8217;t (often using the same data).</p>
<p>If I could sum up my understanding of Clemens position, it would be this: </p>
<p>A lot of developers probably aren&#8217;t experienced, or knowledgeable enough the use O/R mapping well. Therefore writing the sql yourself is better.</p>
<p>While I agree with the first statement, and I think that the same could be said about communication, threading, .net and many other things, I don&#8217;t think that the conclusion logically follows.</p>
<p>So, I guess I would sum up my position like this:</p>
<p>If you would like to develop a persistent domain model, O/R mapping techniques will probably help you. If you would like your solution to perform well, you should probably learn how databases work, as well as what the O/R mapping tool does under the covers.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2006/03/11/to-map-or-not-to-map/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
