<?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; OO</title>
	<atom:link href="http://www.udidahan.com/category/oo/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>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>The Fallacy Of ReUse</title>
		<link>http://www.udidahan.com/2009/06/07/the-fallacy-of-reuse/</link>
		<comments>http://www.udidahan.com/2009/06/07/the-fallacy-of-reuse/#comments</comments>
		<pubDate>Sun, 07 Jun 2009 08:40:16 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Autonomous Services]]></category>
		<category><![CDATA[EDA]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[Web Services]]></category>

		<guid isPermaLink="false">http://www.udidahan.com/?p=1026</guid>
		<description><![CDATA[This industry is pre-occupied with reuse.
There&#8217;s this belief that if we just reused more code, everything would be better.
Some even go so far as saying that the whole point of object-orientation was reuse &#8211; it wasn&#8217;t, encapsulation was the big thing. After that component-orientation was the thing that was supposed to make reuse happen. Apparently [...]]]></description>
			<content:encoded><![CDATA[<p>This industry is pre-occupied with reuse.</p>
<p>There&#8217;s this belief that if we just reused more code, everything would be better.</p>
<p>Some even go so far as saying that the whole point of object-orientation was reuse &#8211; it wasn&#8217;t, encapsulation was the big thing. After that component-orientation was the thing that was supposed to make reuse happen. Apparently that didn&#8217;t pan out so well either because here we are now pinning our reuseful hopes on service-orientation.</p>
<p>Entire books of patterns have been written on how to achieve reuse with the orientation of the day.<br />
Services have been classified every which way in trying to achieve this, from entity services and activity services, through process services and orchestration services. Composing services has been touted as the key to reusing, and creating reusable services.</p>
<p>I might as well let you in on the dirty-little secret:</p>
<h3>Reuse is a fallacy</h3>
<p>Before running too far ahead, let&#8217;s go back to what the actual goal of reuse was: getting done faster.</p>
<p>That&#8217;s it.</p>
<p>It&#8217;s a fine goal to have.</p>
<p>And here&#8217;s how reuse fits in to the picture:</p>
<blockquote><p>
If we were to write all the code of a system, we&#8217;d write a certain amount of code.<br />
If we could reuse some code from somewhere else that was written before, we could write less code.<br />
The more code we can reuse, the less code we write.<br />
The less code we write, the sooner we&#8217;ll be done!
</p></blockquote>
<p>However, the above logical progression is based on another couple of fallacies:</p>
<h3>Fallacy: All code takes the same amount of time to write</h3>
<h3>Fallacy: Writing code is the primary activity in getting a system done</h3>
<p>Anyone who&#8217;s actually written some code that&#8217;s gone into production knows this.</p>
<p>There&#8217;s the time it takes us to understand what the system should do.<br />
Multiply that by the time it takes the users to understand what the system should do <img src='http://www.udidahan.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /><br />
Then there&#8217;s the integrating that code with all the other code, databases, configuration, web services, etc.<br />
Debugging. Deploying. Debugging. Rebugging. Meetings. Etc.</p>
<p>Writing code is actually the least of our worries.<br />
We actually spend less time writing code than&#8230;</p>
<h3>Rebugging code</h3>
<p>Also known as bug regressions.</p>
<p>This is where we fix one piece of code, and in the process break another piece of code.<br />
It&#8217;s not like we do it on purpose. It&#8217;s all those dependencies between the various bits of code.<br />
The more dependencies there are, the more likely something&#8217;s gonna break.<br />
Especially when we have all sorts of hidden dependencies,<br />
like when other code uses stuff we put in the database without asking us what it means,<br />
or, heaven forbid, changing it without telling us.</p>
<p>These debugging/rebugging cycles can make stabilizing a system take a long time.</p>
<p>So, how does reuse help/hinder with that?</p>
<p>Here&#8217;s how:</p>
<h3>Dependencies multiply by reuse</h3>
<p>It&#8217;s to be expected. If you wrote the code all in one place, there are no dependencies. By reusing code, you&#8217;ve created a dependency. The more you reuse, the more dependencies you have. The more dependencies, the more rebugging.</p>
<p>Of course, we need to keep in mind the difference between&#8230;</p>
<h3>Reuse &#038; Use</h3>
<p>Your code <b>uses</b> the runtime API (JDK, .NET BCL, etc).<br />
Likewise other frameworks like (N)Hibernate, Spring, WCF, etc.</p>
<p>Reuse happens when you extend and override existing behaviors within other code.<br />
This is most often done by inheritance in OO languages.</p>
<p>Interestingly enough, by the above generally accepted definition, most web services &#8220;reuse&#8221; is actually really use.</p>
<p>Let&#8217;s take a look at the characteristics of the code we&#8217;re using and reusing to see where we get the greatest value:</p>
<h3>The value of (re)use</h3>
<p>If we were to (re)use a piece of code in only one part of our system, it would be safe to say that we would get less value than if we could (re)use it in more places. For example, we could say that for many web applications, the web framework we use provides more value than a given encryption algorithm that we may use in only a few places.</p>
<p>So, what characterizes the code we use in many places?</p>
<p>Well, it&#8217;s very <b>generic</b>.</p>
<p>Actually, the more generic a piece of code, the less likely it is that we&#8217;ll be changing something in it when fixing a bug in the system.</p>
<p><b>That&#8217;s important</b>.</p>
<p>However, when looking at the kind of code we reuse, and the reasons around it, we tend to see very <b>non-generic</b> code &#8211; something that deals with the domain-specific behaviors of the system. Thus, the likelihood of a bug fix needing to touch that code is higher than in the generic/use-not-reuse case, often much higher.</p>
<h3>How it all fits together</h3>
<blockquote><p>
Goal:&#09;Getting done faster<br />
Via:&#09;Spending less time debugging/rebugging/stabilizing<br />
Via:&#09;Having less dependencies reasonably requiring a bug fix to touch the dependent side<br />
Via:&#09;Not reusing non-generic code
</p></blockquote>
<p>This doesn&#8217;t mean you shouldn&#8217;t use generic code / frameworks where applicable &#8211; absolutely, you should.<br />
Just watch the number of kind of dependencies you introduce.</p>
<h3>Back to services</h3>
<p>So, if we follow the above advice with services, we wouldn&#8217;t want domain specific services reusing each other.<br />
If we could get away with it, we probably wouldn&#8217;t even want them using each other either.</p>
<p>As use and reuse go down, we can see that service autonomy goes up. And vice-versa.<br />
Luckily, we have service interaction mechanisms from Event-Driven Architecture that enable use without breaking autonomy.<br />
Autonomy is actually very similar to the principle of encapsulation that drove object-orientation in the first place.<br />
Interesting, isn&#8217;t it?</p>
<h3>In summary</h3>
<p>We all want to get done faster.</p>
<p>Way back when, someone told us reuse was the way to do that.</p>
<p>They were wrong.</p>
<p>Reuse may make sense in the most tightly coupled pieces of code you have, but not very much anywhere else.</p>
<p>When designing services in your SOA, stay away from reuse, and minimize use (with EDA patterns).</p>
<p>The next time someone pulls the &#8220;reuse excuse&#8221;, you&#8217;ll be ready.</p>
<hr size="1" />
<h3>Further Reading</h3>
<ul>
<li><a href="http://www.udidahan.com/2008/10/22/additional-logic-required-for-service-autonomy/">Additional logic required for service autonomy</a></li>
<li><a href="http://www.udidahan.com/2008/12/13/self-contained-events-and-soa/">Self-contained events &#038; SOA</a></li>
<li><a href="http://msdn2.microsoft.com/en-us/arcjournal/bb245672">Autonomous Services and Enterprise Entity Aggregation</a> [MS Architecture Journal]</li>
<li><a href="http://udidahan.weblogs.us/2006/05/26/podcast-does-soa-mean-the-end-of-oo/">Does SOA mean the end of OO?</a> [Podcast]</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2009/06/07/the-fallacy-of-reuse/feed/</wfw:commentRss>
		<slash:comments>49</slash:comments>
		</item>
		<item>
		<title>ALT.NET DDD Podcast</title>
		<link>http://www.udidahan.com/2009/01/26/altnet-ddd-podcast/</link>
		<comments>http://www.udidahan.com/2009/01/26/altnet-ddd-podcast/#comments</comments>
		<pubDate>Mon, 26 Jan 2009 20:36:08 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[DDD]]></category>
		<category><![CDATA[OO]]></category>

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

		<guid isPermaLink="false">http://udidahan.weblogs.us/2008/03/20/qcon-london-2008-recap/</guid>
		<description><![CDATA[Well QCon was a blast.
NServiceBus Tutorial
I gave a full day tutorial on nServiceBus and we had a full house! The tutorial was about 90% how to think about distributed systems, and 10% mapping those concepts onto nServiceBus. I made an effort to cram about 3 days of a 5 day training course I give clients [...]]]></description>
			<content:encoded><![CDATA[<p>Well QCon was a blast.</p>
<h3>NServiceBus Tutorial</h3>
<p>I gave a full day tutorial on <a href="http://www.nservicebus.com">nServiceBus</a> and we had a full house! The tutorial was about 90% how to think about distributed systems, and 10% mapping those concepts onto nServiceBus. I made an effort to cram about 3 days of a 5 day training course I give clients into one day, but I think I was only about 85% successful. People didn&#8217;t have the time needed to let things really sink in and ask questions, but the <a href="http://tech.groups.yahoo.com/group/nservicebus/">lively forums</a> and <a href="http://udidahan.weblogs.us/2008/02/25/would-you-spend-a-buck-to-save-a-hundred/">skype conversations</a> available will probably do the trick.</p>
<p><a href="http://jim.webber.name/">Jim Webber</a> after looking at the unit testing features of nServiceBus had this to say:</p>
<blockquote><p>&#8220;Oh my God &#8211; you&#8217;ve created testable middleware! It&#8217;ll never catch on. The vendors won&#8217;t have it.&#8221;</p>
</blockquote>
<p>To which I replied that several vendors were already coming on board with their own implementations of transports and saga persistence. I have absolutely no intention, desire, or (quite frankly) the ability to write an enterprise-class middleware runtime. All I hope to do with nServiceBus is to make it so that developers use what&#8217;s out there in one, middleware-product-agnostic way that will make their code more robust and flexible.</p>
<h3>MEST &amp; Mark &#8211; REST &amp; Stefan</h3>
<p>It was also great finally meeting the head MESTian, <a href="http://markclittle.blogspot.com/">Mark Little</a>, who also happens to work for Redhat as SOA Technical Development Manager and Director of Standards in the JBoss division. It was interesting to see the difference between how I went about messaging in nServiceBus (full peer-to-peer including pub/sub) whereas most of the Java world has the messaging infrastructure handled by something database-like in a deployment/networking kind of perspective. If that&#8217;s the way things are done, then I can definitely appreciate the advantages of <a href="http://udidahan.weblogs.us/2007/06/20/space-based-architecture-%e2%80%93-scalable-but-not-much-to-do-with-soa/">Space-Based Architectures</a>.</p>
<p>And I even got to steal <a href="http://www.innoq.com/blog/st/">Stefan Tilkov</a>&#8217;s RESTful ear for an hour or so before I had to jet back home. It looks like we MESTians and RESTians can be one big happy family. I&#8217;m guessing that our despise of WS connects us all at a deeper level <img src='http://www.udidahan.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h3>Core Design Principles</h3>
<p>I also gave a talk about core design principles, &#8220;Intentions &amp; Interfaces &#8211; making patterns concrete&#8221;, and it went over very well especially considering that that was the first time that I gave that talk. You can find the slides <a href="http://www.eos1.dk/qcon-london-2008/slides/UdiDahan_IntentionsAndInterfaces.pdf">here</a>. From the feedback I heard after the talk, I think many people were surprised how many different parts of a system can be designed this way, and how flexible it is without making the code any more complex. The message was this:</p>
<blockquote><p>Make Roles Explicit</p>
</blockquote>
<p>Despite its simplicity, that leads to IEntity, IValidator&lt;T&gt; where T : IEntity, (which I wrote about a year ago &#8211; <a href="http://udidahan.weblogs.us/2007/04/30/generic-validation/">generic validation</a>) and with a bit of Service Locator capabilities, you can add a line of code to your infrastructure that will validate all entities before they&#8217;re sent from the client to the server. </p>
<p>It leads to IFetchingStrategy&lt;T&gt; for improved database loading performance (also a year old &#8211; <a href="http://udidahan.weblogs.us/2007/03/06/better-domain-driven-design-implementation/">better DDD implementation</a> and the <a href="http://udidahan.weblogs.us/2007/09/16/fetching-strategy-nhibernate-implementation-available/">NHibernate implementation</a>). </p>
<p>It&#8217;s also how nServiceBus does message handling &#8211; IMessage, IMessageHandler&lt;T&gt; where T: IMessage, ISaga&lt;T&gt; where T : IMessage.</p>
<h3>San Francisco?</h3>
<p>Just a quick shout to my readers in the San Francisco area, if you&#8217;d be interested in hearing these talks/tutorials, give the organizers of QCon a <a href="mailto:qcon@infoq.com">shout</a> and they&#8217;ll bring me out. That&#8217;s actually what got me to London &#8211; one of the attendees of a talk I gave at Oredev in Sweden last November missed my tutorial there so he put in a request and that did it. (Thanks Jan, I appreciate it!)</p>
<p>If you&#8217;re in a different part of the world and you&#8217;d like to have me give one of these talks, or other ones (I have a fair amount of material on Domain Models/DDD and Occasionally Connected Smart Clients), I&#8217;d be happy to make the trip and see you there as well.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2008/03/20/qcon-london-2008-recap/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How to create fully encapsulated Domain Models</title>
		<link>http://www.udidahan.com/2008/02/29/how-to-create-fully-encapsulated-domain-models/</link>
		<comments>http://www.udidahan.com/2008/02/29/how-to-create-fully-encapsulated-domain-models/#comments</comments>
		<pubDate>Fri, 29 Feb 2008 14:40:33 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Business Rules]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[Simplicity]]></category>

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

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

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

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

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

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

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

    a.Time = message.RequestedTime; 

    session.Save(a);  

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

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/10/12/podcast-thread-safe-asynchronous-smart-clients/</guid>
		<description><![CDATA[In this podcast we&#8217;ll look at various patterns involved in creating MVC-based Smart Clients which communicate using asynchronous messaging and how to avoid threading problems there. 
Neil asks:

Hi Udi,
We&#8217;re building a smart client application that uses WCF for full-duplex communications with our server. This is the asynchronous communication you talk about in your podcast. The [...]]]></description>
			<content:encoded><![CDATA[<p>In this podcast we&#8217;ll look at various patterns involved in creating MVC-based Smart Clients which communicate using asynchronous messaging and how to avoid threading problems there. </p>
<p>Neil asks:</p>
<blockquote><p>
Hi Udi,</p>
<p>We&#8217;re building a smart client application that uses WCF for full-duplex communications with our server. This is the asynchronous communication you talk about in your podcast. The smart-client is based on the MVC pattern, where model objects raise events when they&#8217;re changed so that the views can update themselves.</p>
<p>What&#8217;s started happening recently is that the smart-client has been freezing-up on us intermittently. We don&#8217;t know how to debug this and are wondering if its an architectural problem.</p>
<p>Any help you can give would be most appreciated.</p>
<p>Neil
</p></blockquote>
<p><b>Download</b></p>
<p><a href="http://www.ddj.com/architect/202401468">Download via the Dr. Dobb&#8217;s site</a></p>
<p>Or download directly <a href="http://www.dobbsprojects.com/media/newengine/dynamp.php/071011ud01.mp3?podcast=071011ud01.mp3">here</a></p>
<p><b>Additional References</b></p>
<ul>
<li>Blog post on <A href="http://udidahan.weblogs.us/2007/04/04/occasionally-connected-systems-architecture/">Occasionally Connected Systems Architecture</A></li>
<li>Blog post on <A href="http://udidahan.weblogs.us/2007/09/28/objectbuilder-synchronization-features-needed-for-pubsub-ing-smart-clients/">ObjectBuilder synchronization features needed for pub/sub-ing Smart Clients</A></li>
</ul>
<p><b>Want more?</b></p>
<p>Check out the <a href="/ask-udi/">&#8220;Ask Udi&#8221; archives</a>.</p>
<p><b>Got a question?</b></p>
<p><a href="mailto:podcast@UdiDahan.com">Send Udi your question to answer on the show.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/10/12/podcast-thread-safe-asynchronous-smart-clients/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
<enclosure url="http://www.dobbsprojects.com/media/newengine/dynamp.php/071011ud01.mp3?podcast=071011ud01.mp3" length="13030892" type="audio/mp3" />
		</item>
		<item>
		<title>Performant and Explicit Domain Models</title>
		<link>http://www.udidahan.com/2007/06/04/performant-and-explicit-domain-models/</link>
		<comments>http://www.udidahan.com/2007/06/04/performant-and-explicit-domain-models/#comments</comments>
		<pubDate>Mon, 04 Jun 2007 20:31:34 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Business Rules]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Databases]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Simplicity]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Threading]]></category>

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

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

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/06/04/interfaces-solve-visibility-and-testing-issues/</guid>
		<description><![CDATA[Jimmy&#8217;s recent post called out some of the insights on the advantages of Ruby from Niclas&#8217; keynote at DevSummit 2007. Jimmy writes:

In Ruby it&#8217;s easy to redefine the visibility of a method from private to public for testing purposes. This was just one small detail in his talk of course, but I started to think [...]]]></description>
			<content:encoded><![CDATA[<p>Jimmy&#8217;s <a href="http://jimmynilsson.com/blog/posts/Devsummit2007b.htm">recent post</a> called out some of the insights on the advantages of Ruby from <a href="http://niclasnilsson.se/">Niclas&#8217; keynote at DevSummit 2007</a>. Jimmy writes:</p>
<blockquote><p>
In Ruby it&#8217;s easy to redefine the visibility of a method from private to public for testing purposes. This was just one small detail in his talk of course, but I started to think about how much pain I quite often go through regarding this in legacy code.
</p></blockquote>
<p>Let me just start out by saying that dealing with legacy code is far from easy. However, when writing new code, or as a part of refactoring that legacy, adding interfaces to your design can help you get around those visibility and testing issues.</p>
<p>For instance, if you only let &#8220;client&#8221; code access the interface, and not the implementation (probably using some kind of <a href="http://udidahan.weblogs.us/category/dependency-injection/">dependency injection</a>), then you could leave all sorts of methods public on your concrete class without worry that the client will call them since the interface doesn&#8217;t expose them. Now that the methods on the concrete class are public, you can easily test that class.</p>
<p>The way to package your code to make sure this occurs follows a <a href="http://udidahan.weblogs.us/2007/05/12/first-principle-of-design-refined/">very simple design principle</a>. This is much easier to put in practice on new development, but you&#8217;ll find that it isn&#8217;t that hard for legacy either. Since legacy code often doesn&#8217;t make use of interfaces, and the implementation is already packaged, and your new client code will already be separately packaged, you&#8217;re 90% there!</p>
<p>If you can change the legacy code, you&#8217;re actually 95% there. Just create a new package for the interface that the client code will use. Then change the legacy code to implement that interface &#8211; since the methods will be pretty much the same, it&#8217;s not that much work.</p>
<p>If you can&#8217;t change the legacy code, create a &#8220;wrapper&#8221; class that implements the interface and delegates the calls to the legacy code.</p>
<p>Finally, let me sum up by saying that I think Ruby is great. However, I think that often many advantages are attributed to anything new that may have already been possible/easy with what we already have today. Sometimes, the new stuff helps raise awareness on important issues &#8211; and then we can have great discussions on how to solve those issues with today&#8217;s (yesterday&#8217;s ?) technology <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/2007/06/04/interfaces-solve-visibility-and-testing-issues/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Layering &#8211; too simplistic to actually work</title>
		<link>http://www.udidahan.com/2007/06/03/layering-too-simplistic-to-actually-work/</link>
		<comments>http://www.udidahan.com/2007/06/03/layering-too-simplistic-to-actually-work/#comments</comments>
		<pubDate>Sun, 03 Jun 2007 21:35:34 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Business Rules]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[Simplicity]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/06/03/layering-too-simplistic-to-actually-work/</guid>
		<description><![CDATA[After seeing Mark&#8217;s post on Reasons for Isolation describing the ways Layered Architectures break down, and the ways making it more testable can change it, I&#8217;ve got to wonder &#8211; is Layering just too simplistic to actually work?
Just the other day I was doing a design review for a fairly simple Smart Client whose design [...]]]></description>
			<content:encoded><![CDATA[<p>After seeing Mark&#8217;s post on <a href="http://blogs.msdn.com/ploeh/archive/2007/05/30/ReasonsForIsolation.aspx">Reasons for Isolation</a> describing the ways Layered Architectures break down, and the ways making it more testable can change it, I&#8217;ve got to wonder &#8211; is Layering just too simplistic to actually work?</p>
<p>Just the other day I was doing a design review for a fairly simple <a href="http://udidahan.weblogs.us/category/smart-client/">Smart Client</a> whose design was layered. In order to stay away from interfaces that accepted dozens of ints, strings, and dates, they wanted to have each layer talk to the other using &#8220;entities&#8221;. So where are these entities defined &#8211; oh, in a &#8220;vertical layer&#8221; that all the horizontal layers talk to.</p>
<p>OK, so we&#8217;ve taken the simplistic one-dimensional layered architecture and added a dimension. What now?</p>
<p>Well, it seems that having the business logic and the entities in separate layers goes against one of the most basic <a href="http://udidahan.weblogs.us/category/oo/">Object Oriented</a> principles &#8211; encapsulation. So, let&#8217;s put the entities back in the <a href="http://udidahan.weblogs.us/category/business-rules/">Business Logic</a> Layer. But then how will the <a href="http://udidahan.weblogs.us/category/data-access/">Data Access</a> Layer accept those objects as parameters?</p>
<p>So, that is solved by keeping Entity Interfaces in the &#8220;vertical&#8221; shared &#8220;layer&#8221;, and having the entities in the business logic layer implement those interfaces. That way, the data access layer can still accept parameters corresponding to those interfaces:</p>
<pre>void InsertCustomer(Shared.Entities.ICustomer customer);</pre>
<p>So far so good. Now, we want more testable UI layer code &#8211; so we use Model-View-Controller (MVC) &#8211; of whichever flavor suits your fancy. I&#8217;d say that <a href="http://www.martinfowler.com/eaaDev/SupervisingPresenter.html">Supervising Controller</a> is a must. You could also add another presenter for more complex screens as in <a href="http://www.martinfowler.com/eaaDev/PassiveScreen.html">Passive View</a>, but I&#8217;d be less strict on that. So, in which layer do these Controllers/Presenters sit? And is the Business Logic Layer the Model? Or is the Model just part of it?</p>
<p>Well, our Supervising Controllers are those who decide what action to do and when, where to get the data from, etc. That sounds like business logic to me. So let&#8217;s put them in the BLL. Presenters for the Passive View are much more UI centered, so let&#8217;s put them in the Presentation Layer. But we don&#8217;t want them tied to the implementation of the view, so we&#8217;ll put them in a separate package, and have them depend only on the view&#8217;s interface. So we&#8217;ll put the view interfaces in a package separate from the view implementation as well.</p>
<p>If it wasn&#8217;t clear up to this point, all the questions raised in this post are architectural in nature &#8211; as in they have a substantial impact on the structure and flow of the system, and will definitely have a profound effect on its maintainability. In other words, if you think that Layer Diagram covers your design &#8211; you&#8217;re probably deluding yourself. Personally, I think that&#8217;s why many developers consider architects to be &#8220;out of touch with the real world&#8221;.</p>
<p>When you have a design that answers these, and other architectural concerns, you&#8217;ll find that layering is of little importance. The specific constraints on each package are what counts. The fact that the Presentation Layer can talk to the Business Logic Layer doesn&#8217;t mean that the classes in your Views Implementation Package can. A large part of an architects work is to specify these constraints, and communicate them to the team. Tools like FxCop may help in terms of enforcing these constraints, but I believe that getting the team to actually &#8220;buy-in&#8221; is more effective.</p>
<p>Single-dimensional layered architectures don&#8217;t work. They violate Einstein&#8217;s maxim:</p>
<p><i>Make everything as simple as possible, but not simpler.</i></p>
<p>Layering &#8211; &#8220;simpler&#8221; to the point of simplistic.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/06/03/layering-too-simplistic-to-actually-work/feed/</wfw:commentRss>
		<slash:comments>5</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>Frictionless Design</title>
		<link>http://www.udidahan.com/2007/05/14/frictionless-design/</link>
		<comments>http://www.udidahan.com/2007/05/14/frictionless-design/#comments</comments>
		<pubDate>Mon, 14 May 2007 07:21:32 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[Simplicity]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/05/14/frictionless-design/</guid>
		<description><![CDATA[From Ryan&#8217;s post on scaling Rails with multiple databases, he raises a point near and dear to my heart around the use of well designed frameworks (apparently sourced by Joe):

When referring to framework and tooling, &#8220;friction&#8221; is a (subjective) measure of how much the tooling gets in your way when trying to solve a specific-case [...]]]></description>
			<content:encoded><![CDATA[<p>From Ryan&#8217;s post on scaling Rails with multiple databases, he raises a point near and dear to my heart around the use of <a href="http://tomayko.com/weblog/2007/04/13/rails-multiple-connections">well designed frameworks</a> (apparently sourced by <a href="http://bitworking.org/news/160/Scaling-Matters-Twitter">Joe</a>):</p>
<blockquote><p>
When referring to framework and tooling, &#8220;friction&#8221; is a (subjective) measure of how much the tooling gets in your way when trying to solve a specific-case problem. I&#8217;ve come to evaluate frameworks based on two rough metrics: how far the framework goes in solving the general case problem out of the box and how little friction the framework creates when you have to solve the specific-case problem yourself. When a framework finds a balance between these two areas, we call it &#8220;well designed.&#8221;
</p></blockquote>
<p>It has been my experience that when I follow my <a href="http://udidahan.weblogs.us/2007/05/12/first-principle-of-design-refined/">first principle of design</a>, a good separation of logical packages occurs. These packages enable an appropriate level of flexibility by interacting via interfaces and supporting <a href="http://udidahan.weblogs.us/category/dependency-injection/">Dependency Injection</a>. Of course, a fierce focus on assigning responsibility correctly probably makes quite a difference too. I suppose this is why I shoot for multiple smaller frameworks, than one large one. Beyond being easier to <a href="http://udidahan.weblogs.us/2006/06/24/one-wrong-dll-3-months-gone/">manage in terms of version control</a> and supporting across multiple projects and products, they&#8217;re also quite a bit easier to develop.</p>
<p>Finally, consider that the code you&#8217;re writing is someone else&#8217;s framework/API. For people looking for more advanced API design techniques, check out <a href="http://www.martinfowler.com/bliki/FluentInterface.html">fluent interfaces</a> as well.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/05/14/frictionless-design/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generic Validation</title>
		<link>http://www.udidahan.com/2007/04/30/generic-validation/</link>
		<comments>http://www.udidahan.com/2007/04/30/generic-validation/#comments</comments>
		<pubDate>Mon, 30 Apr 2007 21:54:26 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[Simplicity]]></category>
		<category><![CDATA[Smart Client]]></category>
		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/04/30/generic-validation/</guid>
		<description><![CDATA[Ayende brought up the topic of Input &#038; Business Rule Validation and I wanted to post how I solve this issue.
On kind of input validation is something you do as close to the user as possible for performance reasons. This includes all sorts of smart stuff you can do with JavaScript in Web scenarios. When [...]]]></description>
			<content:encoded><![CDATA[<p>Ayende brought up the topic of <a href="http://ayende.com/Blog/archive/2007/04/02/Input-Validation-vs.Business-Rules-Validation.aspx">Input &#038; Business Rule Validation</a> and I wanted to post how I solve this issue.</p>
<p>On kind of input validation is something you do as close to the user as possible for performance reasons. This includes all sorts of smart stuff you can do with JavaScript in Web scenarios. When in a <a href="http://udidahan.weblogs.us/category/smart-client/">Smart Client</a> environment, you usually have greater capabilities.</p>
<p>When I look at the issue of validation, I see that it centers around the entity. Sometimes, it is also affected by other things, like what process are we in (as described in the comments on Ayende&#8217;s post).</p>
<p>So, we can model the thing that validates an entity with an interface, say, IValidator&lt;T&gt; where T : IEntity. This interface will have one main method: bool IsValid(T entity); and one main property: string ErrorDescription { get; }</p>
<p>What this allows us to do is to separate out different validation concerns into different classes, yet have all of them implement the same interface.</p>
<p>The next thing we&#8217;ll need is to be able to get an instance for each of the classes that is a validator for a specific kind of entity. For instance, when the NewCustomerView raises an event proclaiming that it has a Customer object ready to be saved, the Controller will want to find all classes that implement IValidator&lt;Customer&gt; so that it can run all the validation rules.</p>
<p>Luckily, the <a href="http://udidahan.weblogs.us/2007/04/09/advanced-object-creation-with-dependency-injection/">generics patch</a> I put out for the <a href="http://www.springframework.net">Spring.Net Framework</a> allows us to do this in one simple line of code:</p>
<pre>
IList&lt;IValidator&lt;Customer&gt;&gt; validators = spring.GetObjectsOfType(typeof(IValidator&lt;Customer&gt;));
</pre>
<p>and quite simply perform the validation as follows:</p>
<pre>
foreach(IValidator&lt;Customer&gt; v in validators)
&nbsp;&nbsp;if (!v.IsValid(myCustomer))
&nbsp;&nbsp;&nbsp;&nbsp;// notify user with v.ErrorDescription, write to log, whatever
</pre>
<p>Now, when using this in Smart Client scenarios, you will often have views that allow the user to enter in a single entity which you will then want to validate. If you have those views implement a generic interface like: IEntityView&lt;T&gt; where T : IEntity, then you could have a single base class implement a &#8220;Validate&#8221; method, which would perform the work above generically like so:</p>
<pre>
foreach(IValidator&lt;T&gt; v in spring.GetObjectsOfType(typeof(IValidator&lt;T&gt;)))
&nbsp;&nbsp;if (!v.IsValid(this.Entity))
&nbsp;&nbsp;&nbsp;&nbsp;// notify user with v.ErrorDescription
</pre>
<p>and just have your specific view call that method on the button click.</p>
<p>This enables all entity views to activate all the relevant custom validation logic without being tied to it. It also enables you to extend your system by adding new classes implementing the IValidator&lt;T&gt; interface, and have them automatically run without even changing a config file. How&#8217;s that for loose coupling?</p>
<p>Finally, on the issue of tying validation rules to specific processes, this can be done by extending the interface to: IValidator&lt;T, P&gt; where T : IEntity, P : IProcess; You then model each process with a marker interface. You then have your specific validation classes implement the above generic interface for each specific process interface. For instance, say we have a validation rule that needs to run for processes P1 (marked by IP1), and P2 (marked by IP2), but not P3 (marked by IP3), which validates entities of type E. This would be done by defining the class like so:</p>
<pre>
public class MyValidator : IValidator&lt;E, IP1&gt;, IValidator&lt;E, IP2&gt; {}
</pre>
<p>and the Controller class that would request validators for process 2 would just call:</p>
<pre>
spring.GetObjectsOfType(typeof(IValidator&lt;T, IP2&gt;));
</pre>
<p>That&#8217;s it. The basic principles are simple, but, as you can see, can create very powerful structures. I&#8217;ve got to say that this exemplifies one of the reasons why I love generics so much. When used with <a href="http://udidahan.weblogs.us/category/dependency-injection/">Dependency Injection</a>, and/or Delegates, and/or Anonymous Methods, you get such a power of expression just by defining an interface. This is one of things that make coding fun for me. Or maybe I&#8217;m just wierd that way <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/2007/04/30/generic-validation/feed/</wfw:commentRss>
		<slash:comments>13</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>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>.Net 2.0 no big deal?</title>
		<link>http://www.udidahan.com/2006/10/05/net-20-no-big-deal/</link>
		<comments>http://www.udidahan.com/2006/10/05/net-20-no-big-deal/#comments</comments>
		<pubDate>Thu, 05 Oct 2006 11:36:36 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[BizTalk]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[Workflow]]></category>

		<guid isPermaLink="false">http://wp_630.weblogs.us/archives/327</guid>
		<description><![CDATA[Jesse seems to be swallowing the Microsoft party line without missing a drop in his latest post <a href="http://weblogs.asp.net/jezell/archive/2006/10/05/Screw-2.0_2C00_-I_2700_m-Going-Straight-to-3.0.aspx">Screw 2.0, I'm Going Straight to 3.0</a>. 
<br/><br/>
From his post:
<br/><br/>
<em>
"The 2.0 framework doesn't really give you a massive amount of really new really cool features. There is one-click, which we probably wouldn't use anyway, generics (which are useful as a time saver, but don't really do much that you can't do without them), and some other little features... but the best part about the 2.0 framework is probably the IDE/dev experience, not what customers get out of it."
</em>
<br/><br/>
Granted, One-Click is nothing to write home about, but the runtime level additions, they just totally changed the way I write code. I'm talking about generics, anonymous methods, delegate inference, and the rest. The rest of 2.0, like the enhancements of the provider model in ASP.Net, well you would have developed the same kind of framework yourself if you were doing serious web development.
<br/><br/>
The whole 3.0 story, I've got to tell you, I'm pretty underwhelmed. Everybody seems to be jumping up and down about WPF, and yes, it's new and shiny, but there still the clunkety Windows message pump in the background. No real changes in how you're going to write multi-threaded UIs, which seem to be the real future given the rise in multi-core processing. The visual aspects of client side code in the systems I write run at around 5% of the overall effort. So the UI will look better, I dunno, 4D buttons and stuff, sorry for not falling over with enthusiasm.
<br/><br/>
And then there's WCF. Ah, wait, no publish/subscribe. Bummer, most of my systems being asynchronous in nature are built on the pub/sub model. An OO interface for interprocess communication? Who wants it - I need a message-based interface.
<br/><br/>
Don't forget WF - what was that for again? The main place where WF can fit my needs is for handling long-running workflows between systems, since I don't use Biztalk. But the performance of WF doesn't seem to fit this environment, it seems to be more suited for human workflow times. 
<br/><br/>
If anything, I'd have to say that .Net 2.0 was a relatively big deal. 3.0 will probably be just as important with the runtime level enhancements like lambda expressions, extension methods, anonymous types, and implicitly typed variables. All the rest of the hyped up stuff in 3.0, I don't really expect it to change anything in how I work today.]]></description>
			<content:encoded><![CDATA[<p>Jesse seems to be swallowing the Microsoft party line without missing a drop in his latest post <a href="http://weblogs.asp.net/jezell/archive/2006/10/05/Screw-2.0_2C00_-I_2700_m-Going-Straight-to-3.0.aspx">Screw 2.0, I&#8217;m Going Straight to 3.0</a>. </p>
<p>From his post:</p>
<p><em><br />
&#8220;The 2.0 framework doesn&#8217;t really give you a massive amount of really new really cool features. There is one-click, which we probably wouldn&#8217;t use anyway, generics (which are useful as a time saver, but don&#8217;t really do much that you can&#8217;t do without them), and some other little features&#8230; but the best part about the 2.0 framework is probably the IDE/dev experience, not what customers get out of it.&#8221;<br />
</em></p>
<p>Granted, One-Click is nothing to write home about, but the runtime level additions, they just totally changed the way I write code. I&#8217;m talking about generics, anonymous methods, delegate inference, and the rest. The rest of 2.0, like the enhancements of the provider model in ASP.Net, well you would have developed the same kind of framework yourself if you were doing serious web development.</p>
<p>The whole 3.0 story, I&#8217;ve got to tell you, I&#8217;m pretty underwhelmed. Everybody seems to be jumping up and down about WPF, and yes, it&#8217;s new and shiny, but there still the clunkety Windows message pump in the background. No real changes in how you&#8217;re going to write multi-threaded UIs, which seem to be the real future given the rise in multi-core processing. The visual aspects of client side code in the systems I write run at around 5% of the overall effort. So the UI will look better, I dunno, 4D buttons and stuff, sorry for not falling over with enthusiasm.</p>
<p>And then there&#8217;s WCF. Ah, wait, no publish/subscribe. Bummer, most of my systems being asynchronous in nature are built on the pub/sub model. An OO interface for interprocess communication? Who wants it &#8211; I need a message-based interface.</p>
<p>Don&#8217;t forget WF &#8211; what was that for again? The main place where WF can fit my needs is for handling long-running workflows between systems, since I don&#8217;t use Biztalk. But the performance of WF doesn&#8217;t seem to fit this environment, it seems to be more suited for human workflow times. </p>
<p>If anything, I&#8217;d have to say that .Net 2.0 was a relatively big deal. 3.0 will probably be just as important with the runtime level enhancements like lambda expressions, extension methods, anonymous types, and implicitly typed variables. All the rest of the hyped up stuff in 3.0, I don&#8217;t really expect it to change anything in how I work today.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2006/10/05/net-20-no-big-deal/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Web Service Software Factory &#8211; Data Access CRUD!</title>
		<link>http://www.udidahan.com/2006/09/24/web-service-software-factory-data-access-crud/</link>
		<comments>http://www.udidahan.com/2006/09/24/web-service-software-factory-data-access-crud/#comments</comments>
		<pubDate>Mon, 25 Sep 2006 02:50:47 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[Web Services]]></category>

		<guid isPermaLink="false">http://wp_630.weblogs.us/archives/320</guid>
		<description><![CDATA[And I don't mean CRUD as in Create,Read,Update,Delete.
<br/><br/>
I haven't been following the factories much but David Hayden's <a href="http://codebetter.com/blogs/david.hayden/archive/2006/09/24/Web-Service-Software-Factory-_2D00_-Data-Access-Guidance-Package-_2D00_-Code-Generation.aspx">recent post</a> pulled me back in. Here's an example of the kind of solution that the factory creates:
<br/><br/>
<img src="http://codebetter.com/photos/david.hayden/images/149515/original.aspx" />
<br/><br/>
I thought that object orientation was already accepted as good practice, but here comes Microsoft splitting up data and behavior once again. Business components that have only behavior, and business entities that contain only data (relationships between entities doesn't count as behavior) &#60;shudder/&#62;.
<br/><br/>
If anything, the business components, when you actually look at the code in them, are more service layer objects than anything else. Which kind of makes you wonder why there is a separate Service Implementation layer. Is it because the service implementation is technology dependent? The answer is yes.
<br/><br/>
Wouldn't it be great if we could have service layer objects that were technology independent? Then we could take the code in the "business components" and put it there, and do away with an entire layer.
<br/><br/>
You know where this is heading. The tried and true Domain Model pattern and its friends. Its just that this whole "data access" paradigm that Microsoft keeps pushing gets on my nerves. It just does not hold up in complex domains - I know, I've tried. I've also consulted on many other projects that have tried, and seen them get to the point of no return. The point where programmers just don't know what the domain logic is - because its spread all over the place: service implementation, business components, entities, data access, stored procedures... Its at that point when they have to "ship" so that the project won't be called a failure. Then they scrap the whole thing, and start working on version 2.0 which will be totally different! They use a rules engine! I've already <a href="http://udidahan.weblogs.us/archives/036915.html">wrote about </a>the kinds of successes I've seen there.
<br/><br/>
OK, enough whining. Do your own design. There are other patterns besides what Microsoft puts out. Read them, use them. Just because there's a factory that autogenerates thousands of lines of code, doesn't mean that they're the right thousands of lines of code.]]></description>
			<content:encoded><![CDATA[<p>And I don&#8217;t mean CRUD as in Create,Read,Update,Delete.</p>
<p>I haven&#8217;t been following the factories much but David Hayden&#8217;s <a href="http://codebetter.com/blogs/david.hayden/archive/2006/09/24/Web-Service-Software-Factory-_2D00_-Data-Access-Guidance-Package-_2D00_-Code-Generation.aspx">recent post</a> pulled me back in. Here&#8217;s an example of the kind of solution that the factory creates:</p>
<p><img src="http://codebetter.com/photos/david.hayden/images/149515/original.aspx" /></p>
<p>I thought that <a href="http://udidahan.weblogs.us/category/oo/">object orientation</a> was already accepted as good practice, but here comes Microsoft splitting up data and behavior once again. Business components that have only behavior, and business entities that contain only data (relationships between entities doesn&#8217;t count as behavior) &lt;shudder/&gt;.</p>
<p>If anything, the business components, when you actually look at the code in them, are more <a href="http://udidahan.weblogs.us/2007/04/01/service-layer-separation-of-concerns/">service layer objects</a> than anything else. Which kind of makes you wonder why there is a separate Service Implementation layer. Is it because the service implementation is technology dependent? The answer is yes.</p>
<p>Wouldn&#8217;t it be great if we could have service layer objects that were technology independent? Then we could take the code in the &#8220;business components&#8221; and put it there, and do away with an entire layer.</p>
<p>You know where this is heading. The tried and true <a href="http://udidahan.weblogs.us/2007/04/21/domain-model-pattern/">Domain Model pattern</a> and its friends. Its just that this whole <a href="http://udidahan.weblogs.us/category/data-access/">&#8220;data access&#8221;</a> paradigm that Microsoft keeps pushing gets on my nerves. It just does not hold up in complex domains &#8211; I know, I&#8217;ve tried. I&#8217;ve also consulted on many other projects that have tried, and seen them get to the point of no return. The point where programmers just don&#8217;t know what the domain logic is &#8211; because its spread all over the place: service implementation, business components, entities, data access, stored procedures&#8230; Its at that point when they have to &#8220;ship&#8221; so that the project won&#8217;t be called a failure. Then they scrap the whole thing, and start working on version 2.0 which will be totally different! They use a rules engine! I&#8217;ve already <a href="http://udidahan.weblogs.us/2006/09/05/soa-meets-business-rules/">wrote about </a>the kinds of successes I&#8217;ve seen there.</p>
<p>OK, enough whining. Do your own design. There are other patterns besides what Microsoft puts out. Read them, use them. Just because there&#8217;s a factory that autogenerates thousands of lines of code, doesn&#8217;t mean that they&#8217;re the right thousands of lines of code.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2006/09/24/web-service-software-factory-data-access-crud/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>[Podcast] Does SOA mean the end of OO?</title>
		<link>http://www.udidahan.com/2006/05/26/podcast-does-soa-mean-the-end-of-oo/</link>
		<comments>http://www.udidahan.com/2006/05/26/podcast-does-soa-mean-the-end-of-oo/#comments</comments>
		<pubDate>Fri, 26 May 2006 12:42:55 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Ask Udi Podcast]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[SOA]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/archives/409</guid>
		<description><![CDATA[The recent hype around SOA has raised questions around the continued validity of object orientation. Although there is consensus around the fact that object-oriented languages (like C# and Java) are here to stay, the continued use of object-oriented analysis and design in the new service landscape has been called into question.
Get it via the Dr. [...]]]></description>
			<content:encoded><![CDATA[<p>The recent hype around SOA has raised questions around the continued validity of object orientation. Although there is consensus around the fact that object-oriented languages (like C# and Java) are here to stay, the continued use of object-oriented analysis and design in the new service landscape has been called into question.</p>
<p>Get it via the Dr. Dobb&#8217;s site <a href="http://www.ddj.com/dept/webservices/188500437">here</a>.</p>
<p>Or download directly <a href="http://www.dobbsprojects.com/media/newengine/dynamp.php/060518ud01.mp3?site=sdmg&#038;affiliate=ddj&#038;target=%2Fdept%2Fwebservices%2F&#038;title=Does+SOA+mean+the+en&#038;artist=Ask+Udi+Podcast&#038;album=Dr.+Dobb%27s+Portal&#038;year=2006&#038;podcast=060518ud01.mp3">here</a>.</p>
<p>Want more? Go to the <a href="/ask-udi/">&#8220;Ask Udi&#8221; archives</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2006/05/26/podcast-does-soa-mean-the-end-of-oo/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
<enclosure url="http://www.dobbsprojects.com/media/newengine/dynamp.php/060518ud01.mp3?site=sdmg&amp;affiliate=ddj&amp;target=%2Fdept%2Fwebservices%2F&amp;title=Does+SOA+mean+the+en&amp;artist=Ask+Udi+Podcast&amp;album=Dr.+Dobb%27s+Portal&amp;year=2006&amp;podcast=060518ud01.mp3" length="2395210" type="audio/mp3" />
		</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>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>
