<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Udi Dahan - The Software Simplist &#187; DDD</title>
	<atom:link href="http://www.udidahan.com/category/ddd/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.udidahan.com</link>
	<description>Enterprise Development Expert &#38; SOA Specialist</description>
	<lastBuildDate>Sun, 08 Jan 2012 12:45:00 +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>Recording of joint interview with Eric Evans</title>
		<link>http://www.udidahan.com/2011/11/30/recording-of-joint-interview-with-eric-evans/</link>
		<comments>http://www.udidahan.com/2011/11/30/recording-of-joint-interview-with-eric-evans/#comments</comments>
		<pubDate>Thu, 01 Dec 2011 04:59:14 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[CQRS]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Presentations]]></category>

		<guid isPermaLink="false">http://www.udidahan.com/?p=1597</guid>
		<description><![CDATA[Last month both myself and Eric Evans spoke at a conference run by the International Association of Software Architects (IASA) in Madrid. Eric talked about DDD and I talked about CQRS. While the talks were recorded, I don&#8217;t think they&#8217;ve come online yet.
At the end of the conference, we were interviewed by the local .NET [...]]]></description>
			<content:encoded><![CDATA[<p>Last month both myself and Eric Evans spoke at a conference run by the International Association of Software Architects (IASA) in Madrid. Eric talked about DDD and I talked about CQRS. While the talks were recorded, I don&#8217;t think they&#8217;ve come online yet.</p>
<p>At the end of the conference, we were interviewed by the local .NET magazine dNM and that video is now available <a href="http://vimeo.com/32647895">here</a>. We covered the background on things like DDD, CQRS, and the Cloud. I don&#8217;t think that either of us said anything earth-shattering but if you have half an hour, take a look:</p>
<p><iframe src="http://player.vimeo.com/video/32647895?title=0&amp;byline=0&amp;portrait=0" width="400" height="225" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe></p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2011/11/30/recording-of-joint-interview-with-eric-evans/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Why you should be using CQRS almost everywhere…</title>
		<link>http://www.udidahan.com/2011/10/02/why-you-should-be-using-cqrs-almost-everywhere%e2%80%a6/</link>
		<comments>http://www.udidahan.com/2011/10/02/why-you-should-be-using-cqrs-almost-everywhere%e2%80%a6/#comments</comments>
		<pubDate>Sun, 02 Oct 2011 20:45:44 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Autonomous Services]]></category>
		<category><![CDATA[CQRS]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[SOA]]></category>
		<category><![CDATA[Simplicity]]></category>

		<guid isPermaLink="false">http://www.udidahan.com/?p=1551</guid>
		<description><![CDATA[… but differently than the way most people have been using it.
I think I’ve just about drove everybody crazy now with my apparent zigzagging on CQRS.
Some people heard about CQRS first from one of my presentations and got all excited about it. Then I did some blogging which further drove people to CQRS (as did [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.udidahan.com/wp-content/uploads/grass.jpg" alt="grass" title="grass" width="200" height="150" style="float:right; margin-left:10px; margin-bottom:10px;" />… but differently than the way most people have been using it.</p>
<p>I think I’ve just about drove everybody crazy now with my apparent zigzagging on CQRS.</p>
<p>Some people heard about CQRS first from one of my presentations and got all excited about it. Then I did some blogging which further drove people to CQRS (as did Greg Young and some others). As CQRS was just about to hit its stride with the Early Adopters, I started pushing a more balanced view – CQRS not as an answer, but as one of many questions. More recently I’ve pushed more strongly back against CQRS saying that it should be used rarely.</p>
<h3>So what’s the missing piece?</h3>
<p>If you’re in the Domain-Driven Design camp (as many doing CQRS are), then it’s Bounded Contexts.</p>
<p>If you’re in the Event-Driven SOA camp (a much smaller camp to be sure), then it’s Services.</p>
<p>The problem is the naming, because the DDD guys have their kinds of services which do not fit the definition for Service of the Event-Driven SOA approach.</p>
<p>Let me propose the term Autonomous Business Component for the purposes of this blog post to describe that thing which is both a DDD Bounded Context (have the shared BC part of the acronym) and an SOA Autonomous Services. Resulting in the nice short form:  ABC (and everyone knows you need to have a good acronym if you want something to catch on).</p>
<h3>What does this have to do with CQRS?</h3>
<p>Nothing just yet. Well, at least, nothing directly to do with CQRS.</p>
<p>Although some proponents of CQRS have stated that it can and should be used as the top-most architectural pattern, both myself and Greg Young (arguably the first two to talk about it and the two who ultimately collaborated on naming it – and now Google knows we didn’t means “cars”) always recommended it as a pattern to be used one level down. </p>
<p>Although Greg and I have had many long discussions on the topic and do agree very much about what the overall structure should look like, I’ll try to avoid putting words in his mouth from this point on.</p>
<p>Before talking more about ABCs, let’s discuss the principle upon which they rest: The Single Responsibility Principle (SRP).</p>
<h3>What does SRP have to with CQRS?</h3>
<p>Many developers are familiar with SRP and have seen good results from using it. What we’re going to do is take this principle to the next level.</p>
<p>In Object Orientation (OO), data is encapsulated in an object. A good object does not expose its data to other objects to do with as they wish. Rather, it exposes methods that other objects can invoke, and those methods operate on the internal data.</p>
<p>SRP would guide us to not have the same data exist in two objects. For example, if we saw the customer’s first name as an internal data member of two objects, we’d be right to question that kind of duplication and move to refactor it away. However, when we see two systems doing the exact same thing – somehow that gets excused.</p>
<blockquote><p>“Of course we need to be able to see the customer’s first name in the front-end website as well as in the back-end fulfillment system. How could we NOT have the customer’s first name in both those code-bases?”</p></blockquote>
<p>And there’s the catch.</p>
<p>Who said that a system should be a single code-base?</p>
<h3>But what about integration?</h3>
<p>Although many times we do need to integrate existing systems together, sometimes we have the ability to change those systems. More importantly, when going to create a new solution, we can avoid getting ourselves into the problems that integration tries to solve.</p>
<p>Integrating with a system that cannot be changed can be done also by composing multiple ABCs, but that’s a topic for another post.</p>
<p>It is better to think of integration as a necessary evil – kind of like regular expressions and multi-threading; things to be avoided unless absolutely necessary.</p>
<p>“If you have a problem that you decide to use a regular expression to solve, you now have 2 problems.” Or so the saying goes. With multi-threading, you have a non-deterministic number of problems to solve.</p>
<p>If you thought you had duplicate responsibilities with 2 systems operating on the same data, how will introducing a 3rd code base (also known as “integration”) help? Remember that Single Responsibility Principle – our goal is to get it down to one.</p>
<h3>OK, so how do ABCs do that?</h3>
<p>In order for us to get back into alignment with SRP, that would require us to have responsibility for a single piece of data exist in one code base. Note that SRP makes no statements about how many physical places a given code base can be deployed to. Nor does it state that only a single technology can be in play – code that emits HTML can be packaged at design time together with rich-client code in the same solution.</p>
<p>If an ABC is responsible for a piece of data, it is responsible for it everywhere, and forever. No other ABC should see that data. That data should not travel between ABCs via remote procedure call (RPC) or via publish/subscribe. It is the ultimate level of encapsulation – SRP applied at the highest level of granularity.</p>
<p>This results in systems which are the result of deploying the components of multiple ABCs to the same physical place. The ABC which owns the customer name would have the necessary web code to render it in the e-commerce front-end and in the shipping back-end for printing on labels. This would mean that practically every screen in any UI is a composite of widgets owned by their respective ABCs.</p>
<p>This is ultimately what keeps the complexity of each ABC’s code base to a minimum. </p>
<h3>But why not just use CQRS as the top-level pattern? ABCs are weird.</h3>
<p>Imagine trying to create a single denormalized view model for the entire Amazon.com product page – product name, price, inventory, editorial review, customer comments, other products that customers viewed, other products that customers bought, etc. </p>
<p>Pretty complex, right?</p>
<p>How much duplication would you have for the page shown after you add an item to a cart? Once again, you need to show other products that customers bought, their names, images, prices, and inventory. </p>
<p>And then on the home page – items you might be interested in, names, images, prices.</p>
<p>And that’s only in the front-end system.</p>
<p>It’s not just the duplication, but how complex the code is for each one.</p>
<p>Instead of the duplication that top-level CQRS would bring you, consider an ABC responsible for products names and images that has just about the same view model composed on each of the above screens. The same with another ABC responsible for price.</p>
<p>You may be thinking that this would result in more queries to get the data to show on a page, and you’d be right. But it isn’t necessarily a classical N+1 Select problem, as the queries are bounded to the number of ABCs. Secondly, consider the ability to have well-tuned caching at the granularity of an ABC – something that would be much more difficult when dealing with everything as a single monolithic view model. In short, not only will it not be a performance problem, often it will actually improve performance.</p>
<h3>OK – that explains “everywhere”, what about “forever”?</h3>
<p>Forever is where things get interesting – or more accurately, when they get interesting.</p>
<p>Let’s talk about things like invoices.</p>
<p>One of the requirements in this area is that immutability. If the customer’s name was Jane Smith when they made their purchase, it doesn’t matter that they’ve since changed their name to Jane Jones, the invoice should still show Jane Smith.</p>
<p>Often developers push these types of requirements on the data warehouse guys – that’s where history gets handled. The only thing is that if your ABC owns the customer’s name, then no other code base can deal with it. If it’s your data, you have to handle all historical representations of it.</p>
<p>On the one hand, this would seem to kill the data warehouse. On the other hand, it means that the principles of data warehouses are now core to every code-base.</p>
<p>This means you don’t ever delete data (see my <a href="http://www.udidahan.com/2009/09/01/dont-delete-just-dont/">previous blog post</a> on the subject), and you definitely don’t overwrite it with an update – even if you think you’re in a simple CRUD domain. The only case where you can get away with traditional CRUD is if we’re talking about private data – data that is only ever acted on by a single actor.</p>
<h3>This sounds like the collaboration you talk about with CQRS</h3>
<p>It’s similar in principle but different in practice.</p>
<p>In a collaborative domain, an inherent property of the domain is that multiple actors operate in parallel on the same set of data. A reservation system for concerts would be a good example of a collaborative domain – everyone wants the “good seats” (although it might be better call that competitive rather than collaborative, it is effectively the same principle).</p>
<p>A customer’s name would not fall under that category. It isn’t an inherent property of the domain for multiple actors to operate on that data. While there can be multiple readers, one can easily enforce a single writer without any adverse effects. Doing that with a reservation system would cause the online system to behave as if users were lining up in front of a box office – not a desirable outcome.</p>
<p>Private data would be something like a user’s shopping cart. Until they make a purchase, that data doesn’t need to be visible anywhere. Here you could theoretically do simple CRUD – that is, until the business realizes that there’s extremely valuable information to be extracted from the historical record of things people do with their carts.</p>
<h3>I think you’re ready to make your point, so just make it already</h3>
<p>OK – so we now realize that Update and Delete don’t exist in their traditional form. Delete is really just a kind of update, and update is effectively an “upsert” – a combination of update and insert to retain history. This can be done by having ValidFrom and ValidTo columns for our data.</p>
<p>In which case, Create is really just a special case of Upsert, which looks like this:</p>
<blockquote><p>UPDATE Something SET ValidTo = NOW() WHERE Id=@Id AND ValidTo = NULL; INSERT INTO Something SET { regular values }, Id=@Id, ValidTo = NULL;</p></blockquote>
<p>And then we’d have 2 forms of Read – reading the current state (ValidTo = NULL), and reading history (ValidFrom <= Instant AND (ValidTo >= Instant OR ValidTo = NULL))</p>
<p>Here we don’t need fancy N-Tier architectures, data transfer objects, service layers, or domain models. A simple 2-Tier approach could probably suffice. We don’t need a task-based UI, events, denormalized view models, or any of that CQRS stuff. This was at the crux of my previous <a href="http://www.udidahan.com/2011/04/22/when-to-avoid-cqrs/">anti-CQRS post</a>.</p>
<p>The only thing is that this is exactly CQRS.</p>
<h3>Say what?</h3>
<p>Have we not effectively separated the responsibility of commands/upserts and queries/reads?</p>
<p>As Greg Young has said before, “the creation of 2 objects where there previously was one”.</p>
<p>Effectively 2 paths through our ABC.</p>
<p>CQRS.</p>
<p>Let me give you a second to gather your thoughts.</p>
<p>*</p>
<p>You see, CQRS is an approach, a mind-set – not a cookie cutter solution. Frameworks that guide you to applying CQRS exactly the same way everywhere are taking you in the wrong direction. The fact is that you couldn’t possibly know what your Aggregate Roots were before you figured out how to break your system down into ABCs. Attempting to create commands and events for everything will make you overcomplicate your solution.</p>
<h3>So the built-in history of this model is event-sourcing?</h3>
<p>Well, it’s not event-sourcing in the sense that we don’t necessarily have events. It achieves many of the benefits of event-sourcing by giving us the full history of what happened.</p>
<p>On the whole issue of replaying events to fix bugs – that’s a bit problematic, logically, unless we have a closed system. A closed system is one that doesn’t interact with anything else – no other systems, no users, nothing. As such, closed systems aren’t that common.</p>
<p>In an open system, one with users, let’s say there was a bug. This bug could have caused the wrong data to be written and/or shown to users. As such, users could have submitted subsequent commands based on that erroneous data that they would not have submitted otherwise. There’s no way for us to know.</p>
<p>The problem with replaying events when we fix the bug is that we’re in essence rewriting history – making it as if the user didn’t see the wrong data. The only problem is that we can’t know which events not to replay – we can’t automatically come up with the right events that should have come afterwards. We could try to sit together with our users and have them try to revise history manually, but our organization often isn’t in a bubble. Our users interacted with customers and suppliers. It isn’t feasible to try to undo the real-world impacts of this situation.</p>
<h3>Why didn’t you just tell us this from the very beginning?</h3>
<p>I did, you just weren’t listening.</p>
<p>You wanted a cookie cutter, and until you tried CQRS out as cookie cutter (and saw it create a bunch of complexity) you wouldn’t listen to anything else. </p>
<p>As developers, we’re trained to solve problems – the faster the better. Unfortunately, this causes us to be blind to things that don’t immediately present themselves as solutions.</p>
<p>When applying CQRS with ABCs, the solutions you end up with are very simple, but the process of getting there is quite hard and takes practice. Finding the boundaries of ABCs such that data isn’t duplicated between them and that data doesn’t travel between them either via RPC or publish/subscribe – it may feel impossible the first several times you try. Keep at it – it is almost always possible.</p>
<p>We haven’t touched on the whole saga/aggregate-root thing yet, but that isn’t as important until you can successfully apply the principles described here.</p>
<p>Also, this post has already gotten long enough, so it looks like now would be a good time to stop.</p>
<p>Until next time…</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2011/10/02/why-you-should-be-using-cqrs-almost-everywhere%e2%80%a6/feed/</wfw:commentRss>
		<slash:comments>47</slash:comments>
		</item>
		<item>
		<title>Inconsistent data, poor performance, or SOA &#8211; pick one</title>
		<link>http://www.udidahan.com/2011/09/18/inconsistent-data-poor-performance-or-soa-pick-one/</link>
		<comments>http://www.udidahan.com/2011/09/18/inconsistent-data-poor-performance-or-soa-pick-one/#comments</comments>
		<pubDate>Sun, 18 Sep 2011 16:52:17 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Autonomous Services]]></category>
		<category><![CDATA[Business Rules]]></category>
		<category><![CDATA[CQRS]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Databases]]></category>
		<category><![CDATA[Reliability]]></category>
		<category><![CDATA[SOA]]></category>

		<guid isPermaLink="false">http://www.udidahan.com/?p=1527</guid>
		<description><![CDATA[One of the things that surprises some developers that I talk to is that you don&#8217;t always get consistency even with end-to-end synchronous communication and a single database. This goes beyond things like isolation levels that some developers are aware of and is particularly significant in multi-user collaborative domains.
The problem
Let&#8217;s start with an image to [...]]]></description>
			<content:encoded><![CDATA[<p>One of the things that surprises some developers that I talk to is that you don&#8217;t always get consistency even with end-to-end synchronous communication and a single database. This goes beyond things like isolation levels that some developers are aware of and is particularly significant in multi-user collaborative domains.</p>
<h3>The problem</h3>
<p>Let&#8217;s start with an image to describe the scenario:</p>
<p><img src="http://www.udidahan.com/wp-content/uploads/Inconsistency1.gif" alt="Inconsistency" title="Inconsistency" width="600" height="285" class="aligncenter size-full wp-image-1533" /><br />
<center>Image 1. 3 transactions working in parallel on 3 entities</center></p>
<p>The main issue we have here is that the values transaction 2 gets for A and B are those from T0 &#8211; before either transaction 1 or 3 completed. The reason this is an issue is that these old values (usually together with some message data) are used to calculate what the new state of C should be. </p>
<p>Traditional optimistic concurrency techniques won&#8217;t detect any problem if we don&#8217;t touch A or B in transaction 2.</p>
<p>In short, systems today are causing inconsistency.</p>
<h3>Some solutions</h3>
<p>1. Don&#8217;t have transactions which operate on multiple entities (which probably isn&#8217;t possible for some of your most important business logic).</p>
<p>2. Turn on <a href="http://en.wikipedia.org/wiki/Multiversion_concurrency_control">multi-version concurrency control</a> &#8211; this is called snapshot isolation in MS Sql Server.</p>
<p>Yes, you need to turn it on. It&#8217;s off by default.</p>
<p>The good news is that this will stop the writing of inconsistent data to your database.<br />
The bad news is that it will probably cause your system many more exceptions when going to persist.</p>
<p>For those of you who are using transaction messaging with automatic retrying, this will end up as &#8220;just&#8221; a performance problem (unless you follow the recommendations below). For those of you who are using regular web/wcf services (over tcp/http), you&#8217;re &#8220;cross cutting&#8221; exception management will likely end up discarding all the data submitted in those requests (but since that&#8217;s what you&#8217;re doing when you run into deadlocks this shouldn&#8217;t be news to you).</p>
<h3>The solution to the performance issues</h3>
<p>Eventual consistency.</p>
<p>Funny isn&#8217;t it &#8211; all those people who were afraid of eventual consistency got <b>inconsistency</b> instead.</p>
<p>Also, it&#8217;s not enough to just have eventual consistency (like between the command and query sides of CQRS). You need to drastically decrease the size of your entities. And the best way of doing that is to partition those entities across multiple business services (also known in DDD lingo as Bounded Contexts) each with its own database.</p>
<p>This is yet another reason why I say that CQRS shouldn&#8217;t be the top level architectural breakdown. Very useful within a given business service, yes &#8211; though sometimes as small as just some sagas.</p>
<h3>Next steps</h3>
<p>It may seem unusual that the title of this post implies that SOA is the solution, yet the content clearly states that traditional HTTP-based web services are a problem. Even REST wouldn&#8217;t change matters as it doesn&#8217;t influence how transactions are managed against a database.</p>
<p>The SOA solution I&#8217;m talking about here is the one I&#8217;ve spent the last several years <a href="http://www.udidahan.com/category/soa/">blogging about</a>. It&#8217;s a different style of SOA which has services stretch up to contain parts of the UI as well as down to contain parts of the database, resulting in a composite UI and multiple databases. This is a drastically different approach than much of the literature on the topic &#8211; especially Thomas Erl&#8217;s books.</p>
<p>Unfortunately there isn&#8217;t a book out there with all of this in it (that I&#8217;ve found), and I&#8217;m afraid that with my schedule (and family) writing a book is pretty much out of the question. Let&#8217;s face it &#8211; I&#8217;m barely finding time to blog.</p>
<p>The one thing I&#8217;m trying to do more of is provide training on these topics. I&#8217;ve just finished a course in London, doing another this week in Aarhus Denmark, and another next month in San Francisco (which is now sold out). The next openings this year will be in Stockholm, London; Sydney Australia and Austin Texas will be coming in January of next year. I&#8217;ll be coming over to the US more next year so if you missed San Francisco, keep an eye out.</p>
<p>I wish there was more I could do, but I&#8217;m only one guy.</p>
<p>Hmm, maybe it&#8217;s time to change that.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2011/09/18/inconsistent-data-poor-performance-or-soa-pick-one/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>When to avoid CQRS</title>
		<link>http://www.udidahan.com/2011/04/22/when-to-avoid-cqrs/</link>
		<comments>http://www.udidahan.com/2011/04/22/when-to-avoid-cqrs/#comments</comments>
		<pubDate>Fri, 22 Apr 2011 20:32:50 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[CQRS]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Databases]]></category>
		<category><![CDATA[Messaging]]></category>
		<category><![CDATA[SOA]]></category>
		<category><![CDATA[Scalability]]></category>
		<category><![CDATA[Simplicity]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://www.udidahan.com/?p=1441</guid>
		<description><![CDATA[It looks like that CQRS has finally &#8220;made it&#8221; as a full blown &#8220;best practice&#8221;.
Please accept my apologies for my part in the overly-complex software being created because of it.
I&#8217;ve tried to do what I could to provide a balanced view on the topic with posts like Clarified CQRS and Race Conditions Don&#8217;t Exist.
It looks [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.udidahan.com/wp-content/uploads/image20.png" alt="which way?" title="which way?" style="float:right; margin-left:10px; margin-bottom:10px;" />It looks like that CQRS has finally &#8220;made it&#8221; as a full blown &#8220;best practice&#8221;.</p>
<p>Please accept my apologies for my part in the overly-complex software being created because of it.</p>
<p>I&#8217;ve tried to do what I could to provide a balanced view on the topic with posts like <a href="http://www.udidahan.com/2009/12/09/clarified-cqrs/">Clarified CQRS</a> and <a href="http://www.udidahan.com/2010/08/31/race-conditions-dont-exist/">Race Conditions Don&#8217;t Exist</a>.</p>
<p>It looks like that wasn&#8217;t enough, so I&#8217;ll go right out and say it:</p>
<p>Most people using CQRS (and <a href="http://codebetter.com/gregyoung/2010/02/20/why-use-event-sourcing/">Event Sourcing</a> too) shouldn&#8217;t have done so.</p>
<h3>Should we really go back to N-Tier?</h3>
<p>When not using CQRS (which is the majority of the time), you don&#8217;t need N-Tier either.</p>
<p>You see, if you&#8217;re not in a collaborative domain then you don&#8217;t have multiple writers to the same logical set of data as an inherent property of your domain. As such, having a single database where all data lives isn&#8217;t really necessary. </p>
<p>Data is inherently partitioned by who owns it.</p>
<p>Let&#8217;s take the online shopping cart as an example. There aren&#8217;t any use cases where users operate on each others&#8217; carts &#8211; ergo, not collaborative, therefore not a good candidate for CQRS. Same goes for user profiles, and tons of other cases.</p>
<p>So why is it that we need a separate tier to run our business logic?</p>
<p>Originally, the application server tier was introduced for improved scalability, but specifically around managing the connection pool to the database. Increasing numbers of clients (when each had its own user/account for connecting to the database) caused problems. Luckily, most web applications side-step this problem &#8211; that is, until someone got the idea that the web server was only supposed to run the UI layer, and the Business Logic layer would be on a separate application server tier.</p>
<p>Rubbish &#8211; see Fowler&#8217;s First Law of Distribution: Don&#8217;t.</p>
<p>Keep it all on one tier. Same goes for smart clients.<br />
No, Silverlight, you don&#8217;t count &#8211; architecturally speaking, you&#8217;re a glorified browser.</p>
<h3>But what about scalability?</h3>
<p>In a non-collaborative domain, where you can horizontally add more database servers to support more users/requests/data at the same time you&#8217;re adding web servers &#8211; there is no real scalability problem (caveat, until you&#8217;re Amazon/Google/Facebook scale). </p>
<p>Database servers can be cheap &#8211; if using MySQL/SQL Express/others. </p>
<h3>But what about the built-in event-log CQRS/ES gives us?</h3>
<p>Architectural gold-plating / stealing from the business.</p>
<p>Who put you in a position to decide that development time and resources should be diverted from short-term business-value-adding features to support a non-functional requirement that the business didn&#8217;t ask for?</p>
<p>If you sat down with them, explaining the long-term value of having an archive of all actions in the system, and they said OK, build this into the system from the beginning, that would be fine. Most people who ask me about CQRS and/or Event Sourcing skip this step.</p>
<p>Finally, you can usually implement this specific requirement with some simple interception and logging. Don&#8217;t over-engineer the solution. If using messaging, you can get this by turning on journaling, or if you want to centralize this archive, NServiceBus can forward all messages to a specific queue. </p>
<p>Don&#8217;t forget that this storage has a cost &#8211; including administration. Nothing is free.</p>
<h3>What about the &#8220;proof of correctness&#8221; in Event Sourcing</h3>
<p>I&#8217;ve heard statements made that when you use the events that flowed into/through your system <b>AS</b> your system&#8217;s data, rather than transforming those events to some other schema (relational or otherwise) and storing the result &#8211; you can prove that your system behaves correctly.</p>
<p>Let me put it this way:</p>
<p>No programming technique used by humans will prevent those same humans from creating bugs.<br />
No testing technique used by humans will prevent those same humans from not catching those bugs.<br />
* Automated tests &#8211; see programming technique.</p>
<p>While having a full archive of all events can allow us to roll the system back to some state, fix a bug, and roll forwards, that assumes that we&#8217;re in a closed system. We have users which are outside the system. If a user made a decision based on data influenced by the bug, there&#8217;s no automated way for us to know that, or correct for it as we roll forwards.</p>
<p>In short, we&#8217;re interested in the business&#8217; behavior &#8211; as composed of user and system behavior. No proof can exist.</p>
<h3>Umm, so where should we use it</h3>
<p>If you&#8217;ve uncovered a scenario where you&#8217;re wondering &#8220;first-one-wins, or last-one-wins&#8221;, that&#8217;s often a good candidate for a place where CQRS <b>could</b> make sense. Then re-read my <a href="http://www.udidahan.com/2010/08/31/race-conditions-dont-exist/">Race Conditions Don&#8217;t Exist post</a>.</p>
<p>Also, CQRS should not be your top-level architectural pattern &#8211; that would be SOA.<br />
CQRS, if used at all, would be used inside a service boundary only.</p>
<p>Given that SOA guides us away from having a given 3rd normal form entity exist in any one service, it is unlikely that the building blocks of your CQRS design will be those kinds of entities. Most 3rd normal form one-to-many and many-to-many relationships simply do not exist when doing SOA and CQRS properly.</p>
<p>Therefore, I&#8217;m sorry to say that most sample application you&#8217;ll see online that show CQRS are architecturally wrong. I&#8217;d also be extremely wary of frameworks that guide you towards an entity-style aggregate root CQRS model.</p>
<h3>In Summary</h3>
<p>So, when should you avoid CQRS?</p>
<p>The answer is most of the time.</p>
<p>Here&#8217;s the strongest indication I can give you to know that you&#8217;re doing CQRS correctly: Your aggregate roots are sagas.</p>
<p>And the biggest caveat &#8211; the above are generalizations, and can&#8217;t necessarily be true for every specific scenario. If you&#8217;re Greg Young, then you probably can (and will) decide on your own on these matters. For everybody else, please take these warnings to heart. There have been far too many clients that have come to me all mixed up with their use CQRS in areas where it wasn&#8217;t warranted.</p>
<p>If you want to know everything you need to know to apply CQRS appropriately, please come to <a href="http://www.udidahan.com/training/#Advanced_Distributed_System_Design">my course</a> &#8211; there is so much unlearning to do first that just can&#8217;t happen via a series of blog posts.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2011/04/22/when-to-avoid-cqrs/feed/</wfw:commentRss>
		<slash:comments>34</slash:comments>
		</item>
		<item>
		<title>Entities, Transactions, and Broken Boundaries</title>
		<link>http://www.udidahan.com/2011/03/05/entities-transactions-and-broken-boundaries/</link>
		<comments>http://www.udidahan.com/2011/03/05/entities-transactions-and-broken-boundaries/#comments</comments>
		<pubDate>Sat, 05 Mar 2011 11:44:46 +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[DataSets]]></category>
		<category><![CDATA[Databases]]></category>
		<category><![CDATA[OO]]></category>

		<guid isPermaLink="false">http://www.udidahan.com/?p=1409</guid>
		<description><![CDATA[One of the things I cover early on in my course is the problem with traditional layered architecture driving people to create a business logic layer made up of a bunch of inter-related entities. I see this happening a lot, even though nowadays people are calling that bunch of inter-related entities a &#8220;domain model&#8221;.
Let me [...]]]></description>
			<content:encoded><![CDATA[<p>One of the things I cover early on in my course is the problem with traditional layered architecture driving people to create a business logic layer made up of a bunch of inter-related entities. I see this happening a lot, even though nowadays people are calling that bunch of inter-related entities a &#8220;domain model&#8221;.</p>
<p>Let me just say this upfront &#8211; most inter-related entity models are NOT a domain model.<br />
Here&#8217;s why: most transactions don&#8217;t respect entity boundaries.</p>
<p>That being said, you don&#8217;t always need a domain model.<br />
The domain model pattern&#8217;s context is &#8220;if you have complicated and everchanging business rules&#8221; &#8211; right there on page 119 of Patterns of Enterprise Application Architecture.</p>
<p>Persisting the customer&#8217;s first name, last name, and middle initial &#8211; and later reading and showing that data does not sound either complicated or that it is really going to change that much.</p>
<p>Then there are things like credit limits, that may be on the customer entity as well. It is likely that there are business requirements that expect that value to be consistent with the total value of unpaid orders &#8211; data that comes from other entities. </p>
<p>The problem that is created is one of throughput.</p>
<p>Since databases lock an entire row/entity at a time, if one transaction is changing the customer&#8217;s first name, the database would block another transaction that tried to change the same customer&#8217;s credit limit.</p>
<p>The bigger your entities, the more transactions will likely need to operate on them in parallel, the slower your system will get as the number of transactions increases. This feeds back in on itself as often those blocked transactions will have operated already on some other entity, leaving those locked for longer periods of times, blocking even more transactions.</p>
<p>And the absurd thing is that the business never demanded that the customer&#8217;s first name be consistent with the credit limit.</p>
<p>What if we didn&#8217;t have a single Customer entity?</p>
<p>What if we had one that contained first name, last name, middle initial and another that contained things like credit limit, status, and risk rating. These entities would be correlated by the same ID, but could be stored in separate tables in the database. That would do away with much of the cascading locking effects drastically improving our throughput as load increases.</p>
<p>And you know what? That division would still respect the 3rd normal form.</p>
<p>Which of these entities do you think would be classified by the business under the &#8220;complicated and everchanging rules&#8221; category? </p>
<p>And for those entities that are just about data persistence &#8211; do you think it&#8217;s justified to use 3 tiers? Do we really need a view model which we transform to data transfer objects which we transform to domain objects which we transform to relational tables and then all the way back? Wouldn&#8217;t some simpler 2-tier programming suffice &#8211; dare I say datasets? Ruby on Rails? </p>
<p>Are we ready to leave behind the assumption that all elements of a given layer must be built the same way?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2011/03/05/entities-transactions-and-broken-boundaries/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>CQRS, DDD, and NServiceBus video</title>
		<link>http://www.udidahan.com/2010/06/18/cqrs-ddd-and-nservicebus-video/</link>
		<comments>http://www.udidahan.com/2010/06/18/cqrs-ddd-and-nservicebus-video/#comments</comments>
		<pubDate>Fri, 18 Jun 2010 11:11:19 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[CQRS]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[NServiceBus]]></category>
		<category><![CDATA[Presentations]]></category>

		<guid isPermaLink="false">http://www.udidahan.com/?p=1306</guid>
		<description><![CDATA[Following the theme of my last few blog posts, this post will also be pointing you to videos of me talking.
After I had finished speaking at QCon London last March, I sat down for a short interview with the guys from InfoQ chatting about topics from CQRS, to DDD, to NServiceBus. I&#8217;m happy to say [...]]]></description>
			<content:encoded><![CDATA[<p>Following the theme of my last few blog posts, this post will also be pointing you to videos of me talking.</p>
<p>After I had finished speaking at QCon London last March, I sat down for a short interview with the guys from InfoQ chatting about topics from CQRS, to DDD, to NServiceBus. I&#8217;m happy to say that the interview is now online with a full (and mostly accurate) transcript as well as with an MP3 download link.</p>
<p>Get it here: <a href="http://www.infoq.com/interviews/dahan-cqrs-ddd-nservicebus">Udi Dahan on CQRS, DDD and NServiceBus</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2010/06/18/cqrs-ddd-and-nservicebus-video/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>DDD Exchange London 2010</title>
		<link>http://www.udidahan.com/2010/06/17/ddd-exchange-london-2010/</link>
		<comments>http://www.udidahan.com/2010/06/17/ddd-exchange-london-2010/#comments</comments>
		<pubDate>Thu, 17 Jun 2010 09:03:03 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[DDD]]></category>
		<category><![CDATA[Presentations]]></category>

		<guid isPermaLink="false">http://www.udidahan.com/?p=1300</guid>
		<description><![CDATA[Last Friday I was in London for the DDD Exchange. It was great seeing Eric Evans again and Greg Young, who I haven&#8217;t seen for at least a couple of years. It might take some time for Skills Matter to get the videos online so in the mean time I wanted to point you to [...]]]></description>
			<content:encoded><![CDATA[<p>Last Friday I was in London for the DDD Exchange. It was great seeing Eric Evans again and Greg Young, who I haven&#8217;t seen for at least a couple of years. <strike>It might take some time for Skills Matter to get the videos online</strike> so in the mean time I wanted to point you to <a href="http://gojko.net/2010/06/11/udi-dahan-the-biggest-mistakes-teams-make-when-applying-ddd/">Gojko blog post</a> where he pretty much transcribed my talk word for word.</p>
<h3>Update</h3>
<p>The recording of the talk is now online and can be found <a href="http://skillsmatter.com/podcast/design-architecture/architectural-innovation-cqrs/zx-486">here</a>.</p>
<p>You can find the slides for my talk <a href="http://cid-b7c8241e48100dc4.office.live.com/view.aspx/Blog/DDD%5E_Exchange%5E_Domain%5E_models.pptx">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2010/06/17/ddd-exchange-london-2010/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Progressive .NET Wrap-up</title>
		<link>http://www.udidahan.com/2009/09/07/progressive-net-wrap-up/</link>
		<comments>http://www.udidahan.com/2009/09/07/progressive-net-wrap-up/#comments</comments>
		<pubDate>Mon, 07 Sep 2009 06:06:30 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Business Rules]]></category>
		<category><![CDATA[Caching]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Databases]]></category>
		<category><![CDATA[ESB]]></category>
		<category><![CDATA[Messaging]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Pub/Sub]]></category>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

