<?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; Testing</title>
	<atom:link href="http://www.udidahan.com/category/testing/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>The Danger of Centralized Workflows</title>
		<link>http://www.udidahan.com/2011/07/13/the-danger-of-centralized-workflows/</link>
		<comments>http://www.udidahan.com/2011/07/13/the-danger-of-centralized-workflows/#comments</comments>
		<pubDate>Wed, 13 Jul 2011 08:05:19 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Autonomous Services]]></category>
		<category><![CDATA[BPM]]></category>
		<category><![CDATA[BizTalk]]></category>
		<category><![CDATA[Business Rules]]></category>
		<category><![CDATA[EDA]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[Pub/Sub]]></category>
		<category><![CDATA[SOA]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Workflow]]></category>

		<guid isPermaLink="false">http://www.udidahan.com/?p=1493</guid>
		<description><![CDATA[It isn&#8217;t uncommon for me to have a client or student at one of my courses ask me about some kind of workflow tool. This could be Microsoft Workflow Foundation, BizTalk, K2, or some kind of BPEL/orchestration engine. The question usually revolves around using this tool for all workflows in the system as opposed to [...]]]></description>
			<content:encoded><![CDATA[<p>It isn&#8217;t uncommon for me to have a client or student at one of my courses ask me about some kind of workflow tool. This could be Microsoft Workflow Foundation, BizTalk, K2, or some kind of BPEL/orchestration engine. The question usually revolves around using this tool for all workflows in the system as opposed to the SOA-EDA-style publish/subscribe approach I espouse.</p>
<h3>The question</h3>
<p>The main touted benefit of these workflow-centric architectures is that we don&#8217;t have to change the code of the system in order to change its behavior resulting in ultimate flexibility!</p>
<p>Some of you may have already gone down this path and are shaking your heads remembering how your particular road to hell was paved with the exact same good intentions.</p>
<p>Let me explain why these things tend to go horribly wrong.</p>
<h3>What&#8217;s behind the curtain</h3>
<p>It starts with the very nature of workflow &#8211; a flow chart, is procedural in nature. First do this, then that, if this, then that, etc. As we&#8217;ve experienced first hand in our industry, procedural programming is fine for smaller problems but isn&#8217;t powerful enough to handle larger problems. That&#8217;s why we&#8217;ve come up with object-oriented programming.</p>
<p>I have yet to see an object-oriented workflow drag-and-drop engine. Yes, it works great for simple demo-ware apps. But if you try to through your most complex and volatile business logic at it, it will become a big tangled ball of spaghetti &#8211; just like if you were using text rather than pictures to code it.</p>
<p>And that&#8217;s one of the fundamental fallacies about these tools &#8211; you are still writing code. The fact that it doesn&#8217;t look like the rest of your code doesn&#8217;t change that fact. Changing the definition of your workflow in the tool IS changing your code. </p>
<h3>On productivity</h3>
<p>Sometimes people mention how much more productive it would be to use these tools than to write the code &#8220;by hand&#8221;. Occasionally I hear about an attempt to have &#8220;the business&#8221; use these tools to change the workflows themselves &#8211; without the involvement of developers (&#8221;imagine how much faster we could go without those pesky developers!&#8221;).</p>
<p>For those of us who have experienced this first-hand, we know that&#8217;s all wrong. </p>
<p>If &#8220;the business&#8221; is changing the workflows without developer involvement, invariably something breaks, and then they don&#8217;t know what to do. They haven&#8217;t been trained to think the way that developers have &#8211; they don&#8217;t really know how to debug. So the developers are brought back in anyway and from that point on, the business is once again giving requirements and the devs are the one implementing it.</p>
<p>Now when it comes to developer productivity, I can tell you that the keyboard is at least 10x more productive than the mouse. I can bang out an if statement in code much faster than draggy-dropping a diamond on the canvas, and two other activities for each side of the clause.</p>
<h3>On maintainability</h3>
<p>Sometimes the visualization of the workflow is presented as being much more maintainable than &#8220;regular code&#8221;. </p>
<p>When these workflows get to be to big/nested/reused, it ends up looking like the wiring diagram of an Intel chip (or worse). Check out the following diagram taken from the DailyWTF on a <a href="http://thedailywtf.com/Articles/The_Customer-Friendly_System.aspx">customer friendly system</a>:</p>
<p><img src="http://www.udidahan.com/wp-content/uploads/stateModel.gif" alt="stateModel" title="stateModel" width="500" height="564" /></p>
<p>The bigger these get, the less maintainable they are.</p>
<p>Now, some would push back on this saying that a method with 10,000 lines of code in it may be just as bad, if not worse. The thing is that these workflow tools guide developers down a path where it is very likely to end up with big, monolithic, procedural, nested code. When working in real code, we know we need to take responsibility for the cleanliness of our code using object-orientation, patterns, etc and refactoring things when they get too messy.</p>
<p>Here is where I&#8217;d bring up the SOA/pub-sub approach as an alternative &#8211; there is no longer this idea of a centralized anything. You have small pieces of code, each encapsulating a single business responsibility, working in concert with each other &#8211; reacting to each others events.</p>
<h3>Productivity take 2: testing and version control</h3>
<p>If you&#8217;re going to take your most complex and volatile business logic and put it into these workflow tools, have you thought about how your going to test it? How do you know that it works correctly? It tends to be VERY difficult to unit-test these kinds of workflows.</p>
<p>When a developer is implementing a change request, how do they know what other workflows might have been broken? Do they have to manually go through each and every scenario in the system to find out? How&#8217;s that for productivity?</p>
<p>Assuming something did break and the developer wants to see a diff &#8211; what&#8217;s different in the new workflow from the old one, what would that look like? When working with a team, the ability to diff and merge code is at the base of the overall team productivity.</p>
<p>What would happen to your team if you couldn&#8217;t diff or merge code anymore?<br />
In this day and age, it should be considered irresponsible to develop without these version control basics.</p>
<h3>In closing</h3>
<p>There are some cases where these tools might make sense, but those tend to be much more rare than you&#8217;d expect (and there are usually better alternatives anyway). Regardless, the architectural analysis should start without the assumption of centralized workflow, database, or centralized anything for that matter.</p>
<p>If someone tries to push one of these tools/architectures on you, don&#8217;t walk away &#8211; run!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2011/07/13/the-danger-of-centralized-workflows/feed/</wfw:commentRss>
		<slash:comments>45</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>On Design for Testability</title>
		<link>http://www.udidahan.com/2010/04/18/on-design-for-testability/</link>
		<comments>http://www.udidahan.com/2010/04/18/on-design-for-testability/#comments</comments>
		<pubDate>Sun, 18 Apr 2010 15:43:57 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Management]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[The Team]]></category>

		<guid isPermaLink="false">http://www.udidahan.com/?p=1221</guid>
		<description><![CDATA[Almost at every conference, event, training, or consulting engagement someone asks for my opinion on the whole design for testability thing. I&#8217;m not quite sure why I haven&#8217;t blogged on this topic, especially at the time that a lot of the other bloggers were weighing in, but better late than never.
Before getting into that, I [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.udidahan.com/wp-content/uploads/elephant_balance.png" style="float:right; margin-left:10px; margin-bottom:10px; " alt="keeping balance" title="keeping balance" width="204" height="203" />Almost at every conference, event, training, or consulting engagement someone asks for my opinion on the whole design for testability thing. I&#8217;m not quite sure why I haven&#8217;t blogged on this topic, especially at the time that a lot of the other bloggers were weighing in, but better late than never.</p>
<p>Before getting into that, I want to start with a slightly broader scope of discussion.</p>
<p>You see, I get asked about &#8220;best practices&#8221; on all sorts of things. And I try not to be the kind of consultant that responds with &#8220;it depends&#8221;, but the context of the question often makes the answer irrelevant. And the unspoken context of a best-practice question is:</p>
<h2>Given infinite time and budget</h2>
<p>The biggest problem that I see with well-intentioned, best-practices-following developers and architects is that they <b>don&#8217;t</b> ask the question &#8220;is this the right thing for us to be focusing on right now?&#8221; Understandably, that is a difficult question to answer &#8211; but it needs to be asked, since you don&#8217;t have infinite time or budget to do everything according to best practices (assuming those even exist).</p>
<h2>About testing</h2>
<p>The biggest issue I have with the &#8220;design for testability&#8221; topic is the extremely narrow view it takes of the word &#8220;testability&#8221;, usually in the form of more code written by a developer which invokes the production code of the system, also known as &#8220;unit tests&#8221;.</p>
<p>There are many different kinds of testing &#8211; unit, integration, functional, load, performance, exploratory, etc&#8230; where some may be automated and others not. Should we not discuss what &#8220;design for testability&#8221; means for not-just-unit-testing?</p>
<h2>And what&#8217;s the point of testing anyway?</h2>
<p>It&#8217;s not to find bugs.</p>
<p>Research has shown that testing (of all kinds) is not the most effective way of finding bugs. I don&#8217;t have the reference handy but I&#8217;m pretty sure that it&#8217;s from <a href="http://alistair.cockburn.us/">Alistair Cockburn&#8217;s work</a>. Code reviews are (on average) about 60% more effective.</p>
<p>Don&#8217;t get me wrong &#8211; testing can provide indications that the software <b>has</b> bugs in it, but not necessarily where in the code those bugs are.</p>
<p>The purpose of testing is to provide quantitative and qualitative information about the system that can help various stakeholders in their decision-making processes. The relevance of that information indicates the quality of the testing. Here are some examples:</p>
<ul>
<li>The system supports 100 concurrent users, with the expected user-type distribution (X% role A, Y% role B, etc), performing expected use-case distributions, and collaboration scenarios.</li>
<li>Time to proficiency for new users in role A is expected to be 3 days</li>
<li>Alternate #2 of use case #12 fails on step #3</li>
</ul>
<p>As you can see, the relevance of the above information is dependent on what decisions the various stakeholders need to make. The bullet on load can help us decide if more machines are needed or if developers need to tune the performance of the systems. The bullet on time to proficiency can help us decide if larger investment in usability is required. Information like the last bullet can be used in conjunction with the first two to decide on the timing and type of a release.</p>
<p>The timeliness of this relevant information is critical to the success of a project.</p>
<p>Choosing which and how much of the various testing activities to perform when is something that needs to be revisited several times throughout the lifetime of a project, taking into account the current risks (threats and probabilities) and time and resource investment to mitigate them.</p>
<p>Let me reiterate &#8211; we&#8217;re not going to have enough time to do everything.</p>
<h2>On iterations</h2>
<p>If the only part of your organization that is doing iterations are your developers, you&#8217;re not agile.</p>
<p>In order to capitalize on the information that testers are providing, you need them in your iterations.</p>
<p>The same goes for the other roles involved in the project &#8211; business analysts, DBAs, sysadmins, etc.</p>
<p>I know that 99% of organizations aren&#8217;t structured in a way to do this.</p>
<p>I never said doing this would be easy.</p>
<h2>On design</h2>
<p>Figuring out what kind of design and how much to do when is just as important, and just as hard. Design for testability is one part of that, but not the only one, or necessarily the most important one at any point of time.</p>
<p>Within that design for testability topic is the &#8220;design for unit-testing&#8221; sub-topic which seems to be the popular one. Before getting into the design aspects of it, let&#8217;s take a closer look at the unit-testing side of things.</p>
<h2>On unit-testing</h2>
<p>The assumption is that having more unit tests will lead to a code-base with less bugs, thus requiring shorter time to get the system into production, which will pay back the time it took to write those unit tests to begin with.</p>
<p>In practice, what tends to happen is that as development progresses, testing code breaks as the structure of the production code changes. Now one of two things happens &#8211; either the testing code is removed or rewritten. In either case, we didn&#8217;t get the return on investment we expected on the first bit of testing code. Unfortunately, rare is the case where the relevant people in the organization understand <b>why</b>, resulting in the same situation repeating itself over and over again.</p>
<p>Those projects would have been better off without unit testing, though the organization as a whole might have used those experiences to learn and improve. It&#8217;s been my experience that if the organization wasn&#8217;t conscious enough in the context of the project to notice the situation, it is unlikely to do so at higher levels.</p>
<h2>On fragile unit tests</h2>
<p>The reason that a unit test ends up being rewritten (or removed) is that its code was coupled to the production code in such a way that it broke when the production code changed. This tendency to break (fragility) is a critical property of a unit test. A fragile unit test will slow down a developer doing work on some existing code &#8211; it actually makes the system less maintainable.</p>
<p>For a unit test code to be stable (not fragile) it needs to be coupled to stable properties of the production code. The question of whether the production code is designed in such a way that it has stable properties &#8211; is a design question. Is it a <b>unit</b>? If not, you will <b>not</b> be able to write a unit-test against it.</p>
<p>And anyway, who said that every class is a unit, or should be a unit? Domain models (when done right) are good examples of a unit, yet the classes that make them up may not be units. Unit-testing should only be attempted with things which are units. </p>
<p>I think too much weight is put on whether a dependency of a class is a concrete or interface type, and not nearly enough on the nature of the dependency. I wouldn&#8217;t blame the hammer for pounding my thumb, and by the same token I think that blame should not be directed towards tools like those from TypeMock.</p>
<h2>On tools</h2>
<p>There is so much more depth to both design and testability that needs to be more broadly understood. No tool has yet been created to handle either design or testing in such a way that humans can give up responsibility for the outcome. </p>
<p>Over the years I&#8217;ve noticed that tools are most significant when used by skilled practitioners, which makes sense in retrospect. Giving a novice carpenter a laser-guided saw probably won&#8217;t significantly change the outcome of their work. Ultimately, the skilled practitioners are the ones that create tools &#8211; not the novices. And no tool, no matter how advanced, will make a novice perform at levels like the skilled practitioner.</p>
<p>In the case of a project too big for a single skilled practitioner to complete in the time required (or at all), the balance of importance shifts away from tools to the project management topics described above.</p>
<h2>In summary</h2>
<p>I hope that this post has shed some light on the context in which decisions with respect to testing need to be made. Design is one activity that can support certain kinds of testing, but not the only one, or even the most important one for the given type of testing necessary at that time in the project.</p>
<p>Design is hard. Project management is hard. Testing is hard.</p>
<p>Getting the right mix of people that together have enough experience and skills in these activities isn&#8217;t easy.</p>
<p>Don&#8217;t expect that sprinkling some interfaces in your code base will be enough.<br />
That doesn&#8217;t count much in the way of design, just as writing code in a testing namespace doesn&#8217;t count much in the way of testability.</p>
<p>Looking forward to hearing your comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2010/04/18/on-design-for-testability/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>Convention over Configuration &#8211; The Next Generation?</title>
		<link>http://www.udidahan.com/2009/08/15/convention-over-configuration-the-next-generation/</link>
		<comments>http://www.udidahan.com/2009/08/15/convention-over-configuration-the-next-generation/#comments</comments>
		<pubDate>Sat, 15 Aug 2009 18:13:24 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[NServiceBus]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://www.udidahan.com/?p=1081</guid>
		<description><![CDATA[
Convention over configuration describes a style of development made popular by Ruby on Rails which has gained a great deal of traction in the .net ecosystem. After using frameworks designed in this way, I can say that the popularity is justified &#8211; it is much more pleasurable developing this way. 
The thing is, when looking [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.udidahan.com/wp-content/uploads/PicardKirk.jpg" alt="PicardKirk" title="PicardKirk" width="160" height="103" style="float:right; margin-left:10px; margin-bottom:10px; " /><br />
Convention over configuration describes a style of development made popular by Ruby on Rails which has gained a great deal of traction in the .net ecosystem. After using frameworks designed in this way, I can say that the popularity is justified &#8211; it is much more pleasurable developing this way. </p>
<p>The thing is, when looking at this in light of the full software development lifecycle, there are signs that the waters run deeper than we might have originally thought.</p>
<p>Let&#8217;s take things one step at a time though&#8230;</p>
<h3>What is it?</h3>
<p><a href="http://en.wikipedia.org/wiki/Convention_over_configuration">Wikipedia tells us</a>:</p>
<blockquote><p>&#8220;Convention over Configuration (aka Coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application.&#8221;</p></blockquote>
<p>What this means is that frameworks built in this way have default implementations that can be swapped out if needed. So far so good.</p>
<h3>For example&#8230;</h3>
<p>In <a href="http://www.NServiceBus.com">NServiceBus</a>, there is an abstraction for how subscription data is stored and multiple implementations &#8211; one in-memory, another using a durable MSMQ queue, and a third which uses a database. The convention for that part of the system is that the MSMQ implementation will be used, unless something else is specified. </p>
<p>Developers wishing to specify a different implementation can specify the desired implementation in the container &#8211; either one that comes out of the box, or their own implementation of ISubscriptionStorage.</p>
<p>Things get more interesting when we consider the full lifecycle.</p>
<h3>Lifecycle effects</h3>
<p>When developers are in the early phases of writing a new service, they want to focus primarily on what the service does &#8211; its logic. They don&#8217;t want to muck around with MSMQ queues for storing subscriptions and would much rather use the in-memory storage. </p>
<p>As the service takes shape and the developers want to run the full service on their machine, possibly testing basic fault-tolerance behaviors &#8211; kill one service, see that the others get a timeout, bring the service back up, wanting it to maintain all the previous subscriptions.</p>
<p>Moving on from there, our developers want to take the same system they just tested on their machine and move it into a staging environment. There, they don&#8217;t want to use the MSMQ implementation for subscription storage, but rather the database implementation &#8211; as will be used in the production environment. </p>
<p>While it may not sound like a big deal &#8211; changing the code which specifies which implementation to use when moving from one environment to another, consider that on top of just subscription storage, there is logging (output to console, file, db?), saga persistence (in-memory, file-based DB, relational DB), and more.</p>
<p>It&#8217;s actually quite likely that something will get missed as we move the system between environments. Can there be a better way?</p>
<h3>What if&#8230;</h3>
<p>What if there was some way for the developer to express their intent to the system, and the system could change its conventions, without the developer having to change any code or configuration files?</p>
<p>You might compare this (in concept) to debug builds and release builds. Same code, same config, but the runtime behaves different between the two.</p>
<p>As I mulled over how we could capture that intent without any code or config changes, the solution that I kept coming to seemed too trivial at first, so I dismissed it. Yet, it was the simplest one that would work for console and WinForms applications, as well as windows services &#8211; command line arguments. The only thing is that I don&#8217;t think those are available for web applications.</p>
<p>But since we&#8217;re still in &#8220;what if&#8221; land, and I&#8217;m more thinking out loud here than providing workable solutions for tomorrow morning, let&#8217;s &#8220;what if&#8221; command line arguments worked for web apps too.</p>
<h3>Command-Line Intent</h3>
<p>Going back to our original scenario, when developers are working on the logic of the service, they run it using the generic NServiceBus host process, passing it the command line parameter /lite (or whatever). The host then automatically configures all the in-memory implementations. </p>
<p>As the system progresses, when the developer wants to run everything on their machine, they run the processes with /integration. The host then configures the appropriate implementations (MSMQ for subscription storage, SQLite for saga persistence, etc. </p>
<p>When the developers want to run the system in production, they could specify /production (or maybe that could be the default?), and the database backed implementations would be configured.</p>
<h3>Imagine&#8230;</h3>
<p>Imagine being able to move that fluidly from one environment to another. Not needing to pore over configuration files or startup script code which configures a zillion implementation details. Not needing to worry that as you moved the system to staging something would break.</p>
<p>Imagine short, frictionless iterations even for large scale systems.</p>
<p>Imagine &#8211; lifecycle-aware frameworks making all this imagination a reality.</p>
<h3>In Closing</h3>
<p>We&#8217;re not there yet &#8211; but we&#8217;re not that far either. The generic host we&#8217;re providing with NServiceBus 2.0 is now being extended to support exactly these scenarios. </p>
<p>It&#8217;s my hope that as more of us think about this challenge, we&#8217;ll come up with better solutions and more intelligent frameworks. Just as convention came to our rescue before, breaking us out of the pain of endless XML configuration, I hope this new family of lifecycle-aware frameworks will make the friction of moving a system through dev, test, staging, and production a thing of the past.</p>
<p>A worthy problem for us all to solve, don&#8217;t you think?</p>
<p>Any ideas on how to make it a reality?<br />
Send them in &#8211; leave a comment below.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2009/08/15/convention-over-configuration-the-next-generation/feed/</wfw:commentRss>
		<slash:comments>29</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>Unit Testing for Developers and Managers</title>
		<link>http://www.udidahan.com/2008/09/30/unit-testing-for-developers-and-managers/</link>
		<comments>http://www.udidahan.com/2008/09/30/unit-testing-for-developers-and-managers/#comments</comments>
		<pubDate>Tue, 30 Sep 2008 21:03:10 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Management]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[The Team]]></category>

		<guid isPermaLink="false">http://www.udidahan.com/2008/09/30/unit-testing-for-developers-and-managers/</guid>
		<description><![CDATA[ &#8220;We need to rewrite the system.&#8221;
Thus begins the story of yet another developer trying to convince their manager to adopt test-driven development (or any other methodology or technology). There&#8217;s a good chance this developer&#8217;s been reading all sorts of stuff on blogs (like those linked here) that have convinced him that salvation lies that [...]]]></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="240" alt="image" src="http://www.udidahan.com/wp-content/uploads/image44.png" width="178" align="right" border="0"> &#8220;We need to rewrite the system.&#8221;</p>
<p>Thus begins the story of yet another developer trying to convince their manager to adopt test-driven development (or any other methodology or technology). There&#8217;s a good chance this developer&#8217;s been reading all sorts of stuff on blogs (like those linked <a href="http://weblogs.asp.net/rosherove/archive/2008/09/26/unit-testing-decoupled-from-design-adoption.aspx">here</a>) that have convinced him that salvation lies that way.</p>
<p>Don&#8217;t get me wrong. </p>
<p>There&#8217;s a good chance the developer&#8217;s right. </p>
<p>It&#8217;s just that that&#8217;s besides the point.</p>
<h3>Developers and Managers</h3>
<p>There&#8217;s a difference between how developers view a practice and how a manager (defined for the purposes of this post as someone in charge of delivering something) view that same practice. From a developer perspective, <a href="http://codebetter.com/blogs/ian_cooper/archive/2008/09/23/learning-and-crafstmanship.aspx">Ian&#8217;s point</a> about unit testing is spot on:</p>
<blockquote><p>&#8220;The problem is that the most important step is not doing it right, but doing it at all.&#8221;</p>
</blockquote>
<p>Yet, as Ian himself points out in the title, this is a learning issue. If you want to learn to swim, there&#8217;s no replacement for jumping in the pool. </p>
<p>The manager&#8217;s perspective is a bit different.</p>
<p>Yes, we want our developers to improve their skill set. Yes, we understand that unit testing will <em>ultimately</em> improve quality. Yes, we know developers need to practice these skills as a part of their job. But, and it&#8217;s a big ole&#8217; but, when it comes time to sink or swim, and we&#8217;ve got a deadline, those desires need to be balanced with delivering. <a href="http://weblogs.asp.net/rosherove/archive/2008/09/20/goodbye-mocks-farewell-stubs.aspx">Accounts</a> of unit testing adoption efforts resulting in more (test) code to support with little apparent improvement in quality in the short term, well, they scare us. <a href="http://www.rgoarchitects.com/nblog/2008/09/21/WhatsUpWithUnitTestingPartI.aspx">Arnon&#8217;s post</a> gives more links supporting that feeling.</p>
<h3>What&#8217;s a Unit Test anyway?</h3>
<p>Is it any class that happens to have a TestFixture attribute on it?</p>
<p>If we are to &#8220;decouple&#8221; unit testing from good design, as <a href="http://weblogs.asp.net/rosherove/archive/2008/09/26/unit-testing-decoupled-from-design-adoption.aspx">Roy has described</a>, that&#8217;s a not-improbable outcome. If the design of the system is such as there aren&#8217;t any real &#8220;units&#8221;, what exactly are we testing? Regardless of static or dynamic typing, replaceability of code, and other technological things, does the fact that all TestMethods in that TestFixture complete successfully mean anything? In other words, what did the test test?</p>
<p>It is clear that these tests <em>cost</em> something.</p>
<p>It&#8217;s more code to write. It&#8217;s more code to maintain.</p>
<p>The question is, what value are we getting from these &#8220;unit tests that any developer without design skills can write&#8221;?</p>
<p>The manager in me doesn&#8217;t like this return on investment.</p>
<blockquote><p>By the way, TDD is as much the evolution of unit testing as the screw driver is the evolution of the hammer. But that&#8217;ll have to wait for a different post.</p>
</blockquote>
<h3>What&#8217;s Design Got To Do With It?</h3>
<p>If you&#8217;re looking for the technical ability to write a test fixture and replace calls to other classes, then design has nothing to it.</p>
<p>If tests are to be valuable &#8211; design has everything to do with it.</p>
<p>The difficulty our developer is having unit-testing the system is a symptom of design problems. There&#8217;s a good chance that&#8217;s why he suggested a rewrite. </p>
<blockquote><p>By the way, please do a search &amp; replace in your vocabulary on the word &#8220;rewrite&#8221; with the word &#8220;redesign&#8221;. The code&#8217;s syntax isn&#8217;t the problem &#8211; it&#8217;s not the &#8220;m_&#8221;, camel case, or anything like that. It&#8217;s not that if the code was rewritten under the same design that all problems will go away.</p>
<p>Redesign, or do nothing.</p>
</blockquote>
<p>The community&#8217;s been discussing the issues of coupling, interfaces, mocking, and tools at length in the context of testability. I won&#8217;t reiterate the debate here but I&#8217;ll tell you this:</p>
<p>If logic is duplicated, if the code is tightly coupled, if there is no separation of concerns, the unit tests will be useless &#8211; even if they &#8220;test&#8221; the class in isolation.</p>
<h3>Cut the coverage crap</h3>
<p>Metrics lie.</p>
<p>The fact that there&#8217;s a bunch of other code which calls 100% of the system&#8217;s code and doesn&#8217;t contain false assertions doesn&#8217;t mean that the code is high quality or doesn&#8217;t contain bugs.</p>
<p>In a well designed system, most &#8220;logic&#8221; will be contained in two &#8220;layers&#8221; &#8211; the controllers and the domain model. These classes should be independent of any and all technological concerns. You can and should get high unit test coverage on classes in these layers. Shoot for 100%, it&#8217;s worth it.</p>
<blockquote><p>Testing domain models is all about asserting state. While using setters to get the domain objects into a necessary initial state is OK, setters should not be used beyond that. Testing controllers is primarily about interactions &#8211; mocks will probably be needed for views and service agents. Commands do not need to be mocked out.</p>
</blockquote>
<p>Most other layers have some dependence on technology that makes unit tests relatively less valuable. Coverage on these layers is most meaningless. My guidance is to take the effort that would have been spent on unit testing these other layers and invest it all in automated integration tests. You&#8217;re likely to get a much higher return on investment. Much higher.</p>
<p>Much.</p>
<h3>Everybody&#8217;s Right</h3>
<p>Developers aren&#8217;t just born knowing good design, testing, or anything else. Universities, colleges, and most vendors do little to change that state of affairs. Books help, a bit, but when learning to swim, you&#8217;ve got to get your feet wet, and on the job training is, by and large, all there is. As such, lowering the barrier to entry is important. </p>
<p>Keeping in mind the <a href="http://w3.msi.vxu.se/~per/CP-web/PBDDSKIL.HTM">Dreyfus model of knowledge acquisition</a>, it&#8217;s not about &#8220;<a href="http://ayende.com/Blog/archive/2008/09/23/cuddling-is-consider-harmful.aspx">dumbing down</a>&#8221; software development, it&#8217;s about bringing novices up to speed:</p>
<blockquote><p>&#8220;In the beginning [novices] learn to recognize objective facts and features, relevant to the skill. Characteristic of relevant elements are that they can be recognized context-free, i.e. without reference to the overall situation. The novice acquire basic rules to follow, acting upon those facts and features. The rules are also context-free, i.e. no notice is taken to the surroundings. <strong>On account of this the novice feels very little responsibility for the result</strong>.&#8221; (emphasis mine)</p>
</blockquote>
<p>Managers <strong><em>are</em></strong> ultimately responsible for the result. </p>
<p>Managers shouldn&#8217;t necessarily sacrifice their projects on this altar of learning. Organizations need to find ways for developers to safely practice these techniques as a part of developing their &#8220;human resources&#8221;. First of all, this needs to be communicated to everyone &#8211; that the organization understands the importance of these techniques, the desires of developers to adopt them, and the projects that need to be delivered. </p>
<p>Some projects may be allocated additional non-functional requirements: the software will be developed test-first, there will be at least 80% unit test coverage, etc. It can make sense to have developers spend some time on these projects after finishing one more delivery focused project and before going onto another one. As more developers become proficient with unit testing and design, the delivery focused projects can start to benefit from these skills.</p>
<p>It&#8217;s a gradual process.</p>
<h2>The Important Bit</h2>
<p>No matter how you go about unit testing, do periodic test reviews.</p>
<p>Just like code reviews.</p>
<p>That&#8217;s it.</p>
<p>&nbsp;</p>
<hr size="1">
<h4>Related Posts</h4>
<blockquote><p><a href="http://www.udidahan.com/2008/02/04/sagas-and-unit-testing-business-process-verification-made-easy/">Business Process Verification</a></p>
<p><a href="http://www.udidahan.com/2007/04/16/self-documenting-test-driven-alien-artifacts/">Self documenting and Test-Driven Alien Artifacts</a></p>
<p><a href="http://www.udidahan.com/2006/06/16/soa-testing/">SOA Testing</a></p>
</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2008/09/30/unit-testing-for-developers-and-managers/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Make WCF and WF as Scalable and Robust as NServiceBus</title>
		<link>http://www.udidahan.com/2008/06/30/make-wcf-and-wf-as-scalable-and-robust-as-nservicebus/</link>
		<comments>http://www.udidahan.com/2008/06/30/make-wcf-and-wf-as-scalable-and-robust-as-nservicebus/#comments</comments>
		<pubDate>Mon, 30 Jun 2008 14:47:08 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[NServiceBus]]></category>
		<category><![CDATA[Reliability]]></category>
		<category><![CDATA[Scalability]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[Workflow]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2008/06/30/make-wcf-and-wf-as-scalable-and-robust-as-nservicebus/</guid>
		<description><![CDATA[This topic is getting more play as more people are using WCF and WF in real-world scenarios, so I thought I&#8217;d pull the things that I&#8217;ve been watching in this space together:
Reliability 
Locking in SqlWorkflowPersistenceService (via Ron Jacobs) where, if you want predictable persistence (MS: &#8216;none of our customers asked for this to be easy&#8217;), [...]]]></description>
			<content:encoded><![CDATA[<p>This topic is getting more play as more people are using WCF and WF in real-world scenarios, so I thought I&#8217;d pull the things that I&#8217;ve been watching in this space together:</p>
<h3>Reliability<a href="http://udidahan.weblogs.us/wp-content/uploads/doctor1.png"><img style="border-right: 0px; border-top: 0px; margin: 0px 0px 10px 10px; border-left: 0px; border-bottom: 0px" height="244" alt="doctor" src="http://udidahan.weblogs.us/wp-content/uploads/doctor-thumb1.png" width="225" align="right" border="0"></a> </h3>
<p><a href="http://blogs.msdn.com/rjacobs/archive/2008/06/27/locking-in-sqlworkflowpersistenceservice.aspx">Locking in SqlWorkflowPersistenceService</a> (via Ron Jacobs) where, if you want predictable persistence (MS: &#8216;none of our customers asked for this to be easy&#8217;), you need to use a custom activity (which Ron was kind enough to supply).</p>
<blockquote><p>&#8220;Given what I learned today I&#8217;d have to say that I&#8217;d be very careful about using workflows with an optimistic locking.&nbsp; Detecting these types of situations is not that simple.&#8221;</p>
</blockquote>
<p>Let&#8217;s think about that. If we&#8217;re doing pessimistic locking, we get into the problem of, if a host restarts (as the result of a critical windows patch or some other unexpected occurrence), that the workflow won&#8217;t be able to be handled by any other host in the meantime (you didn&#8217;t care so much about your SLA, did you?).</p>
<p>Luckily, someone&#8217;s come up with a hack that works around this robustness problem in <a href="http://www.topxml.com/rbnews/Orchestration---Workflow/re-78382_Scaleable-Workflow-Persistence-and-Ownership.aspx">Scalable Workflow Persistence and Ownership</a>.</p>
<blockquote><p>&#8220;So this code will attempt to load workflow instances with expired locks every second. Is it a hack? Yes. But without one of two things in the SqlWorkflowPersistenceService its the sort of code you have to write to pick up unlocked workflow instances robustly.&#8221;</p>
</blockquote>
<p>This will seriously churn the table used to store your workflows, decreasing performance of workflows that haven&#8217;t timed out. Oh well.</p>
<h3>Testability</h3>
<p><a href="http://blogs.msdn.com/ploeh/archive/2008/06/26/implementing-wcf-services-without-referencing-wcf.aspx">Implementing WCF Services without Referencing WCF</a> (via Mark Seemann): </p>
<blockquote><p>&#8220;More than a year ago, I wrote my first post on <a href="http://blogs.msdn.com/ploeh/archive/2006/12/03/UnitTestingWCFServices.aspx">unit testing WCF services</a>. One of my points back then was that you have to be careful that the service implementation doesn&#8217;t use any of the services provided by the WCF runtime environment (if you want to keep the service testable). As soon as you invoke something like <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.operationcontext.current.aspx">OperationContext.Current</a>, your code is not going to work in a unit testing scenario, but only when hosted by WCF.&#8221;</p>
</blockquote>
<p>After pointing out some of the more basic difficulties in testability a straightforward WCF implementation brings, Mark turns the heat up in his follow-up post, <a href="http://blogs.msdn.com/ploeh/archive/2008/06/27/modifying-behavior-of-wcf-free-service-implementations.aspx">Modifying Behavior of WCF-Free Service Implementations</a>:</p>
<blockquote><p>&#8220;Perhaps you need to control the service&#8217;s <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.servicebehaviorattribute.concurrencymode.aspx">ConcurrencyMode</a>, or perhaps you need to set <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.servicebehaviorattribute.usesynchronizationcontext.aspx">UseSynchronizationContext</a>. These options are typically controlled by the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.servicebehaviorattribute.aspx">ServiceBehaviorAttribute</a>. You may also want to provide an <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iinstanceprovider.aspx">IInstanceProvider</a> via a custom attribute that implements <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.description.icontractbehavior.aspx">IContractBehavior</a>. However, you can&#8217;t set these attributes on the service implementation itself, since it mustn&#8217;t have a reference to System.ServiceModel.&#8221;</p>
</blockquote>
<p>Wow &#8211; all the things required to make a WCF service scalable and thread-safe make it difficult to test. In the end, we&#8217;re beginning to see how many hoops we have to go through in order to get separation of concerns, but until we can take all this and get it out of our application code, it&#8217;s an untenable solution. I hope Mark will continue with this series, if only so I can take the framework that might grow out of it and use it as a generic WCF transport for NServiceBus.</p>
<h3>Comparison<a href="http://udidahan.weblogs.us/wp-content/uploads/apples-and-oranges.jpg"><img style="border-right: 0px; border-top: 0px; margin: 0px 0px 10px 10px; border-left: 0px; border-bottom: 0px" height="244" alt="apples and oranges" src="http://udidahan.weblogs.us/wp-content/uploads/apples-and-oranges-thumb.jpg" width="184" align="right" border="0"></a> </h3>
<p>After the <a href="http://samgentile.com/blogs/samgentile/archive/2008/05/21/response-to-nservicebus-performance.aspx">Neuron-NServiceBus comparison</a> that Sam and I had, we talked some more. After going through some of the rational and thinking, Sam even <a href="http://samgentile.com/blogs/samgentile/archive/2008/06/24/looking-at-nservicebus-added-to-tonight-s-presentation.aspx">put nServiceBus into his WCF-Neuron comparison talk</a>. Sam had this to say about nServiceBus:</p>
<blockquote><p>&#8220;The bottom line is: I like what I see. Although it&#8217;s a framework, not an ESB product like Neuron, it&#8217;s a powerful framework that takes the right approach on SOA and enforces a paradigm of reliable one-way, *non-blocking* calls. That is the point of the talk tonight overall; we need to get away from the stack world of synchronous RPC calls to true asynchronous non-blocking message based SOA systems.&#8221;</p>
</blockquote>
<p>The main concern I have with a WCF+WF based solution is that developers need to know a lot in order to make it testable, scalable, and robust. In nServiceBus, that&#8217;s baked into the design. It would be extremely difficult for a developer writing application logic to interfere with when persistence needs to happen, or the concurrency strategy of long-running workflows. The fact that message handlers in the service layer don&#8217;t need concurrency modes, instance providers, or any of that junk make them testable by default.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2008/06/30/make-wcf-and-wf-as-scalable-and-robust-as-nservicebus/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sagas and Unit Testing &#8211; Business Process Verification Made Easy</title>
		<link>http://www.udidahan.com/2008/02/04/sagas-and-unit-testing-business-process-verification-made-easy/</link>
		<comments>http://www.udidahan.com/2008/02/04/sagas-and-unit-testing-business-process-verification-made-easy/#comments</comments>
		<pubDate>Mon, 04 Feb 2008 13:09:51 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Autonomous Services]]></category>
		<category><![CDATA[Business Rules]]></category>
		<category><![CDATA[EDA]]></category>
		<category><![CDATA[ESB]]></category>
		<category><![CDATA[NServiceBus]]></category>
		<category><![CDATA[Pub/Sub]]></category>
		<category><![CDATA[SOA]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Workflow]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2008/02/04/sagas-and-unit-testing-business-process-verification-made-easy/</guid>
		<description><![CDATA[Sagas have always been designed with unit testing in mind. By keeping them disconnected from any communications or persistence technology, it was my belief that it should be fairly easy to use mock objects to test them. I&#8217;ve heard back from projects using nServiceBus this way that they were pleased with their ability to test [...]]]></description>
			<content:encoded><![CDATA[<p>Sagas have always been designed with unit testing in mind. By keeping them disconnected from any communications or persistence technology, it was my belief that it should be fairly easy to use mock objects to test them. I&#8217;ve heard back from projects using nServiceBus this way that they were pleased with their ability to test them, and thought all was well.</p>
<p>Not so.</p>
<p>The other day I sat down to implement and test a non-trivial business process, and the testing was far from easy. Now as developers go, I&#8217;m not great, or an expert on unit testing or TDD, but I&#8217;m above average. It should not have been this hard. And I tried doing it with <a href="http://www.ayende.com/projects/rhino-mocks.aspx">Rhino.Mocks</a>, <a href="http://www.typemock.com/">TypeMock</a>, and finally <a href="http://code.google.com/p/moq/">Moq</a>. It seemed like I was in a no-mans-land, between trying to do state-based testing, and setting expectations on the messages being sent (as well as correct values in those messages), nothing flowed.</p>
<p>Until I finally stopped trying to figure out how to test, and focused on what needed to be tested. I mean, it&#8217;s not like I was trying to build a generic mocking framework like <a href="http://feeds.feedburner.com/~r/DanielCazzulino/~3/228130195/NewMoqfeaturesformockverificationandcreation.aspx">Daniel</a>.</p>
<p>Here&#8217;s an example business process, or actually, part of one, and then we&#8217;ll see how that can be tested. By the way, there will be a post coming soon which describes how we go about analysing a system, coming up with these message types, and how these sagas come into being, so stay tuned. Either that, or just come to <a href="http://qcon.infoq.com/london/presentation/Build+Scalable%2C+Maintainable%2C+Distributed+Enterprise+.NET+Solutions+with+nServiceBus">my tutorial at QCon.</a></p>
<p>On with the process:</p>
<blockquote><p>1. When we receive a CreateOrderMessage, whose “Completed” flag is true, we’ll send 2 AuthorizationRequestMessages to internal systems (for managers to authorize the order), one OrderStatusUpdatedMessage to the caller with a status “Received”, and a TimeoutMessage to the TimeoutManager requesting to be notified – so that the process doesn’t get stuck if one or both messages don’t get a response.</p>
<p>2. When we receive the first AuthorizationResponseMessage, we notify the initiator of the Order by sending them a OrderStatusUpdatedMessage with a status “Authorized1”.</p>
<p>3. When we get “timed out” from the TimeoutManager, we check if at least one AuthorizationResponseMessage has arrived, and if so, publish an OrderAcceptedMessage, and notify the initator (again via the OrderStatusUpdatedMessage) this time with a status of “Accepted”.</p></blockquote>
<p>And here&#8217;s the test:</p>
<div style="overflow: scroll; width: 95%"><!-- 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;*/  }  .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt   {  	background-color: #f4f4f4;  	width: 100%;  	margin: 0em;  } .csharpcode .lnum { color: #606060; }</style>
<pre class="csharpcode">    <span class="kwrd">public</span> <span class="kwrd">class</span> OrderSagaTests
    {
        <span class="kwrd">private</span> OrderSaga orderSaga = <span class="kwrd">null</span>;
        <span class="kwrd">private</span> <span class="kwrd">string</span> timeoutAddress;
        <span class="kwrd">private</span> Saga Saga;     

        [SetUp]
        <span class="kwrd">public</span> <span class="kwrd">void</span> Setup()
        {
            timeoutAddress = <span class="str">"timeout"</span>;
            Saga = Saga.Test(<span class="kwrd">out</span> orderSaga, timeoutAddress);
        }     

        [Test]
        <span class="kwrd">public</span> <span class="kwrd">void</span> OrderProcessingShouldCompleteAfterOneAuthorizationAndOneTimeout()
        {
            Guid externalOrderId = Guid.NewGuid();
            Guid customerId = Guid.NewGuid();
            <span class="kwrd">string</span> clientAddress = <span class="str">"client"</span>;     

            CreateOrderMessage createOrderMsg = <span class="kwrd">new</span> CreateOrderMessage();
            createOrderMsg.OrderId = externalOrderId;
            createOrderMsg.CustomerId = customerId;
            createOrderMsg.Products = <span class="kwrd">new</span> List&lt;Guid&gt;(<span class="kwrd">new</span> Guid[] { Guid.NewGuid() });
            createOrderMsg.Amounts = <span class="kwrd">new</span> List&lt;<span class="kwrd">float</span>&gt;(<span class="kwrd">new</span> <span class="kwrd">float</span>[] { 10.0F });
            createOrderMsg.Completed = <span class="kwrd">true</span>;     

            TimeoutMessage timeoutMessage = <span class="kwrd">null</span>;     

            Saga.WhenReceivesMessageFrom(clientAddress)
                .ExpectSend&lt;AuthorizeOrderRequestMessage&gt;(
                    <span class="kwrd">delegate</span>(AuthorizeOrderRequestMessage m)
                    {
                        <span class="kwrd">return</span> m.SagaId == orderSaga.Id;
                    })
                .ExpectSend&lt;AuthorizeOrderRequestMessage&gt;(
                    <span class="kwrd">delegate</span>(AuthorizeOrderRequestMessage m)
                    {
                        <span class="kwrd">return</span> m.SagaId == orderSaga.Id;
                    })
                .ExpectSendToDestination&lt;OrderStatusUpdatedMessage&gt;(
                    <span class="kwrd">delegate</span>(<span class="kwrd">string</span> destination, OrderStatusUpdatedMessage m)
                    {
                        <span class="kwrd">return</span> m.OrderId == externalOrderId &amp;&amp; destination == clientAddress;
                    })
                .ExpectSendToDestination&lt;TimeoutMessage&gt;(
                    <span class="kwrd">delegate</span>(<span class="kwrd">string</span> destination, TimeoutMessage m)
                    {
                        timeoutMessage = m;
                        <span class="kwrd">return</span> m.SagaId == orderSaga.Id &amp;&amp; destination == timeoutAddress;
                    })
                .When(<span class="kwrd">delegate</span> { orderSaga.Handle(createOrderMsg); });     

            Assert.IsFalse(orderSaga.Completed);     

            AuthorizeOrderResponseMessage response = <span class="kwrd">new</span> AuthorizeOrderResponseMessage();
            response.ManagerId = Guid.NewGuid();
            response.Authorized = <span class="kwrd">true</span>;
            response.SagaId = orderSaga.Id;     

            Saga.ExpectSendToDestination&lt;OrderStatusUpdatedMessage&gt;(
                    <span class="kwrd">delegate</span>(<span class="kwrd">string</span> destination, OrderStatusUpdatedMessage m)
                    {
                        <span class="kwrd">return</span> (destination == clientAddress &amp;&amp;
                                m.OrderId == externalOrderId &amp;&amp;
                                m.Status == OrderStatus.Authorized1);
                    })
                .When(<span class="kwrd">delegate</span> { orderSaga.Handle(response); });     

            Assert.IsFalse(orderSaga.Completed);     

            Saga.ExpectSendToDestination&lt;OrderStatusUpdatedMessage&gt;(
                    <span class="kwrd">delegate</span>(<span class="kwrd">string</span> destination, OrderStatusUpdatedMessage m)
                    {
                        <span class="kwrd">return</span> (destination == clientAddress &amp;&amp;
                                m.OrderId == externalOrderId &amp;&amp;
                                m.Status == OrderStatus.Accepted);
                    })
                .ExpectPublish&lt;OrderAcceptedMessage&gt;(
                    <span class="kwrd">delegate</span>(OrderAcceptedMessage m)
                    {
                        <span class="kwrd">return</span> (m.CustomerId == customerId);
                    })
                .When(<span class="kwrd">delegate</span> { orderSaga.Timeout(timeoutMessage.State); });     

            Assert.IsTrue(orderSaga.Completed);
        }
    }</pre>
</div>
<p>You might notice that this style is a bit similar to the fluent testing found in Rhino Mocks. That&#8217;s not coincidence. It actually makes use of Rhino Mocks internally. The thing that I discovered was that in order to test these sagas, you don&#8217;t need to actually see a mocking framework. All you should have to do is express how messages get sent, and under what criteria those messages are valid.</p>
<p>If you&#8217;re wondering what the OrderSaga looks like, you can find the code right here. It&#8217;s not a complete business process implementation, but its enough to understand how one would look like:</p>
<div style="overflow: scroll; width: 95%"><!-- 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;*/  }  .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt   {  	background-color: #f4f4f4;  	width: 100%;  	margin: 0em;  } .csharpcode .lnum { color: #606060; }</style>
<pre class="csharpcode"><span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Collections.Generic;
<span class="kwrd">using</span> ExternalOrderMessages;
<span class="kwrd">using</span> NServiceBus.Saga;
<span class="kwrd">using</span> NServiceBus;
<span class="kwrd">using</span> InternalOrderMessages;     

<span class="kwrd">namespace</span> ProcessingLogic
{
    [Serializable]
    <span class="kwrd">public</span> <span class="kwrd">class</span> OrderSaga : ISaga&lt;CreateOrderMessage&gt;,
        ISaga&lt;AuthorizeOrderResponseMessage&gt;,
        ISaga&lt;CancelOrderMessage&gt;
    {
        <span class="preproc">#region</span> config info     

        [NonSerialized]
        <span class="kwrd">private</span> IBus bus;
        <span class="kwrd">public</span> IBus Bus
        {
            set { <span class="kwrd">this</span>.bus = <span class="kwrd">value</span>; }
        }     

        [NonSerialized]
        <span class="kwrd">private</span> Reminder reminder;
        <span class="kwrd">public</span> Reminder Reminder
        {
            set { <span class="kwrd">this</span>.reminder = <span class="kwrd">value</span>; }
        }     

        <span class="preproc">#endregion</span>     

        <span class="kwrd">private</span> Guid id;
        <span class="kwrd">private</span> <span class="kwrd">bool</span> completed;
        <span class="kwrd">public</span> <span class="kwrd">string</span> clientAddress;
        <span class="kwrd">public</span> Guid externalOrderId;
        <span class="kwrd">public</span> <span class="kwrd">int</span> numberOfPendingAuthorizations = 2;
        <span class="kwrd">public</span> List&lt;CreateOrderMessage&gt; orderItems = <span class="kwrd">new</span> List&lt;CreateOrderMessage&gt;();     

        <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(CreateOrderMessage message)
        {
            <span class="kwrd">this</span>.clientAddress = <span class="kwrd">this</span>.bus.SourceOfMessageBeingHandled;
            <span class="kwrd">this</span>.externalOrderId = message.OrderId;     

            <span class="kwrd">this</span>.orderItems.Add(message);     

            <span class="kwrd">if</span> (message.Completed)
            {
                <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; <span class="kwrd">this</span>.numberOfPendingAuthorizations; i++)
                {
                    AuthorizeOrderRequestMessage req = <span class="kwrd">new</span> AuthorizeOrderRequestMessage();
                    req.SagaId = <span class="kwrd">this</span>.id;
                    req.OrderData = orderItems;     

                    <span class="kwrd">this</span>.bus.Send(req);
                }
            }     

            <span class="kwrd">this</span>.SendUpdate(OrderStatus.Recieved);     

            <span class="kwrd">this</span>.reminder.ExpireIn(message.ProvideBy - DateTime.Now, <span class="kwrd">this</span>, <span class="kwrd">null</span>);
        }     

        <span class="kwrd">public</span> <span class="kwrd">void</span> Timeout(<span class="kwrd">object</span> state)
        {
            <span class="kwrd">if</span> (<span class="kwrd">this</span>.numberOfPendingAuthorizations &lt;= 1)
                <span class="kwrd">this</span>.Complete();
        }     

        <span class="kwrd">public</span> Guid Id
        {
            get { <span class="kwrd">return</span> id; }
            set { id = <span class="kwrd">value</span>; }
        }     

        <span class="kwrd">public</span> <span class="kwrd">bool</span> Completed
        {
            get { <span class="kwrd">return</span> completed; }
        }     

        <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(AuthorizeOrderResponseMessage message)
        {
            <span class="kwrd">if</span> (message.Authorized)
            {
                <span class="kwrd">this</span>.numberOfPendingAuthorizations--;     

                <span class="kwrd">if</span> (<span class="kwrd">this</span>.numberOfPendingAuthorizations == 1)
                    <span class="kwrd">this</span>.SendUpdate(OrderStatus.Authorized1);
                <span class="kwrd">else</span>
                {
                    <span class="kwrd">this</span>.SendUpdate(OrderStatus.Authorized2);
                    <span class="kwrd">this</span>.Complete();
                }
            }
            <span class="kwrd">else</span>
            {
                <span class="kwrd">this</span>.SendUpdate(OrderStatus.Rejected);
                <span class="kwrd">this</span>.Complete();
            }
        }     

        <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(CancelOrderMessage message)
        {     

        }     

        <span class="kwrd">private</span> <span class="kwrd">void</span> SendUpdate(OrderStatus status)
        {
            OrderStatusUpdatedMessage update = <span class="kwrd">new</span> OrderStatusUpdatedMessage();
            update.OrderId = <span class="kwrd">this</span>.externalOrderId;
            update.Status = status;     

            <span class="kwrd">this</span>.bus.Send(<span class="kwrd">this</span>.clientAddress, update);
        }     

        <span class="kwrd">private</span> <span class="kwrd">void</span> Complete()
        {
            <span class="kwrd">this</span>.completed = <span class="kwrd">true</span>;     

            <span class="kwrd">this</span>.SendUpdate(OrderStatus.Accepted);     

            OrderAcceptedMessage accepted = <span class="kwrd">new</span> OrderAcceptedMessage();
            accepted.Products = <span class="kwrd">new</span> List&lt;Guid&gt;(<span class="kwrd">this</span>.orderItems.Count);
            accepted.Amounts = <span class="kwrd">new</span> List&lt;<span class="kwrd">float</span>&gt;(<span class="kwrd">this</span>.orderItems.Count);     

            <span class="kwrd">this</span>.orderItems.ForEach(<span class="kwrd">delegate</span>(CreateOrderMessage m)
                                        {
                                            accepted.Products.AddRange(m.Products);
                                            accepted.Amounts.AddRange(m.Amounts);
                                            accepted.CustomerId = m.CustomerId;
                                        });     

            <span class="kwrd">this</span>.bus.Publish(accepted);
        }
    }
}</pre>
</div>
<p>All this code is online in the subversion repository under /Samples/Saga.</p>
<p>Questions, comments, and general thoughts are always appreciated.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2008/02/04/sagas-and-unit-testing-business-process-verification-made-easy/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Estimate Individually &#8211; Fail Globally?</title>
		<link>http://www.udidahan.com/2007/09/01/estimate-individually-fail-globally/</link>
		<comments>http://www.udidahan.com/2007/09/01/estimate-individually-fail-globally/#comments</comments>
		<pubDate>Sat, 01 Sep 2007 18:53:31 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Management]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[The Team]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/09/01/estimate-individually-fail-globally/</guid>
		<description><![CDATA[After reading Derek Hatchard&#8217;s post, The Art and War of Estimating and Scheduling Software, I wanted to follow up on my previous post on the topic, Don&#8217;t Trust Developers with Project Management. The problem lies with individualistic thinking.
Developers, and managers too for that matter, by and large are concerned with &#8220;productivity&#8221;. Developers want the latest [...]]]></description>
			<content:encoded><![CDATA[<p>After reading Derek Hatchard&#8217;s post, <a href="http://www.ardentdev.com/blog/index.php/2007/08/29/the-art-and-war-of-estimating-and-scheduling-software/">The Art and War of Estimating and Scheduling Software</a>, I wanted to follow up on my previous post on the topic, <a href="http://udidahan.weblogs.us/2007/08/06/dont-trust-developers-with-project-management/">Don&#8217;t Trust Developers with Project Management</a>. The problem lies with individualistic thinking.</p>
<p>Developers, and managers too for that matter, by and large are concerned with &#8220;productivity&#8221;. Developers want the latest tools and technologies so that they can churn out more code faster. Managers create schedules trying to get the maximum efficiency out of each one of their developers. They consider resource utilization and other terms that sound manager-ish.</p>
<p>Fact is, on medium to large sized projects, if you look at the studies you&#8217;ll find that developer productivity when measured as total lines of (non-blank) code of the system in production divided by the total number of developer days comes in roughly at 6. Maybe 7.</p>
<p>7 lines of code a day.</p>
<p>Let that sink in for a second.</p>
<p>I can hear the managers screaming already. OMFG, what were they doing all day long?! It takes, what, 10 minutes to put out 7 lines of code? An hour even, if it&#8217;s complicated recursive code and stuff. And they say they don&#8217;t like us micro-managing them?! Now we know why. It&#8217;s because they&#8217;re goofing off all day long.</p>
<p>Well, managers, that&#8217;s not really the way it goes. You see, you have to take into account the time it took to learn the technology, tools, frameworks, etc. Add to that the time of understanding the requirements, which is really sitting through boring meetings that don&#8217;t explain much. Finally, our poor developer actually gets to implement the requirement. Maybe run the system a couple of times, trying out the feature they implemented, and checking the code in.</p>
<p>Well, that&#8217;s actually the easy part. Now comes the part which kills most of the time. After a bunch of features have been developed by the team, the testers start banging away at it and find a bunch of bugs. Now the developer has to reverse-engineer some bizarre system behavior and figure out which part of the system is to blame. That involves usually some educated guessing (unless they&#8217;ve just joined the team and have been put in the bug-fixer role to &#8220;learn the system&#8221;, in which case it is thoroughly <B>UN</B>educated guessing). They change some code, run the system, which looks like its been fixed, check the new code in, and close the bug.</p>
<p>But the bugs keep coming. And as the project progresses towards production, more and more of the developers time is spent looking through code and changing existing code, that actually writing new code.</p>
<p>And the larger the system, the more bugs. And I don&#8217;t mean that the number of bugs linearly increases with lines of code, or number of features. It&#8217;s probably closer to exponential. If it&#8217;s a mission critical system, the performance bugs will be taking an order of magnitude more time to fix than other bugs.</p>
<p>So, as you can see, getting a system into production is a team effort. It includes the developers and testers, of course, but also management, and the customer, and how they manage scope. This is kind of a &#8220;duh&#8221; statement, but we&#8217;re getting to the punch-line.</p>
<p>If getting a system into production involves the entire team, isn&#8217;t that obviously true for each feature too?</p>
<p>In which case, why are we asking just the developers to estimate the time it takes to get a feature &#8220;done&#8221;? Why are we trying so hard to measure their productivity?</p>
<p>I know why. It&#8217;s so we can get rid of the less productive ones and give bonuses to the more productive ones!</p>
<p>Back to the main issue. I don&#8217;t &#8220;trust&#8221; developer estimates because I need to see the <i>team&#8217;s</i> capability to put features in production. The involves all aspects, and often many team members, in some cases multiple developers going through the same code. This involves all overhead and cross team communication, sick days, etc. It&#8217;s also why I try to get multiple data points over time to understand the team&#8217;s velocity.</p>
<p>While I care about the quality of my developers, and testers, and everybody on my team and would like them to be able to estimate their work as best they can, I&#8217;ve got a project to put into production. And the best way I&#8217;ll know when it&#8217;ll go into production is by having data that&#8217;ll enable me to state to my management:</p>
<p>&#8220;Our team is finishing 20 feature-units a month, we&#8217;ve got 200 feature-units to go, so we&#8217;ll be done in around 10 months.&#8221;</p>
<p>If I&#8217;m busy micro-measuring each developers estimates, I won&#8217;t have the time to see the forest. By first taking a harsh look at the reality of what the team can do, I can start looking for ways to make it better. Maybe the bottleneck is between analysts and developers, maybe we&#8217;re seeing the same bugs regressing many times, but until we know where we are, we can&#8217;t run controlled experiments to see what makes us better.</p>
<p>Focusing on the individual developer, getting them the latest and greatest tools may be great for their morale, but it probably won&#8217;t make a bit of difference to their actual productivity.</p>
<p>Next time &#8211; what to do when management asks you what it&#8217;ll take to be done sooner.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/09/01/estimate-individually-fail-globally/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Don&#8217;t trust developers with project management</title>
		<link>http://www.udidahan.com/2007/08/06/dont-trust-developers-with-project-management/</link>
		<comments>http://www.udidahan.com/2007/08/06/dont-trust-developers-with-project-management/#comments</comments>
		<pubDate>Mon, 06 Aug 2007 21:29:01 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Management]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[The Team]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/08/06/dont-trust-developers-with-project-management/</guid>
		<description><![CDATA[What with all the warm and fuzzy feelings around trusting developers (here, here, and here) I just have to tone it down a bit. The title takes it a bit far &#8211; but less than you might think. Just today I had a talk with one of the team leads on the project I&#8217;m consulting [...]]]></description>
			<content:encoded><![CDATA[<p>What with all the warm and fuzzy feelings around trusting developers (<a href="http://feeds.feedburner.com/~r/Commonality/~3/141206718/DevelopersAndTrust.aspx">here</a>, <a href="http://feeds.feedburner.com/~r/AyendeRahien/~3/141094234/Those-untrustworthy-developers.aspx">here</a>, and <a href="http://codebetter.com/blogs/jeremy.miller/archive/2007/08/05/on-software-teams.aspx">here</a>) I just have to tone it down a bit. The title takes it a bit far &#8211; but less than you might think. Just today I had a talk with one of the team leads on the project I&#8217;m consulting on. It boiled down to this:</p>
<p>Developers don&#8217;t know how to estimate.</p>
<p>Or more specifically, the variance in the actual completion time of a feature from the estimate given by a developer increases probably exponentially with time.</p>
<p>For example, if the estimate is a day, you can expect it to be finished in around a day. If the estimate is a week (5 works days), it will probably vary between 4-10 work days. If the estimate is a month, in all actuallity the developer probably doesn&#8217;t know enough to say but will answer when pressed.</p>
<p>This is why Ron (the team lead) asked me if I wasn&#8217;t worried I was putting myself in a lose-lose situation by changing the project structure. There were two &#8220;teams&#8221; when I came in &#8211; developers and testers. All the team leads had &#8220;committed&#8221; to &#8220;finishing&#8221; the project in 6 months. When I originally proposed the change to more feature-driven teams, mixing skilled and newer developers and testers together on the same team, came the cry:</p>
<p>&#8220;It&#8217;ll take us twice as long this way.&#8221;</p>
<p>&#8220;It&#8217;s so much less efficient than before.&#8221;</p>
<p>And on, and on. What was funny to me was that 3 of the &#8220;6&#8243; months were already gone and not a single feature worked. We were half &#8220;gone&#8221;, and nowhere near half done.</p>
<p>The thing is that Ron was sure I was cooking my own goose with upper management. What he, and most other developers don&#8217;t know is that upper management has gotten used to the state of things. If developers say one month, management has seen enough history to know that it&#8217;ll really be 3-4 months. So when I come in and do things different from what developers are used to, upper management is thrilled &#8211; that&#8217;s why they brought me in the first place.</p>
<p>The difference is that by working based on features, and measuring project progress by feature-units completed per iteration, I drive down variability. This creates solid data about progress saying when we&#8217;ll be done (more or less). This is quite different from the &#8220;normal&#8221; course of many projects:</p>
<p>&#8220;OK, so it&#8217;s been 8 months now on your 6 month project. When will you guys be finished already?&#8221;</p>
<p>Without the data, your only strategy is hope: &#8220;Umm, I hope the developers will be done this week(?)&#8221;</p>
<p>Don&#8217;t get me wrong. I trust my developers and testers deeply. But it&#8217;s not their job to know how to estimate and manage projects. PMs who take developers estimates as is and stake the project on that being correct are setting themselves up for failure &#8211; with only themselves to blame.</p>
<p>Now back to your nice warm-and-fuzzy blogging&#8230; <img src='http://www.udidahan.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/08/06/dont-trust-developers-with-project-management/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>Performant and Explicit Domain Models</title>
		<link>http://www.udidahan.com/2007/06/04/performant-and-explicit-domain-models/</link>
		<comments>http://www.udidahan.com/2007/06/04/performant-and-explicit-domain-models/#comments</comments>
		<pubDate>Mon, 04 Jun 2007 20:31:34 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Business Rules]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Databases]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Simplicity]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Threading]]></category>

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

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

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

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

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/05/17/testing-services-the-hard-way-with-wcf/</guid>
		<description><![CDATA[I just read the kind of hoops you have to go through in order to test your WCF service implementations. Oh. My. GOD.
If that&#8217;s the best there is, NOBODY is going to be testing their WCF services. That&#8217;s scary.
When using this message-based design, your service implementations tend to look like this:

public class WorkflowMessageHandler : IMessageHandler
{
	public [...]]]></description>
			<content:encoded><![CDATA[<p>I just read the kind of hoops you have to go through in order to <a href="http://blogs.msdn.com/martijnh/archive/2007/05/17/testing-wcf-service-implementations.aspx">test your WCF service implementations</a>. Oh. My. GOD.</p>
<p>If that&#8217;s the best there is, NOBODY is going to be testing their WCF services. That&#8217;s <i>scary</i>.</p>
<p>When using this <a href="http://udidahan.weblogs.us/2006/06/02/can-indigo-be-my-bus/">message-based design</a>, your service implementations tend to <a href="http://udidahan.weblogs.us/2007/05/12/service-enabled-workflows-with-wf-and-wcf/">look like this</a>:</p>
<pre>
public class WorkflowMessageHandler : IMessageHandler<Stage1Msg>
{
	public void Handle(Stage1Msg msg)
	{
		using (IDBScope scope = this.DbServices.GetScope(TransactionOption.On))
		{
			IWorkflow wf = this.DbServices.Get(msg.WorkFlowID);
			wf.Handle(msg);

			scope.Complete();
		}
	}
}
</pre>
<p>And it&#8217;s this easy to test them:</p>
<pre>
[TestMethod]
public void TestWorkflowMessageHandler()
{
	WorkflowMessageHandler handler = new WorkflowMessageHandler();
	handler.Bus = this.MockBus;

	// set up expectations on bus in terms of messages returned

	Stage1Msg msg = new Stage1Msg();
	// fill msg with data

	handler.Handle(msg);

	// verify expectations on bus
}
</pre>
<p>That&#8217;s right, it&#8217;s just plain old unit testing the way we test everything else these days.</p>
<p>I&#8217;m beginning to get the impression that the new suite of technologies that is coming out of Microsoft is making things more complicated than they need to be.</p>
<p>Well, maybe that&#8217;s just me.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/05/17/testing-services-the-hard-way-with-wcf/feed/</wfw:commentRss>
		<slash:comments>2</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>Self-Documenting, Test-Driven Alien Artifacts</title>
		<link>http://www.udidahan.com/2007/04/16/self-documenting-test-driven-alien-artifacts/</link>
		<comments>http://www.udidahan.com/2007/04/16/self-documenting-test-driven-alien-artifacts/#comments</comments>
		<pubDate>Mon, 16 Apr 2007 20:56:38 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Management]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/04/16/self-documenting-test-driven-alien-artifacts/</guid>
		<description><![CDATA[How much, and what kind of documentation do we need to create even if we have “self-documenting code”? Or is that kind of code enough all by itself? I for one yearn for the day where the code really will be enough, and I think that Scott and Ayende do too. First of all, I [...]]]></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>How much, and what kind of documentation do we need to create even if we have “self-documenting code”? Or is that kind of code enough all by itself? I for one yearn for the day where the code really will be enough, and I think that </FONT><A href="http://codebetter.com/blogs/scott.bellware/archive/2007/04/15/161874.aspx"><FONT face=Calibri>Scott</FONT></A><FONT face=Calibri> and </FONT><A href="http://ayende.com/Blog/archive/2007/04/16/Read-The-Code-is-not-a-valid-answer.aspx"><FONT face=Calibri>Ayende</FONT></A><FONT face=Calibri> do too. First of all, I think that as time progresses, the size of systems that the average developer works on is increasing substantially. And the larger a system is, the more we find a kind of code/design dialect that developers use to talk about that system. I think that these dialects are significantly different between framework/open source code, and application code. So, when a new developer comes in, do we tell them to “just read the code”? Or if the application has gone into production some time ago and now needs to be enhanced but the original team is long gone, what can be done?<?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>What I usually suggest (and practice) is to have some kind of documentation explaining “language” of the system – what things go together, how, and why; and just as importantly, what things must be kept apart. This can be a Software Architecture and Design document, or even videos of the design sessions where things were first discussed. The relevant requirements should be a part of this as well. We need to know that the reason asynchronous messaging was used was for the strenuous scalability requirements, otherwise we might start adding the high-productivity Visual Studio Web Services we like so much.<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>Continuous integration is a boon to projects who use them. But developers who are only familiar with building solutions in Visual Studio may not be used to working that way, keeping code checked out for weeks at a time.<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"><A href="http://codebetter.com/blogs/scott.bellware/archive/2007/04/15/161875.aspx"><FONT face=Calibri>Test-Driven Development and Architecture</FONT></A><FONT face=Calibri> will help those who know about it. We should probably write something up about how the system should be enhanced. Side-effect or not, developers and testers will need to know how we test the system – what tools are used in which way and at which stage of the development lifecycle. We could reference existing methodologies as well as in what ways we deviate from them and why.<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 <I>sustainable</I> business value do we provide by leaving behind us </FONT><A href="http://www.eaves.org/blog-archive/000071.html"><FONT face=Calibri>alien artifacts and practices</FONT></A><FONT face=Calibri>? I’m not saying not to use state-of-the-art designs, techniques, and practices. On the contrary, I think that they are the key to sustainable business value. Necessary, but not sufficient. Documentation, of whatever flavor you find most suitable to each specific thing you are documenting, should be considered by the team as a whole, and the conclusions presented to stakeholders. The famous Chrysler C3 project’s long-term business value is shaky as the result of those stakeholders decision that documentation wasn’t necessary – in no way was the Agile process faulty in that respect.<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>Finally, you may be surprised the holes you find in your own thinking when forced to write down and explain to someone just coming in “how we do things around here”, I know I was. I can tell you that in the cases where I did that exercise, several stupid, costly mistakes were avoided. Fleshing out your thinking isn’t necessarily big design up front (BDUF), it’s just smart.<o:p></o:p></FONT></SPAN></P></p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/04/16/self-documenting-test-driven-alien-artifacts/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>SOA Testing</title>
		<link>http://www.udidahan.com/2006/06/16/soa-testing/</link>
		<comments>http://www.udidahan.com/2006/06/16/soa-testing/#comments</comments>
		<pubDate>Fri, 16 Jun 2006 14:36:40 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[ESB]]></category>
		<category><![CDATA[SOA]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://wp_630.weblogs.us/archives/290</guid>
		<description><![CDATA[The question of testing has been gaining quite a bit of traction lately in the whole SOA context. Jimmy's been <a href="http://www.jnsk.se/weblog/posts/SOA-QSemantics.htm">aggregating </a>quite a bit of it. The catchall question, “how do I test my SOA?” is much too generic though.
<br/><br/>
First of all, we have to specify what kind of testing we’re talking about. Functional, non-functional, load, usability (services can have a UI) – each is approached differently. Second, we have to define what it is we’re testing. Are we trying to test the architecture, as the term “SOA testing” suggests, or are we focusing on testing a specific service?
<br/><br/>
Practically, architecture cannot be tested. The most common “test” performed on architecture is an inspection of use case realizations. By examining the way the system is going to be used in various scenarios, and tracing the flow through the elements that comprise the system, we can get a feel for how well the architecture supports a use case. If we see that a certain use case realization is cumbersome, or involves parts of the system that do not appear to be directly related to the use case, we might say that we found a bug in the architecture (if we really tried to use testing terminology). However, this process is really just a part of coming up with the architecture in the first place, before a single line of code is written. This doesn’t seem to jive very much with the spirit of “SOA testing”.
<br/><br/>
So, we’re back to how to test a specific service, once we decide what kind of testing we want. If we look at one of the important changes services brought to the structure of a system we can see that services represent a different style of division of functionality than components or objects. Their interfaces are different – message based. They manage their own data; which means we have to include state-based testing. When it comes to load testing, or usability testing, its hard to see what impact the decision to divide a system up into services (instead of components) has.
<br/><br/>
So, given that we’re going to want to perform functional, state-based testing on our services, we’re going to have to “exercise” them using the same kinds of communication found in a production environment – by using a <a href=http://www.ddj.com/dept/webservices/188700967>bus</a>, be it <a href=http://www.ddj.com/blog/webservicesblog/archives/2006/06/esbs_improve_so.html>ESB</a> or otherwise, to send to, and receive messages from the service under test. There’s also another level of testing that warrants examination in the service landscape and that is unit testing. What parts of a service can be unit tested, and how?
<br/><br/>
All the details, and more, coming soon :)]]></description>
			<content:encoded><![CDATA[<p>The question of testing has been gaining quite a bit of traction lately in the whole SOA context. Jimmy&#8217;s been <a href="http://www.jnsk.se/weblog/posts/SOA-QSemantics.htm">aggregating </a>quite a bit of it. The catchall question, “how do I test my SOA?” is much too generic though.</p>
<p>First of all, we have to specify what kind of testing we’re talking about. Functional, non-functional, load, usability (services can have a UI) – each is approached differently. Second, we have to define what it is we’re testing. Are we trying to test the architecture, as the term “SOA testing” suggests, or are we focusing on testing a specific service?</p>
<p>Practically, architecture cannot be tested. The most common “test” performed on architecture is an inspection of use case realizations. By examining the way the system is going to be used in various scenarios, and tracing the flow through the elements that comprise the system, we can get a feel for how well the architecture supports a use case. If we see that a certain use case realization is cumbersome, or involves parts of the system that do not appear to be directly related to the use case, we might say that we found a bug in the architecture (if we really tried to use testing terminology). However, this process is really just a part of coming up with the architecture in the first place, before a single line of code is written. This doesn’t seem to jive very much with the spirit of “SOA testing”.</p>
<p>So, we’re back to how to test a specific service, once we decide what kind of testing we want. If we look at one of the important changes services brought to the structure of a system we can see that services represent a different style of division of functionality than components or objects. Their interfaces are different – message based. They manage their own data; which means we have to include state-based testing. When it comes to load testing, or usability testing, its hard to see what impact the decision to divide a system up into services (instead of components) has.</p>
<p>So, given that we’re going to want to perform functional, state-based testing on our services, we’re going to have to “exercise” them using the same kinds of communication found in a production environment – by using a <a href="http://udidahan.weblogs.us/2006/06/02/podcast-does-an-soa-require-an-esb/">bus</a>, be it <a href="http://udidahan.weblogs.us/2006/06/04/esbs-improve-soa-testability/">ESB</a> or otherwise, to send to, and receive messages from the service under test. There’s also another level of testing that warrants examination in the service landscape and that is unit testing. What parts of a service can be unit tested, and how?</p>
<p>All the details, and more, coming soon <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/2006/06/16/soa-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

