<?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; NHibernate</title>
	<atom:link href="http://www.udidahan.com/category/nhibernate/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 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>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>Fetching Strategy NHibernate Implementation Available</title>
		<link>http://www.udidahan.com/2007/09/16/fetching-strategy-nhibernate-implementation-available/</link>
		<comments>http://www.udidahan.com/2007/09/16/fetching-strategy-nhibernate-implementation-available/#comments</comments>
		<pubDate>Mon, 17 Sep 2007 00:54:02 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[ADO.NET]]></category>
		<category><![CDATA[Caching]]></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[Performance]]></category>
		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/09/16/fetching-strategy-nhibernate-implementation-available/</guid>
		<description><![CDATA[A couple of months ago I put out a post discussing one way to implement custom fetching strategies. Anyway, I finally got around to putting my money where my mouth was&#8230;
So, I&#8217;ve implemented the pattern in NHibernate, adding the following method to ISession:
T Create&#60;T&#62;();
As well as adding the following interface to the NHibernate package:

  [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of months ago I put out a <a href="http://udidahan.weblogs.us/2007/04/23/fetching-strategy-design/">post discussing one way to implement custom fetching strategies</a>. Anyway, I finally got around to putting my money where my mouth was&#8230;</p>
<p>So, I&#8217;ve implemented the pattern in NHibernate, adding the following method to ISession:</p>
<div style="border: solid black 1px; background-color:beige; padding: 0em 1em; overflow:auto; width:550; font-family:courier">T Create&lt;T&gt;();</div>
<p>As well as adding the following interface to the NHibernate package:</p>
<div style="border: solid black 1px; background-color:beige; padding: 0em 1em; overflow:auto; width:550; font-family:courier">
    public interface IFetchingStrategy&lt;T&gt;<br />
    {<br />
        ICriteria AddFetchJoinTo(ICriteria criteria);<br />
    }
</div>
<p>All this enables you to have a stronger separation between your service layer classes and your domain model class, as well as for you to express each service-level use case as a domain concept &#8211; an interface.</p>
<p>Once you have such an interface, you can create a fetching strategy for that use case and define exactly how deep of an object graph you want to load so that you only hit the DB once for that use case.</p>
<p>The nice thing is that its all configured with Spring. In other words, if you the entry for your fetching strategy class exists, you get the improved performance, if it doesn&#8217;t, you don&#8217;t. All without touching your service layer classes.</p>
<p>Just as an example, when I&#8217;m in the use case modeled by &#8220;ICustomer&#8221;, I want to get all the customer&#8217;s orders, and their orderlines. This would be done by having a class like this:</p>
<div style="border: solid black 1px; background-color:beige; padding: 0em 1em; overflow:auto; width:550; font-family:courier">
    public class CustomerFetchingStrategy : IFetchingStrategy&lt;ICustomer&gt;<br />
    {<br />
        public ICriteria AddFetchJoinTo(ICriteria criteria)<br />
        {<br />
            criteria.SetFetchMode(&#8221;orders&#8221;, FetchMode.Eager).<br />
                SetFetchMode(&#8221;orders.orderLines&#8221;, FetchMode.Eager);</p>
<p>            return criteria;<br />
        }<br />
    }
</p></div>
<p>And the configuration would look like this (as a part of the regular spring template):</p>
<div style="border: solid black 1px; background-color:beige; padding: 0em 1em; overflow:auto; width:550; font-family:courier">
      &lt;object id=&#8221;CustomerFetchingStrategy&#8221; type=&#8221;Domain.Persistence.CustomerFetchingStrategy, Domain.Persistence&#8221; /&gt;
</div>
<p>If you want to take a look at the full solution, you can find it here. For some reason, the combined file was too big for the upload on my blog so it&#8217;s split into two. Unzip both packages into the same directory. You&#8217;ll find a file called &#8220;db_scripts.sql&#8221; which contains the schema for the DB. Don&#8217;t forget to update your connection string in the &#8220;hibernate.cfg.xml&#8221;. If you&#8217;re looking for the changes I made to the NHibernate source, you can find it in the &#8220;Updated NHibernate Files&#8221; directory. The only real change is to the &#8220;SessionImpl.cs&#8221; file.</p>
<p><a href='http://udidahan.weblogs.us/wp-content/uploads/libraries.zip' title='libraries.zip'>Relevant NHibernate and Spring binaries</a>.</p>
<p><a href='http://udidahan.weblogs.us/wp-content/uploads/objectrelationalmappingdemo4.zip' title='objectrelationalmappingdemo.zip'>Source code of example</a>.</p>
<p>BTW, there is some intelligent thread-safe caching going on in SessionImpl now so that you get a much smaller performance hit (in terms of code that uses reflection) on subsequent usages of the same interfaces.</p>
<p>Let me know what you think.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/09/16/fetching-strategy-nhibernate-implementation-available/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</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>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>Product-Driven Architecture and O/R Mapping</title>
		<link>http://www.udidahan.com/2007/02/22/product-driven-architecture-and-or-mapping/</link>
		<comments>http://www.udidahan.com/2007/02/22/product-driven-architecture-and-or-mapping/#comments</comments>
		<pubDate>Thu, 22 Feb 2007 14:19:29 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/02/22/product-driven-architecture-and-or-mapping/</guid>
		<description><![CDATA[Published in Developer.com
Summary: The single, most important trap to watch out for when choosing an object-relational mapping tool is this: &#8220;Product-Driven Architecture&#8221;. PDA is a term I use to describe a set of symptoms that I&#8217;ve seen in projects over the years. In these projects, entire teams would spend months agonizing over product comparison tables, [...]]]></description>
			<content:encoded><![CDATA[<p>Published in <a href="http://www.developer.com">Developer.com</a></p>
<p><b>Summary:</b> The single, most important trap to watch out for when choosing an object-relational mapping tool is this: &#8220;Product-Driven Architecture&#8221;. PDA is a term I use to describe a set of symptoms that I&#8217;ve seen in projects over the years. In these projects, entire teams would spend months agonizing over product comparison tables, debating the importance and rankings of various features, all without a coherent architecture.</p>
<p><a href="http://www.developer.com/design/article.php/3531871">Continue reading.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/02/22/product-driven-architecture-and-or-mapping/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dataset – O/R mapping rumble at TechEd MVP Dinner</title>
		<link>http://www.udidahan.com/2006/11/09/dataset-%e2%80%93-or-mapping-rumble-at-teched-mvp-dinner/</link>
		<comments>http://www.udidahan.com/2006/11/09/dataset-%e2%80%93-or-mapping-rumble-at-teched-mvp-dinner/#comments</comments>
		<pubDate>Thu, 09 Nov 2006 13:11:05 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[ADO.NET]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Business Rules]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[DataSets]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Scalability]]></category>

		<guid isPermaLink="false">http://wp_630.weblogs.us/archives/348</guid>
		<description><![CDATA[So, last night I was at the MVP dinner in TechEd and everything was nice. We had a nice meal, conversation was nice, weather was… nice. And then the volume started to rise, slowly at first, so as you don’t quite notice it. After a bit, you kind of stop talking and look around. And then I hear it…
<br/><br/>
&#60;WWF announcer voice&#62;<br/>
Are you ready… to RUMBLE !?!?<br/>
&#60;/WWF announcer voice&#62;<br/>
<br/>
It was datasets vs. O/R mapping, a slight twist on the infamous datasets vs. custom objects debate, all over again. They pulled me in, kicking and screaming, I swear, I really do. The lines were drawn, maintainability, performance, all the things that architects like to philosophize about in terms of other people’s work.
<br/><br/>
Anyway, I won’t give you the play-by-play ‘cause we were there almost all night. I’ll just cut to the chase.
<br/><br/>
First things first – any comparison of solutions without the context of a problem leads nowhere, fast, and stays there. So the first question I asked (when I got the chance to speak) was “are we talking about querying/reporting here?” and the answer was something like “well, yeah, but a lot of other things too”. So my suggestion was that we discuss the solutions in terms of two contexts -  querying/reporting and OLTP.
<br/><br/>
What I mean by OLTP is the data-updating kind of work that you do on certain items. Examples of this include “insert order”, “change customer address”, and “discount product”. Querying/reporting doesn’t change data, and often involves dealing with large sets of data pulled from different kinds of entities (in ERD terms).
<br/><br/>
Luckily, my suggestion to deal with them separately was accepted. Secondly, I proposed that an object model (specifically implementing the Domain Model pattern) designed for OLTP would perform poorly when used for querying/reporting – simply because it wasn’t designed for it. The structure of a domain model is such that it makes it possible to define / implement business rules in one place. That’s possible, not easy. 
<br/><br/>
Well, the dataset people weren’t going to just hand me the OLTP side of the equation without a fight, so they mentioned how easy it was to just “AcceptChanges”, and that my way was much more complex. My rebuttal came in the form of a question (are you seeing a pattern here?): Do you just swallow DbConcurrencyExceptions are do you throw all the user’s changes away when it happens? I didn’t quite make out the answer since there was a lot of mumbling going on, but I’m pretty sure they had one. I mean, you can’t develop multi-user systems using datasets without running into this situation.
<br/><br/>
The example that clinched OLTP was this. Two users perform a change to the same entity at the same time – one updates the customer’s marital status, the other changes their address. At the business level, there is no concurrency problem here. Both changes should go through. When using datasets, and those changes are bundled up with a bunch of other changes, and the whole snapshot is sent together from each user, you get a DbConcurrencyException. Like I said, I’m sure there’s a solution to it, I just haven’t heard it yet.
<br/><br/>
Now, here’s where things get interesting. I didn’t say that using a domain model automatically solves this problem. Rather, I described how each client could send a specific message, one a ChangeMaritalStatusMessage, the other a ChangeAddressMessage, to the server – in essence, giving the server the context in which each bit of data is relevant. The server could just open a transaction, get the customer object based on its Id, call a method on the customer (ChangeMaritalStatus or ChangeAddress), and commit the transaction. If two of these messages got to the server at the same time, the transactions would just cause them to be performed serially, and both transactions would succeed. The important part here is not losing the context of the changes.
<br/><br/>
When we talked about querying/reporting, things seemed quite a bit clearer. Datasets, or rather datatables seemed like a fine solution – most 3rd party controls support them out of the box. One guy mentioned that datasets performed poorly for large sets of data and that by designing custom entities for the result set, he could improve performance and memory utilization by, like, 70%. To tell you the truth, I think that if you need the performance, do it, if not, just use datasets. There isn’t much of an issue of correctness.
<br/><br/>
Just as an ending comment, in response to something someone said about scalability, I asked if they were reporting against the live OLTP data. The response was “yes”. Well, there’s a database scalability problem if I ever saw one. OLTP works most correctly when employing transactions that have an isolation level of serializable. The problem with them is that they lock up the whole table, or get blocked when a table scan is going on. Querying often results in a table scan. You can see the problem. Anyway, a common solution to this problem is to just reduce the isolation level, a quick fix that improves performance almost immediately. You take one hit in that your reports may be showing incorrect data, especially if they do aggregate type work. You might take another hit if your OLTP transactions need to do aggregate type work themselves. That second hit is pretty much unacceptable. A different solution is to accept the fact that the heaviest querying can usually show data that isn’t up to date up to the second.
<br/><br/>
In such a solution, you would have another database for reporting. It wouldn’t be just a replica of the OLTP database, but rather a lot more denormalized – which is a really not nice way of saying designed for reporting. You could then move the data from your OLTP database to the reporting database in some way (more to come on this topic) and you increase the scalability of your database. Just to define that a bit better – your OLTP database will be able to handle more transactions per unit of time, and reports will run faster, meaning that you will both improve their latency and the number of queries that can be handled per unit of time.
<br/><br/>
Anyway, I was pretty tired after all that, but if I had to sum it up I’d say something like this: before debating solutions, define the problem, you get a lot more insight into the solutions and you get it faster. That’s just win-win all around.]]></description>
			<content:encoded><![CDATA[<p>So, last night I was at the MVP dinner in TechEd and everything was nice. We had a nice meal, conversation was nice, weather was… nice. And then the volume started to rise, slowly at first, so as you don’t quite notice it. After a bit, you kind of stop talking and look around. And then I hear it…</p>
<p>&lt;WWF announcer voice&gt;<br />
Are you ready… to RUMBLE !?!?<br />
&lt;/WWF announcer voice&gt;</p>
<p>It was <a href="http://udidahan.weblogs.us/category/datasets/">Datasets</a> vs. <a href="http://udidahan.weblogs.us/category/nhibernate/">O/R mapping</a>, a slight twist on the infamous datasets vs. custom objects debate, all over again. They pulled me in, kicking and screaming, I swear, I really do. The lines were drawn, maintainability, performance, all the things that architects like to philosophize about in terms of other people’s work.</p>
<p>Anyway, I won’t give you the play-by-play ‘cause we were there almost all night. I’ll just cut to the chase.</p>
<p>First things first – any comparison of solutions without the context of a problem leads nowhere, fast, and stays there. So the first question I asked (when I got the chance to speak) was “are we talking about querying/reporting here?” and the answer was something like “well, yeah, but a lot of other things too”. So my suggestion was that we discuss the solutions in terms of two contexts &#8211;  querying/reporting and OLTP.</p>
<p>What I mean by OLTP is the data-updating kind of work that you do on certain items. Examples of this include “insert order”, “change customer address”, and “discount product”. Querying/reporting doesn’t change data, and often involves dealing with large sets of data pulled from different kinds of entities (in ERD terms).</p>
<p>Luckily, my suggestion to deal with them separately was accepted. Secondly, I proposed that an object model (specifically implementing the <a href="http://udidahan.weblogs.us/2007/04/21/domain-model-pattern/">Domain Model pattern</a>) designed for OLTP would perform poorly when used for querying/reporting – simply because it wasn’t designed for it. The structure of a domain model is such that it makes it possible to define / implement <a href="http://udidahan.weblogs.us/category/business-rules/">business rules</a> in one place. That’s possible, not easy. </p>
<p>Well, the dataset people weren’t going to just hand me the OLTP side of the equation without a fight, so they mentioned how easy it was to just “AcceptChanges”, and that my way was much more complex. My rebuttal came in the form of a question (are you seeing a pattern here?): Do you just swallow DbConcurrencyExceptions are do you throw all the user’s changes away when it happens? I didn’t quite make out the answer since there was a lot of mumbling going on, but I’m pretty sure they had one. I mean, you can’t develop multi-user systems using datasets without running into this situation.</p>
<p>The example that clinched OLTP was this. Two users perform a change to the same entity at the same time – one updates the customer’s marital status, the other changes their address. At the business level, there is no <a href="http://udidahan.weblogs.us/2007/01/22/realistic-concurrency/">concurrency</a> problem here. Both changes should go through. When using datasets, and those changes are bundled up with a bunch of other changes, and the whole snapshot is sent together from each user, you get a DbConcurrencyException. Like I said, I’m sure there’s a solution to it, I just haven’t heard it yet.</p>
<p>Now, here’s where things get interesting. I didn’t say that using a domain model automatically solves this problem. Rather, I described how each client could send a specific message, one a ChangeMaritalStatusMessage, the other a ChangeAddressMessage, to the server – in essence, giving the server the context in which each bit of data is relevant. The server could just open a transaction, get the customer object based on its Id, call a method on the customer (ChangeMaritalStatus or ChangeAddress), and commit the transaction. If two of these messages got to the server at the same time, the transactions would just cause them to be performed serially, and both transactions would succeed. The important part here is not losing the context of the changes.</p>
<p>When we talked about querying/reporting, things seemed quite a bit clearer. Datasets, or rather datatables seemed like a fine solution – most 3rd party controls support them out of the box. One guy mentioned that datasets performed poorly for large sets of data and that by designing custom entities for the result set, he could improve performance and memory utilization by, like, 70%. To tell you the truth, I think that if you need the performance, do it, if not, just use datasets. There isn’t much of an issue of correctness.</p>
<p>Just as an ending comment, in response to something someone said about <a href="http://udidahan.weblogs.us/category/scalability/">scalability</a>, I asked if they were reporting against the live OLTP data. The response was “yes”. Well, there’s a database scalability problem if I ever saw one. OLTP works most correctly when employing transactions that have an isolation level of serializable. The problem with them is that they lock up the whole table, or get blocked when a table scan is going on. Querying often results in a table scan. You can see the problem. Anyway, a common solution to this problem is to just reduce the isolation level, a quick fix that improves performance almost immediately. You take one hit in that your reports may be showing incorrect data, especially if they do aggregate type work. You might take another hit if your OLTP transactions need to do aggregate type work themselves. That second hit is pretty much unacceptable. A different solution is to accept the fact that the heaviest querying can usually show data that isn’t up to date up to the second.</p>
<p>In such a solution, you would have another database for reporting. It wouldn’t be just a replica of the OLTP database, but rather a lot more denormalized – which is a really not nice way of saying designed for reporting. You could then move the data from your OLTP database to the reporting database in some way (more to come on this topic) and you increase the scalability of your database. Just to define that a bit better – your OLTP database will be able to handle more transactions per unit of time, and reports will run faster, meaning that you will both improve their latency and the number of queries that can be handled per unit of time.</p>
<p>Anyway, I was pretty tired after all that, but if I had to sum it up I’d say something like this: before debating solutions, define the problem, you get a lot more insight into the solutions and you get it faster. That’s just win-win all around.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2006/11/09/dataset-%e2%80%93-or-mapping-rumble-at-teched-mvp-dinner/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>SQL Injection attacks &amp; O/R mapping</title>
		<link>http://www.udidahan.com/2006/09/30/sql-injection-attacks-or-mapping/</link>
		<comments>http://www.udidahan.com/2006/09/30/sql-injection-attacks-or-mapping/#comments</comments>
		<pubDate>Sun, 01 Oct 2006 04:20:11 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://wp_630.weblogs.us/archives/325</guid>
		<description><![CDATA[You've probably never thought of SQL Injection Attacks and O/R mapping in the same context. I know I haven't, that is, until today. I saw Scott's post on how to <a href="http://weblogs.asp.net/scottgu/archive/2006/09/30/Tip_2F00_Trick_3A00_-Guard-Against-SQL-Injection-Attacks.aspx">"Guard Against SQL Injection Attacks"</a> and started wondering how long it's been since I've given it any thought. Then I realized that it was around the same time I switched to O/R mapping.
<br/><br/>
Since data received from the user is put in domain objects, and then those objects are mapped to tables (or views) in the database, the O/R mapper just handles it all for me. I assume that all the mappers out there use parameterized SQL, but I know for sure that NHibernate does (from peeking at the logs every once in a while).
<br/><br/>
Anyway, just wanted to mention this added side benefit of moving to the Domain Model pattern - no more SQL injection worries.]]></description>
			<content:encoded><![CDATA[<p>You&#8217;ve probably never thought of SQL Injection Attacks and <a href="http://udidahan.weblogs.us/category/nhibernate/">O/R mapping</a> in the same context. I know I haven&#8217;t, that is, until today. I saw Scott&#8217;s post on how to <a href="http://weblogs.asp.net/scottgu/archive/2006/09/30/Tip_2F00_Trick_3A00_-Guard-Against-SQL-Injection-Attacks.aspx">&#8220;Guard Against SQL Injection Attacks&#8221;</a> and started wondering how long it&#8217;s been since I&#8217;ve given it any thought. Then I realized that it was around the same time I switched to O/R mapping.</p>
<p>Since data received from the user is put in domain objects, and then those objects are mapped to tables (or views) in the database, the O/R mapper just handles it all for me. I assume that all the mappers out there use parameterized SQL, but I know for sure that <a href="http://udidahan.weblogs.us/category/nhibernate/">NHibernate</a> does (from peeking at the logs every once in a while).</p>
<p>Anyway, just wanted to mention this added side benefit of moving to the <a href="http://udidahan.weblogs.us/2007/04/21/domain-model-pattern/">Domain Model pattern</a> &#8211; no more SQL injection worries.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2006/09/30/sql-injection-attacks-or-mapping/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>
		<item>
		<title>Ultra scalability for the web</title>
		<link>http://www.udidahan.com/2005/12/10/ultra-scalability-for-the-web/</link>
		<comments>http://www.udidahan.com/2005/12/10/ultra-scalability-for-the-web/#comments</comments>
		<pubDate>Sun, 11 Dec 2005 02:12:53 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Scalability]]></category>

		<guid isPermaLink="false">http://wp_630.weblogs.us/archives/236</guid>
		<description><![CDATA[On one of the discussion lists I linger in, the following question was raised:
<br/><br/>
I have a client who wants me to use nHibernate for a ASP.NET Portal we are creating with Visual Basic 2005.  Approx. 250,000 users, as many as 40,000 actives at the same time. Does nHibernate introduce significant overhead? Are there known issues?
<br/><br/>
I figure that the answer I gave there would be valuable to a larger audience, so here it is:
<br/><br/>
1. No, NHibernate does not introduce significant overhead. <br/>
2. Not that that will make any difference for the load described above. 
 <br/><br/>
Unless you architect for that level of load, any data access strategy will require very expensive hardware. For example, what better way to handle load than preventing the users from hitting your servers at all? This can be done by generating xml files for data, which are referenced by html pages statically. Look and feel should be done by separate css files. There’s nothing better than using the entire internet as your cache. Manage the expiration of these xml files from the caches of ISPs all over the web. This kind of solution will also enable you to expand your site to Akamai networks much easier, further increasing scalability.
<br/><br/>
NHibernate gives you the ability to write object oriented business logic in a persistent environment. If your site is light on logic, you might not get much benefit from using an O/R mapper. This has nothing to do with handling very high levels of load.
<br/><br/>
--
<br/><br/>
While the internet places inherent constraints on our ability to develop certain solutions, at the same time we can take advantage of "the rules of the net" - how content is transferred, to handle the highest levels of load. You would be hard pressed to come up with a better, more resilient solution if you were to architect it from scratch.]]></description>
			<content:encoded><![CDATA[<p>On one of the discussion lists I linger in, the following question was raised:</p>
<p>I have a client who wants me to use nHibernate for a ASP.NET Portal we are creating with Visual Basic 2005.  Approx. 250,000 users, as many as 40,000 actives at the same time. Does nHibernate introduce significant overhead? Are there known issues?</p>
<p>I figure that the answer I gave there would be valuable to a larger audience, so here it is:</p>
<p>1. No, NHibernate does not introduce significant overhead.<br />
2. Not that that will make any difference for the load described above. </p>
<p>Unless you architect for that level of load, any data access strategy will require very expensive hardware. For example, what better way to handle load than preventing the users from hitting your servers at all? This can be done by generating xml files for data, which are referenced by html pages statically. Look and feel should be done by separate css files. There’s nothing better than using the entire internet as your cache. Manage the expiration of these xml files from the caches of ISPs all over the web. This kind of solution will also enable you to expand your site to Akamai networks much easier, further increasing scalability.</p>
<p>NHibernate gives you the ability to write object oriented business logic in a persistent environment. If your site is light on logic, you might not get much benefit from using an O/R mapper. This has nothing to do with handling very high levels of load.</p>
<p>&#8211;</p>
<p>While the internet places inherent constraints on our ability to develop certain solutions, at the same time we can take advantage of &#8220;the rules of the net&#8221; &#8211; how content is transferred, to handle the highest levels of load. You would be hard pressed to come up with a better, more resilient solution if you were to architect it from scratch.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2005/12/10/ultra-scalability-for-the-web/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>O/R Mapping meets Mission Critical</title>
		<link>http://www.udidahan.com/2005/07/04/or-mapping-meets-mission-critical/</link>
		<comments>http://www.udidahan.com/2005/07/04/or-mapping-meets-mission-critical/#comments</comments>
		<pubDate>Tue, 05 Jul 2005 02:45:45 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Databases]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Scalability]]></category>

		<guid isPermaLink="false">http://wp_630.weblogs.us/archives/202</guid>
		<description><![CDATA[After listening to a recently uncovered gem - <a href="http://polymorphicpodcast.com/">polymorphic podcasts</a> the topic of O/R mapping was raised yet again. I will be writing on this topic more in depth in other forums soon, but I wanted to give the executive summary here: O/R mapping is problematic.
<BR/><BR/>
The underlying assumption of O/R mapping is based on mapping objects to tables. However, for mission critical systems, the whole idea of updating or deleting rows from the database goes against basic principles. In a <a href="http://www.ronjacobs.com/podcast/default.htm">not-so-recent podcast from Ron Jacobs</a>, Clemens Vasters described the kind of database design often utilized in high-end systems. There he describes timestamping data with a validity period creating "insert-only databases" - these enable the highest levels of performance and scalability, not to mention regulatory compliance. However, the familiar semantics of updating and deleting entities provided by O/R mapping do not seem to support these scenarios.
<BR/><BR/>
But all is not lost! There are solutions. I'll be posting these solutions in the afore-mentioned forums soon.<BR/><BR/>]]></description>
			<content:encoded><![CDATA[<p>After listening to a recently uncovered gem &#8211; <a href="http://polymorphicpodcast.com/">polymorphic podcasts</a> the topic of O/R mapping was raised yet again. I will be writing on this topic more in depth in other forums soon, but I wanted to give the executive summary here: O/R mapping is problematic.</p>
<p>The underlying assumption of O/R mapping is based on mapping objects to tables. However, for mission critical systems, the whole idea of updating or deleting rows from the database goes against basic principles. In a <a href="http://www.ronjacobs.com/podcast/default.htm">not-so-recent podcast from Ron Jacobs</a>, Clemens Vasters described the kind of database design often utilized in high-end systems. There he describes timestamping data with a validity period creating &#8220;insert-only databases&#8221; &#8211; these enable the highest levels of performance and scalability, not to mention regulatory compliance. However, the familiar semantics of updating and deleting entities provided by O/R mapping do not seem to support these scenarios.</p>
<p>But all is not lost! There are solutions. I&#8217;ll be posting these solutions in the afore-mentioned forums soon.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2005/07/04/or-mapping-meets-mission-critical/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Code from First Agile Israel Meeting</title>
		<link>http://www.udidahan.com/2005/02/01/code-from-first-agile-israel-meeting/</link>
		<comments>http://www.udidahan.com/2005/02/01/code-from-first-agile-israel-meeting/#comments</comments>
		<pubDate>Wed, 02 Feb 2005 02:59:00 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[DataSets]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://wp_630.weblogs.us/archives/168</guid>
		<description><![CDATA[The code I presented at the Agile Israel meeting can be downloaded here. It&#8217;s just a small sampling of how much code you DON&#8217;T have to write when using O/R Mapping.
]]></description>
			<content:encoded><![CDATA[<p>The code I presented at the Agile Israel meeting can be downloaded <a href="http://udidahan.weblogs.us/archives/NHibernate demo.zip">here</a>. It&#8217;s just a small sampling of how much code you DON&#8217;T have to write when using O/R Mapping.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2005/02/01/code-from-first-agile-israel-meeting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Don, Spring, OR mapping, Lazy Loading, in a short post</title>
		<link>http://www.udidahan.com/2004/11/23/don-spring-or-mapping-lazy-loading-in-a-short-post/</link>
		<comments>http://www.udidahan.com/2004/11/23/don-spring-or-mapping-lazy-loading-in-a-short-post/#comments</comments>
		<pubDate>Wed, 24 Nov 2004 00:47:54 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[Simplicity]]></category>

		<guid isPermaLink="false">http://wp_630.weblogs.us/archives/130</guid>
		<description><![CDATA[After listening to the DNR episode with Don, Ted, and Mark I got to thinking about the issue of lazy loading in OR mappers. This was unanimously(?) described as being one of the imperfections inherent in the O/R mapping world. What I wondered was if that TransparentProxy could be used somehow to work around it. [...]]]></description>
			<content:encoded><![CDATA[<p>After listening to the DNR episode with <a href="http://pluralsight.com/blogs/dbox/">Don</a>, <a href="http://www.neward.net/ted/weblog/index.jsp">Ted</a>, and Mark I got to thinking about the issue of <a href="http://udidahan.weblogs.us/2007/04/15/lazy-loading-and-how-messaging-fixes-everything-again/">lazy loading</a> in OR mappers. This was unanimously(?) described as being one of the imperfections inherent in the <a href="http://udidahan.weblogs.us/category/nhibernate/">O/R mapping</a> world. What I wondered was if that TransparentProxy could be used somehow to work around it. I submit this to the ObjectSpaces gods as an open question &#8211; how are you guys going about it?</p>
<p>There is a different, more <a href="http://udidahan.weblogs.us/category/oo/">OO</a> way of handling this. By separating out the interface of the class you want to be lazy loaded &#8211; make an IPerson interface &#8211; and have the client code be tied to that. In that way, your <a href="http://udidahan.weblogs.us/category/dependency-injection/">dependency injection container</a> (<a href="http://www.springFramework.net">Spring</a>, for example) could instantiate an implementation that handles lazy loading without the client having to know about it. This implementation is absolutely something that could be handled by an OR mapping tool.</p>
<p>So, I suppose that even some of the more difficult problems of OR mapping could be handled. All that is needed is not to add more to the tool itself, but rather to more formally structure how to work with it. My opinion, anyway.</p>
<p><B><U>Update</U></B></p>
<p>The next part around the discussion about lazy loading and <a href="http://udidahan.weblogs.us/2007/03/06/better-domain-driven-design-implementation/">fetching strategies</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2004/11/23/don-spring-or-mapping-lazy-loading-in-a-short-post/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
