<?xml version='1.0' encoding='UTF-8'?><rss xmlns:atom='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' version='2.0'><channel><atom:id>tag:blogger.com,1999:blog-9991642</atom:id><lastBuildDate>Thu, 11 Mar 2010 18:30:36 +0000</lastBuildDate><title>ILoggable</title><description>A place to keep my thoughts on programming</description><link>http://www.claassen.net/geek/blog/</link><managingEditor>noreply@blogger.com (ether)</managingEditor><generator>Blogger</generator><openSearch:totalResults>186</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-8464778953513818623</guid><pubDate>Mon, 22 Feb 2010 16:30:00 +0000</pubDate><atom:updated>2010-02-22T08:47:56.115-08:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>riak</category><category domain='http://www.blogger.com/atom/ns#'>db4o</category><category domain='http://www.blogger.com/atom/ns#'>nosql</category><category domain='http://www.blogger.com/atom/ns#'>mongodb</category><category domain='http://www.blogger.com/atom/ns#'>rdbms</category><title>NoSQL is the new Arcadia</title><description>Recently there's been &lt;a href="http://codebetter.com/blogs/gregyoung/archive/2010/02/18/using-an-orm-is-like-kissing-your-sister.aspx"&gt;a lot&lt;/a&gt; &lt;a href="http://codebetter.com/blogs/gregyoung/archive/2010/02/19/using-an-orm-is-like-kissing-your-sister-part-2.aspx"&gt;of people&lt;/a&gt; &lt;a href="http://blog.wekeroad.com/2010/02/06/nosql-a-practical-approach-part-1"&gt;lamenting the sheep like mentality&lt;/a&gt; &lt;a href="http://blog.dotnetclr.com/archive/2010/02/06/515.aspx"&gt;of picking RDBMS&lt;/a&gt; (and with it ORMs) as the way to model persistence, without first considering solutions that do not suffer the &lt;a href="http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch"&gt;object-relational impedance mismatch&lt;/a&gt;.

&lt;p&gt;Many of the arguments for having to use RDBMS' are easily shot down, such as the relentless requirements for adhoc reporting against production data (&lt;b&gt;If your OLTP and OLAP are the same DB &lt;i&gt;you are doing it wrong&lt;/i&gt;&amp;#0153;.&lt;/b&gt;) But just because the arguments for picking an RDBMS are often ill-considered, the reasons for abandoning it also seem to suffer from some depth of consideration.

&lt;p&gt;Let me be clear that I do my best to stay away from RDBMS' whenever i can. I have plenty of scars from supporting large production DB environments over the years and there are lots of pain points in writing web applications against RDBMS'. I, too, love schema-less, document and object databases. They make so much sense. I rabidly follow the &lt;a href="http://blog.dotnetclr.com/archive/2010/02/06/515.aspx"&gt;MongoDB&lt;/a&gt; and &lt;a href="http://riak.basho.com/"&gt;Riak&lt;/a&gt; mailing lists and prototype projects with them and others NoSQL tech, such as &lt;a href="http://www.db4o.com/"&gt;Db4o&lt;/a&gt;. However, following those lists it is clear to me that a) they are still re-discovering lessons painfully learned by RDBMS folks and b) my knowledge of working with these systems when something goes wrong is woefully behind my knowledge of the same for RDBMS.

&lt;h2&gt;Pick the best tool&lt;/h2&gt;
&lt;p&gt;So yes, marvel at the simplicity of mapping your object model to a document model, or even serialize that object graph using an object or graph DB. But don't just concentrate on what they do better for development, ignoring the day-to-day production support issues. Take a minute and see if you can answer these questions for yourself:

&lt;h3&gt;Can you troubleshoot performance problems?&lt;/h3&gt;

&lt;p&gt;Every RDBMS has some kind of profiling tool and process list. And on the ORM side, &lt;a href="http://ayende.com/Blog/Default.aspx"&gt;Ayende&lt;/a&gt;'s &lt;a href="http://hibernatingrhinos.com/products/UberProf"&gt;Uberprof&lt;/a&gt; is doing a fantastic job of bringing additional transparency to many ORMs. Do you have any similar tools for the alternative persistence layer? Do you know what's blocking your writes, your reads? What's slowing down your map/reduce? What indicies, if applicable, are being hit? And if you're using a sharded setup, profiling just got an order of magnitude more complicated.
 
&lt;h3&gt;What about concurrency on non-key accesses?&lt;/h3&gt;

Key/value stores are much faster than even primary key hits on RDBMS. And document databases let you store the entire data hierarchy instead of normalizing them across foreign key tables making graph retrieval cheap too.

&lt;p&gt;But as NoSQL goes beyond simple key retrieval with query APIs and map/reduce, concurrency concerns sneak back in along with the query power. Many NoSQL stores are still using single threaded concurrency per node or at least data silos (read: table locking).In RDBMS land, mysql was the last one to solve that and it did it 6-7 years ago.

&lt;h3&gt;What tools to you have to recover a corrupted data file?&lt;/h3&gt;

&lt;p&gt;Another set of tools you are guaranteed to find with any RDBMS are utilities for recovering corrupted data and index files. Or at the very least utilities for extracting data from them in case of catastrophic failure.

&lt;p&gt;With many NoSQL stores using memory mapped files, corruption on power loss or DB crash is not uncommon. Does you persistence choice have ways to recover those files?

&lt;h3&gt;What's your backup strategy?&lt;/h3&gt;

Most DBs have non-blocking DB dumps. Almost all have replication. Both are valid mechanisms. 

&lt;p&gt;Some NoSQL stores use replication to address the problem, others seem to punt on it by using redundant data duplication across nodes. But unless your redundant/replica nodes are geographically co-located, it's not the same as being able to go back to a backup on catastrophic loss.

&lt;h3&gt;How do you know your replicas are working?&lt;/h3&gt;

So you say, you don't care if your data gets corrupted or that you can't do live backups, because it all gets replicated to a safe server. Well, much like going back to tape only to discover that your back-up process hasn't actually backed up anything, &lt;b&gt;do you have the tools to ensure that your replicas are up to date and didn't get the corruption replicated into them?&lt;/b&gt;

&lt;h3&gt;Do your sysadmins share your comfort level?&lt;/h3&gt;

&lt;p&gt;A lot of these production level and back-up related issues are not even something developers think about, because with the maturity of RDBMS' their maintenance and back-up are often tightly integrated into the sysadmin's processes. If you don't think you need to care about the above questions, chances are you have others doing it for you. And in that case, it's vital that your sysadmins are versed the in NoSQL tool you are choosing before you throw the operations requirements over the wall at them.

&lt;h2&gt;The tool you know&lt;/h2&gt;

&lt;p&gt;Maybe you have all those questions covered for your NoSQL tool of choice. &lt;b&gt;Google, Facebook, LinkedIn&lt;/b&gt; do. &lt;i&gt;But likely, you don't&lt;/i&gt;. Maybe you don't have them covered for any RDBMS that you know either. But here's the difference: &lt;b&gt;These problems have been tackled in painstaking detail in thousands of RDBMS production environments&lt;/b&gt;. So, when you hit a wall with an RDBMS, chances are you can find an answer and get yourself out of that production mess.

&lt;p&gt;The relative novelty and deployment size of most NoSQL solutions means you can't easily fall back on established production experience. Until you have that same certainty &lt;i&gt;when, not if,&lt;/i&gt; you face problems in production, you can't really say that you objectively evaluated all choices and found NoSQL to be the superior solution to your problem.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-8464778953513818623?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2010/02/nosql-is-new-arcadia.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>2</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-1595758739678185973</guid><pubDate>Sat, 20 Feb 2010 18:31:00 +0000</pubDate><atom:updated>2010-02-20T11:43:45.756-08:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>ffs win2k8 win7 administrator</category><title>You're an administrator, not THE Administrator</title><description>I set up a new dev machine last week and decided to give win7 a try. Most recent dev setup was using win2k8 server and it's still my favorite dev environment. Fast, unobtrusive, things just worked.

&lt;p&gt;Win7 appeared to be a different story, reminding me of the evil days of Vista. I had expected it to be more like Win2k8 server, but it just wasn't. I was trying to be zen about the constant UAC nagging and just get used to the way it wanted me to work. But two days in, it just came to a head and after wasting countless hours trying to work within the security circus it set up, i was ready to pave the machine.

&lt;p&gt;Here's just a couple of things that were killing me:
&lt;dl&gt;
&lt;dt&gt;Can't save into Program Files from the web&lt;/dt&gt;
&lt;dd&gt;Had to save into my documents then move it there. Worse, it told me i had to talk to an administrator about that. I am an administrator!&lt;/dd&gt;
&lt;dt&gt;Can't unzip into Program Files&lt;/dt&gt;
&lt;dd&gt;Same story as above.&lt;/dd&gt;
&lt;dt&gt;Have to whitelist reserve Uri's for HttpListeners and you can't wildcard ports.&lt;/dt&gt;
&lt;dd&gt;This was the final straw, since my unit tests create random port listeners so that the shutdown failures of a previous test doesn't hose the registration of the next.&lt;/dd&gt;
&lt;/dl&gt;

&lt;p&gt;All these things need administrator privileges. But wait, I am an administrator, so what's going on? It appears that being an administrator is more like being in the sudoers file on unix. I have the right to invoke commands in the context of an administrator, but my normal actions aren't. I tried to work around this with registry hacks, shortcuts set to run as administrator and so on, to try to get things to start-up with administrator privs by default, but Visual Studio 2k8 just refused to play along. You cannot set it up so that you can double-click on a solution and it launch the solution as administrator in Win7. And even if you start VS as administrator, you cannot drag&amp;drop files to it since it's now running in a different context as Explorer.

&lt;p&gt;And if you ask MS Connnect about this you'll find that like anything of value &lt;a href="https://connect.microsoft.com/VisualStudio/feedback/details/263221/cant-open-sln-files-when-under-uac-in-vista"&gt;the issue has been closed as "By Design."&lt;/a&gt;. Ok, &lt;i&gt;look buddy&lt;/i&gt;, just because you designed a horrible user experience doesn't mean the problem can just be dismissed.

&lt;p&gt;&lt;i&gt;But why was win2k8 so much better an experience&lt;/i&gt;, a nagging voice kept asking. Turns out that on win2k8, i just run as Administrator. Win7 never gave that option (and you have to do &lt;a href="http://www.howtogeek.com/howto/windows-vista/enable-the-hidden-administrator-account-on-windows-vista/"&gt;some cmdline foo&lt;/a&gt; to enable the account.) Being a unix guy as well, running dev in what is root, just felt distasteful. But distaste or not, it's the key for actually being able to do productive development work in windows. As soon as I became THE Administrator, instead of an administrator, all was smooth again.

&lt;p&gt;Stupid lesson learned.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-1595758739678185973?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2010/02/youre-adminstrator-not-administrator.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-1286138991195490392</guid><pubDate>Fri, 22 Jan 2010 06:02:00 +0000</pubDate><atom:updated>2010-01-22T17:07:10.150-08:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>IL</category><category domain='http://www.blogger.com/atom/ns#'>ducktyping</category><category domain='http://www.blogger.com/atom/ns#'>Reflection.Emit</category><category domain='http://www.blogger.com/atom/ns#'>c#</category><title>Duckpond: Lightweight duck-typing for C#</title><description>&lt;b&gt;Edit&lt;/b&gt;: Changed &lt;code&gt;As&lt;/code&gt; to &lt;code&gt;AsImplementationOf&lt;/code&gt; since it's an extension method on &lt;code&gt;object&lt;/code&gt; and too likely to collide.

&lt;p&gt;A while back I was &lt;a href="http://www.claassen.net/geek/blog/2009/06/c-duck-typing-to-rescue-for.html"&gt;talking about Interface Segregation&lt;/a&gt; and proposed using either LinFu's DynamicObject or delegate injection. While I &lt;a href="http://www.claassen.net/geek/blog/2009/06/ultimate-interface-segregation.html"&gt;played a bit more with delegate injection&lt;/a&gt;, in practical use delegate injection turned out to be rather ugly and not really improve readability.

&lt;p&gt;So, I've come back to wanting to cast an object to an interface regardless of what interfaces that object implemented. I wanted this to be as simple and lightweight as possible, so rather than using a dynamic proxy framework, i simply rolled my own IL and wrote a pure proxy that does nothing but call the identical method on the class it wraps.

&lt;h2&gt;Introducing DuckPond&lt;/h2&gt;

&lt;b&gt;DuckPond&lt;/b&gt; is a very simple and focused library. It currently adds only a single extension method: &lt;code&gt;object.AsImplementationOf&amp;lt;Interface&amp;gt;&lt;/code&gt;

&lt;p&gt;Given a class &lt;code&gt;Duck&lt;/code&gt; that implements a number of methods, including &lt;code&gt;Quack&lt;/code&gt;:
&lt;pre class="brush: csharp;"&gt;
public class Duck {
  public void Quack(double decibels) {
    ...
  }
  ... various other methods ...
}
&lt;/pre&gt;

we can easily cast &lt;code&gt;Duck&lt;/code&gt; to a more limited interface that the class doesn't implement such as:

&lt;pre class="brush: csharp;"&gt;
public interface IQuacker {
  void Quack(double decibels);
}
&lt;/pre&gt;

using the &lt;code&gt;object.AsImplementationOf&amp;lt;T&amp;gt;&lt;/code&gt; extension method:

&lt;pre class="brush: csharp;"&gt;
using Droog.DuckPond;

...

var quacker = new Duck().AsImplementationOf&amp;lt;IQuacker&amp;gt;();
&lt;/pre&gt;

That's all there is to it.

&lt;h2&gt;But is it fast?&lt;/h2&gt;

Honestly, i don't know yet. I have not benchmarked the generated classes against virtual method dispatches or LinFu's and Castle's dynamic proxy. I assume it is, since unlike with dyanmic proxy, DuckPond doesn't use an interceptor. Instead it emits Intermediate Language for each call in the interface, dispatching the call against the wrapped instance's counterpart.

&lt;h2&gt;Try it, fork it, let me know what you think&lt;/h2&gt;

The code is available now at GitHub: &lt;a href="http://github.com/sdether/duckpond"&gt;http://github.com/sdether/duckpond&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-1286138991195490392?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2010/01/duckpond-lightweight-duck-typing-for-c.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>1</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-300223179467685196</guid><pubDate>Sun, 27 Sep 2009 19:33:00 +0000</pubDate><atom:updated>2009-09-27T17:46:49.943-07:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>mysql</category><category domain='http://www.blogger.com/atom/ns#'>NHibernate</category><category domain='http://www.blogger.com/atom/ns#'>nosql</category><category domain='http://www.blogger.com/atom/ns#'>linq</category><category domain='http://www.blogger.com/atom/ns#'>c#</category><category domain='http://www.blogger.com/atom/ns#'>mongodb</category><category domain='http://www.blogger.com/atom/ns#'>fluent interface</category><title>Linq2MongoDB: Building a Linq Provider for MongDB</title><description>This weekend has been a &lt;i&gt;hack-a-thon&lt;/i&gt;, trying to build a simple linq provider for &lt;a href="http://www.mongodb.org"&gt;MongoDB&lt;/a&gt;. I'm using &lt;a href="http://github.com/samus/mongodb-csharp"&gt;Sam Corder, et al.'s excellent C# MongoDB Driver&lt;/a&gt; as the query pipeline, so my provider really is just a translator from Linq syntax to Mongo Document Query syntax. I call it a &lt;i&gt;hack-a-thon&lt;/i&gt;, because it's my first linq provider attempt and, boy, is that query translator state machine ugly already. However, I am covering every bit of syntax with tests, so that once i understand it all better, i can rewrite the translator in a cleaner fashion.

&lt;p&gt;My goals for this provider is to replace a document storage layer i've built for a new &lt;a href="http://notify.me/"&gt;notify.me&lt;/a&gt; project using &lt;a href="http://nhforge.org/Default.aspx"&gt;NHibernate&lt;/a&gt; against mysql. This is in no way a judgment against NHibernate. It just happens that for this project, my schema is a heavily denormalized json document database. While &lt;a href="http://fluentnhibernate.org/"&gt;fluent NHibernate&lt;/a&gt; made it a breeze to let me map it into mysql, it's really an abuse of an RDBMS. It was a case of &lt;i&gt;prototyping with what you know&lt;/i&gt;, but now it's time to evaluate whether a document database is the way to go.

&lt;p&gt;Replacing existing NHibernate code does mean that, eventually, &lt;b&gt;i want the provider to work with POCO entities&lt;/b&gt; and use a fully strong-typed query syntax. But that layer will be built on top of the &lt;i&gt;string&lt;/i&gt;-key based version i'm building right now. The &lt;i&gt;string&lt;/i&gt;-key based version will be the primary layer, so that you never loose any of the schema-less flexibility of MongoDB, unless you choose to.

&lt;h2&gt;Basic MongoDB queries&lt;/h2&gt;
&lt;p&gt;So, lacking an entity with named properties to map against, what does the syntax look like right now? First thing we need is an &lt;code&gt;IQueryable&amp;lt;Document&amp;gt;&lt;/code&gt; which is created like this:

&lt;pre class="brush: csharp;"&gt;
var mongo = new Mongo();
var queryable = mongo[&amp;quot;db&amp;quot;][&amp;quot;collection&amp;quot;].AsQueryable();
&lt;/pre&gt;

Given the queryable, the queries can be built using the &lt;code&gt;Document&lt;/code&gt; indexer like this:

&lt;pre class="brush: csharp;"&gt;
var q = from d in queryable where (string)d[&amp;quot;foo&amp;quot;] == &amp;quot;bar&amp;quot; select d;
&lt;/pre&gt;

The &lt;code&gt;Document&lt;/code&gt; returns an &lt;code&gt;object&lt;/code&gt;, which means a cast is unfortunately required on one side of the conditional. Alternatively, &lt;code&gt;Equals&lt;/code&gt;, either the static or instance version, also works, alleviating the need for a cast:

&lt;pre class="brush: csharp;"&gt;
var q = from d in queryable where Equals(d[&amp;quot;foo&amp;quot;], &amp;quot;bar&amp;quot;) select d;
// OR
var q = from d in queryable where d[&amp;quot;foo&amp;quot;].Equals(&amp;quot;bar&amp;quot;) select d;
&lt;/pre&gt;

Better, but it's not as nice as operator syntax would be, if we could get rid of the casts..

&lt;p&gt;As it turns out there is a number of query operators in MongoDB that don't have an equivalent syntax in Linq, so a helper class to generate query expression was already needed. The helper is instantiated via the &lt;code&gt;Document&lt;/code&gt; extension method &lt;code&gt;.Key(&lt;i&gt;key&lt;/i&gt;)&lt;/code&gt;, giving us the opportunity to overload operators for the various types recognized by MongoDB's BSON. This allows for the following conditional syntax:

&lt;pre class="brush: csharp;"&gt;
var q = from d in queryable 
        where d.Key(&amp;quot;type&amp;quot;) == &amp;quot;customer&amp;quot; &amp;amp;&amp;amp;
              d.Key(&amp;quot;created&amp;quot;) &amp;gt;= DateTime.Parse(&amp;quot;2009/09/27&amp;quot;)
              d.Key(&amp;quot;status&amp;quot;) != &amp;quot;inactive&amp;quot;
        select d;
&lt;/pre&gt;
&lt;h2&gt;IN and NOT IN&lt;/h2&gt;
&lt;p&gt;In addition to normal conditional operators, the query expression helper class also defines IN and NOT IN syntax:

&lt;pre class="brush: csharp;"&gt;
var in = from d in queryable where d.Key(&amp;quot;foo&amp;quot;).In(&amp;quot;bar&amp;quot;, &amp;quot;baz&amp;quot;) select d;

var notIn = from d in queryable where d.Key(&amp;quot;foo&amp;quot;).NotIn(&amp;quot;bar&amp;quot;, &amp;quot;baz&amp;quot;) select d;
&lt;/pre&gt;
The helper will be the point of extension to support more of MongoDB's syntax, so that most query definitions will use the &lt;code&gt;d.Key(&lt;i&gt;key&lt;/i&gt;)&lt;/code&gt; syntax.

&lt;h2&gt;findOne, limit and skip&lt;/h2&gt;

Linq has matching counter parts of MongoDB's &lt;b&gt;findOne()&lt;/b&gt;, &lt;b&gt;limit()&lt;/b&gt; and &lt;b&gt;skip()&lt;/b&gt;, in &lt;code&gt;First&lt;/code&gt; or &lt;code&gt;FirstOrDefault&lt;/code&gt;, &lt;code&gt;Take&lt;/code&gt; and &lt;code&gt;Skip&lt;/code&gt; respectively, and the current version of Linq provider already supports them.

&lt;h2&gt;What's missing?&lt;/h2&gt;

There is a lot in Linq that will likely never be supported, since MongoDB is not a relational DB. That means joins, sub-queries, etc. will not covered by the provider. Anything that does map to MongoDB's capabilities, though, will be added over time. The low hanging fruit are &lt;code&gt;Count()&lt;/code&gt; and &lt;code&gt;order by&lt;/code&gt;, with &lt;code&gt;group by&lt;/code&gt; following thereafter.

&lt;p&gt;Surprisingly, &lt;b&gt;||&lt;/b&gt; (&lt;i&gt;or&lt;/i&gt; conditionals) are not going to happen as fast, since aside from &lt;i&gt;or&lt;/i&gt; type queries using the &lt;code&gt;.In&lt;/code&gt; syntax, it is not directly supported by MongoDB. In order to perform &lt;b&gt;||&lt;/b&gt; queries, the query has to be written as a javascript function, which would basically mean that as soon as a single &lt;b&gt;||&lt;/b&gt; shows up in the &lt;b&gt;where&lt;/b&gt; clause the query translato would have to rewrite all other conditions in javascript as well. So, that's a bit more on the &lt;i&gt;nice to have&lt;/i&gt; end of the spectrum of priorities.

&lt;h2&gt;Ready to go!&lt;/h2&gt;

&lt;p&gt;I will most likely concentrate on the low hanging fruit and then work on the POCO query layer next, since my goal is to be able to try out MongoDB as an alternative to my NHibernate code.

&lt;p&gt;All that said, the code described above works now and is ready for some test driving. It's currently only in &lt;a href="http://github.com/sdether/mongodb-csharp"&gt;my branch on github&lt;/a&gt;, but I hope it will make it into the &lt;a href="http://github.com/samus/mongodb-csharp"&gt;master&lt;/a&gt; soon.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-300223179467685196?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2009/09/linq2mongodb-building-linq-provider-for.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>2</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-8279543106517729246</guid><pubDate>Thu, 24 Sep 2009 15:51:00 +0000</pubDate><atom:updated>2009-09-24T09:17:45.425-07:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>c#</category><category domain='http://www.blogger.com/atom/ns#'>coroutines</category><category domain='http://www.blogger.com/atom/ns#'>mindtouch</category><category domain='http://www.blogger.com/atom/ns#'>dream</category><category domain='http://www.blogger.com/atom/ns#'>concurrency</category><title>About Concurrent Podcast #3: Coroutines</title><description>Posted a &lt;a href="http://blog.developer.mindtouch.com/2009/09/23/concurrent-podcast-episode-3-coroutines/"&gt;new episode&lt;/a&gt; of the &lt;b&gt;&lt;a href="http://developer.mindtouch.com/Community/Concurrent_Podcast"&gt;Concurrent Podcast&lt;/a&gt;&lt;/b&gt; over on the &lt;a href="http://blog.developer.mindtouch.com/"&gt;MindTouch developer blog&lt;/a&gt;. This time Steve and I delve into Coroutines, a programming pattern we use extensively in MindTouch 2009 and one that i'm also trying out as an alternative to my actor based Xmpp code in Notify.me.

&lt;p&gt;Since there isn't a native coroutine framework in C#, we're using the one provided by MindTouch &lt;a href="http://developer.mindtouch.com/dream"&gt;Dream&lt;/a&gt;. It's built on top of the .NET iterator pattern (i.e. &lt;code&gt;IEnumerable&lt;/code&gt; and &lt;code&gt;yield&lt;/code&gt;) and makes the assumption that all Coroutines are asynchronous methods using Dream's &lt;code&gt;Result&amp;lt;T&amp;gt;&lt;/code&gt; object for coordinating the producer and consumer of a return values. Steve's &lt;a href="http://www.mindtouch.com/blog/2007/10/17/dream-asynchronicity-results/"&gt;previously blogged about &lt;code&gt;Result&lt;/code&gt;&lt;/a&gt;. Since those posts there's also been a lot of performance improvements and capability improvements to &lt;code&gt;Result&lt;/code&gt; committed to trunk, primarily providing robust cancellation with resource cleanup callbacks. For background on coroutines, you can also check out &lt;a href="http://www.mindtouch.com/blog/2008/10/21/dream-asynchronicity-coroutines/"&gt;previous posts I'vee written&lt;/a&gt;.

&lt;p&gt;The cool thing about asynchronous coroutines compared to an actor model is that call/response based actions can be written as a single linear block of code, rather than separate message handlers whose contiguous flow can only be determined by examining the message dispatcher. With a message dispatcher that can correlate message responses with suspended coroutines, sending and waiting for a message in a coroutine can be made to look like a method call without blocking the thread, which, especially with message passing concurrency, is vital, since a response isnn't in any way guaranteed to happen.

&lt;p&gt;I'm due to write another post on how to use Dream's coroutine framework, but in the meantime i highly recommend checking out Dream from &lt;a href="https://svn.mindtouch.com/source/public/dream"&gt;mindtouch's svn&lt;/a&gt;. Lot's of cool concurrency stuff in there. &lt;i&gt;trunk&lt;/i&gt;is under heavy development, as we work towards Dream profile 2.0, but 1.7.0 is stable and production proven.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-8279543106517729246?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2009/09/about-concurrent-podcast-3-coroutines.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-4285851469154751064</guid><pubDate>Tue, 15 Sep 2009 17:23:00 +0000</pubDate><atom:updated>2009-09-23T09:11:35.268-07:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>linq</category><category domain='http://www.blogger.com/atom/ns#'>c#</category><title>Composing remote and local linq queries</title><description>One of the cool things with Linq is that queries are composable, i.e. &lt;b&gt;you can add further query constraints by selecting from an existing query&lt;/b&gt;. Nothing is executed until you try to read from the query. This allows IQueryable to compose all the added constraints and transform it into the underlying query structure, most commonly SQL.

&lt;p&gt;However it does come with the pitfall that there are a lot of things legal in Linq expressions that will die at run time. This happens because an expression may not have an equivalent syntax in the transformed language, like calling a method as part of a where clause.

&lt;p&gt;This does not mean that you can't use linq for the portion of the query that is not executable by the provider. As long as you know what expression is affected, you can use query composition to &lt;b&gt;build a query that executes some part remotely and some part against the object model in memory&lt;/b&gt;.

&lt;p&gt;Let's suppose we wish to execute the following query:

&lt;pre class="brush: csharp;"&gt;
var q = from e in session.Queryable&amp;lt;Entry&amp;gt;()
    where e.Created &amp;gt; DateTime.Parse(&amp;quot;2009/9/1&amp;quot;) 
        &amp;amp;&amp;amp;  e.Created &amp;lt; DateTime.Now
        &amp;amp;&amp;amp; e.Tags.Contains('foo')
    select e;&lt;/pre&gt;
But our query provider doesn't understand the extension method that allows us to check the list of Tags. In order for this query to work, that portion must be executed against the result set of the date range query. We could coerce the first portion to a list or array and then query that portion, but that would just force the date query to be materialized before we could prune the set. Instead we want to feed the stream of matching entries into a second query, composing a new query that contains both portions as a single query and won't access the database until we iterate over it.

&lt;p&gt;To accomplish this I created an extension method that coerces the query into a sequence that yields each item as it is returned by the database query:

&lt;pre class="brush: csharp;"&gt;
public static class LinqAdapter {
    public static IEnumerable&amp;lt;T&amp;gt; AsSequence&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; enumerable) {
        foreach(var item in enumerable) {
            yield return item;
        }
    }
}&lt;/pre&gt;

&lt;b&gt;UPDATE:&lt;/b&gt;&lt;i&gt; As &lt;a href="http://www.odetocode.com/blogs/scott/"&gt;Scott&lt;/a&gt; points out in the comments, my &lt;code&gt;AsSequence&lt;/code&gt; just re-implements what is already available in Ling as &lt;code&gt;AsEnumerable&lt;/code&gt;. So the above really just serves to explain how &lt;code&gt;AsEnumerable&lt;/code&gt; defers execution to enumeration rather than query definition.&lt;/i&gt;

&lt;p&gt;Anyway, &lt;code&gt;AsSequence&lt;/code&gt; or &lt;code&gt;AsEnumerable&lt;/code&gt; allows me to compose the query from server and local expressions like this:

&lt;pre class="brush: csharp;"&gt;
var q = from e in session.Queryable&amp;lt;Entry&amp;gt;()
    where e.Created &amp;gt; DateTime.Parse(&amp;quot;2009/9/1&amp;quot;) 
        &amp;amp;&amp;amp;  e.Created &amp;lt; DateTime.Now
    select e;
q = from e in q.AsSequence() where e.Tags.Contains('foo') select e;&lt;/pre&gt;

When q is enumerated, the first expression is converted to SQL and executes against the database. Each item returned from the database is then fed into the second query, which checks its expression and yields the item to the caller, should the expression match. Since &lt;code&gt;q.AsSequence()&lt;/code&gt; is used as part of query composition, &lt;b&gt;it does not force the first expression to execute at the time of query definition as &lt;code&gt;q.ToList()&lt;/code&gt; would&lt;/b&gt;. The additional benefit is that even when &lt;code&gt;q.AsSequence()&lt;/code&gt; is executed, it never builds the entire result set in memory as a list to iterate over, but rather just streams each database query result item through its own expression evaluation.

&lt;p&gt;Of course, this still have the performance implications of sending data across the wire and filtering it locally. However, this is not an uncommon problem when SQL alone cannot provide all the filtering. The benefit of this approach is reduced memory pressure on execution, better control when execution occurs and the ability to use Linq syntax to do the secondary filtering.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-4285851469154751064?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2009/09/composing-remote-and-local-linq-queries.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>2</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-7533939396337308104</guid><pubDate>Thu, 10 Sep 2009 22:50:00 +0000</pubDate><atom:updated>2009-09-10T15:53:16.612-07:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>c#</category><category domain='http://www.blogger.com/atom/ns#'>podcast</category><category domain='http://www.blogger.com/atom/ns#'>mindtouch</category><category domain='http://www.blogger.com/atom/ns#'>dream</category><category domain='http://www.blogger.com/atom/ns#'>concurrency</category><title>Concurrent Podcast and Producer/Consumer approaches</title><description>As usual, I've been blogging over on the &lt;a href="http://blog.developer.mindtouch.com"&gt;MindTouch Developer blog&lt;/a&gt;, and since the topics i post about over there have a pretty strong overlap with what I'd post here, I figured i might as well start cross-posting about it here.

&lt;p&gt;Aside from various technical posts, Steve Bjork and I have started recording a &lt;a href="http://blog.developer.mindtouch.com/category/podcast/concurrent-podcast/"&gt;Podcast&lt;/a&gt; about concurrent programming. It's currently 2 episodes strong, with a third one coming soon. Information on past and future posts can always be found &lt;a href="http://developer.mindtouch.com/Community/Concurrent_Podcast"&gt;here&lt;/a&gt;.

&lt;p&gt;&lt;a href="http://blog.developer.mindtouch.com/2009/09/10/producerconsumer-iblockingqueue-vs-elasticthreadpool/"&gt;Today's post&lt;/a&gt; on the MindTouch dev blog is about the producer/consumer pattern and how i moved from using dedicated workers with a blocking queue to using Dream's new ElasticThreaPool to dispatch work.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-7533939396337308104?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2009/09/concurrent-podcast-and-producerconsumer.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-3499236465424133963</guid><pubDate>Wed, 09 Sep 2009 04:05:00 +0000</pubDate><atom:updated>2009-09-08T21:05:00.369-07:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>tags</category><category domain='http://www.blogger.com/atom/ns#'>parser</category><category domain='http://www.blogger.com/atom/ns#'>coco/r</category><category domain='http://www.blogger.com/atom/ns#'>c#</category><category domain='http://www.blogger.com/atom/ns#'>compiler</category><category domain='http://www.blogger.com/atom/ns#'>ast</category><category domain='http://www.blogger.com/atom/ns#'>dsl</category><title>Writing a Tag Algebra compiler with Coco/R</title><description>This week, i was digging back into the &lt;a href="http://www.ssw.uni-linz.ac.at/coco/"&gt;Coco/R&lt;/a&gt; implemented parser of &lt;a href="http://developer.mindtouch.com/DekiScript"&gt;DekiScript&lt;/a&gt;, tracking down a bug, which turned out to not be in the parsing bits at all. It did, however, get me familiarized with Coco/R again. So I thought i'd give myself an hour to implement the parser for my &lt;a href="http://www.claassen.net/geek/blog/2009/09/boolean-algebra-for-tag-matching.html"&gt;Tag related boolean algebra&lt;/a&gt; with Coco/R. If i could pull it off, forget about the regex/state-machine approach i was considering.

&lt;p&gt;Took me about 15 minutes to set up the classes to represent the intermediate AST and another 30 minutes for the grammar in Coco/R ATG format. After that I wrote a couple of unit tests to check that the parsing was right, only to realize that while &lt;b&gt;AND&lt;/b&gt; and &lt;b&gt;OR&lt;/b&gt; are left-to-right associative, &lt;b&gt;NOT&lt;/b&gt; is right-to-left associative. Figuring out how to adjust the grammar for that actually took me another 10-15 minutes. But overall, I hit the one hour goal.

&lt;h2&gt;The Syntax Tree&lt;/h2&gt;

&lt;p&gt;Before tackling the grammar to parse, I needed to define data structures to represent the parsed syntax tree, which I'd later convert to executable code. The syntax is fairly simple:
&lt;pre&gt;
(foo+bar)|(^foo+baz)
&lt;/pre&gt;
This can be represented by just 4 tree node types (with common parent &lt;code&gt;TagExpression&lt;/code&gt;:
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;AndExpression&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;OrExpression&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;NotExpression&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Tag&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
The parentheses are just tree structure artifacts, so are not represented in the AST.

&lt;h2&gt;The Coco/R grammar&lt;/h2&gt;

I've broken the grammar up to discuss the various parts, but the below sections represent a single ATG file, the Coco/R grammar format.

&lt;pre class="brush: csharp;"&gt;
COMPILER TagAlgebra

  public TagExpression Result = TagExpression.Empty;
&lt;/pre&gt;
The &lt;b&gt;COMPILER&lt;/b&gt; defines the entrypoint &lt;b&gt;PRODUCTION&lt;/b&gt;for the parser. The following lines. until the next grammar definition, are inserted into the generated Parser, and can be used to inject class fields, extra methods, etc. into the Parser source. The only thing I inserted was a field to hold the root of the AST and initialize it to empty.
 
&lt;pre class="brush: csharp;"&gt;
IGNORECASE
&lt;/pre&gt;
This tells Coco/R that our grammar is case insensitive.
&lt;pre class="brush: csharp;"&gt;
CHARACTERS
  tab = '\t'.
  eol = '\n'.
  cr = '\r'.
  nbsp = '\u00a0'. // 0xA0 = 'unbreakable space'
  shy = '\u00ad'.  // 0xAD = 'soft-hyphen'
  letter = 'a'..'z'.
  digit = '0'..'9'.
&lt;/pre&gt;
&lt;b&gt;CHARACTERS&lt;/b&gt; defines characters that the parser should recognize for matches.
&lt;pre class="brush: csharp;"&gt;
TOKENS
  tag = 
    letter { letter | digit | &amp;quot;_&amp;quot; | &amp;quot;:&amp;quot; }
    .
&lt;/pre&gt;
The only token in the grammar are tag, which is composed from the characters defined above and extra quoted characters.
&lt;pre class="brush: csharp;"&gt;
IGNORE eol + cr + tab + nbsp + shy
&lt;/pre&gt;
&lt;b&gt;IGNORE&lt;/b&gt; tells Coco/R what characters have no meaning in parsing the input.

&lt;p&gt;Next come the &lt;b&gt;PRODUCTIONS&lt;/b&gt;, i.e. the meat of the grammar. These are the rules for matching input and converting it into code. Coco/R is an LL(1) parser generator, i.e. the grammar must be parsable from Left to Right with Left-canonical derivations and one look-ahead symbol. We also cannot have a loop in our grammar, i.e all possible branches have to lead to a terminal via a unique set of production matches.
&lt;pre class="brush: csharp;"&gt;
PRODUCTIONS

  TagAlgebra                      (. Result = TagExpression.Empty; .)
    =
    [ BinaryExpr&amp;lt;out Result&amp;gt; ]
    .
&lt;/pre&gt;
The first production, is the entry point which, again, sets the result to an empty AST, since the same instance of the parser can parse multiple expressions. It then specifies 0 or 1 &lt;b&gt;BinaryExpr&lt;/b&gt; productions.
&lt;pre class="brush: csharp;"&gt;
  BinaryExpr&amp;lt;out TagExpression expr&amp;gt;  (.  expr = null; TagExpression right = null; .)
    =
    NotExpr&amp;lt;out expr&amp;gt; {               (. bool and = false; .)
      (
        &amp;quot;|&amp;quot;
        | &amp;quot;+&amp;quot;                         (. and = true; .)
      )
      NotExpr&amp;lt;out right&amp;gt;              (. expr = and ? (TagExpression)new AndExpression(expr,right) : new OrExpression(expr,right); .)
    }
    .
&lt;/pre&gt;
&lt;b&gt;BinaryExpr&lt;/b&gt; is used for both AND and OR expressions, since both take two sub-expressions and combine them with a single operator. The production specifies a left side of a &lt;b&gt;NotExpr&lt;/b&gt; followed by an optional operator and another &lt;b&gt;NotExpr&lt;/b&gt;. I.e. should our first match happen to not be a &lt;b&gt;BinaryExpr&lt;/b&gt;, the parser can fall through to &lt;b&gt;NotExpr&lt;/b&gt; return its result instead, without matching the optional production body.
&lt;pre class="brush: csharp;"&gt;
  NotExpr&amp;lt;out TagExpression expr&amp;gt; (. expr = null; int notCount = 0; .)
    =
    { 
      &amp;quot;^&amp;quot;                         (. notCount++; .)
    }
    (
      &amp;quot;(&amp;quot; BinaryExpr&amp;lt;out expr&amp;gt; &amp;quot;)&amp;quot;
      | tag                       (. expr = new Tag(t.val); .)
    )                             (. for(var i=0;i&amp;lt;notCount;i++) expr = new NotExpression(expr); .)
    .

END TagAlgebra.
&lt;/pre&gt;
&lt;b&gt;NotExpr&lt;/b&gt;, just like &lt;b&gt;BinaryExpr&lt;/b&gt; optionally matches on its operator, requiring only that the end of the operation it matches either a &lt;b&gt;BinaryExpr&lt;/b&gt; enclosed by parentheses (i.e. not a circular match back into &lt;b&gt;BinaryExpr&lt;/b&gt;, since it requires additional surrounding matches), or it matches a tag, the ultimate terminal in the grammar.

&lt;p&gt;There is one tricky bit in this production, i.e. the NOT operator can match multiple times, which means, we need to accumulate the number of operator matches and build the chain of NOT expressions wrapping the current expression once we know how many, if any, matched.

&lt;h2&gt;What to do with the AST&lt;/h2&gt;
The nice thing with Coco/R is that it adds no runtime dependency at all, building a fully self-contained Scanner and Parser. With these built, it is now possible to take Tag Algebra expressions and turn them into an executable tree of &lt;code&gt;Func&lt;/code&gt; calls, as described in "&lt;a href="http://www.claassen.net/geek/blog/2009/09/boolean-algebra-for-tag-matching.html"&gt;Boolean Algebra for Tag queries&lt;/a&gt;".

&lt;p&gt;The grammar could have been written to accumulate the unique tags and construct the &lt;code&gt;Func&lt;/code&gt; tree right away, but the two benefits of going to an AST first, is that &lt;b&gt;a)&lt;/b&gt;the AST can easily be rendered back into text form (even placing parentheses properly for expressions that previously had not parentheses), and &lt;b&gt;b)&lt;/b&gt; the AST can easily be programatically composed with other expressions, or decomposed into sub-expressions, which can be used for caching and other efficiency operations.

&lt;p&gt;I'll probably play with &lt;a href="http://www.codeplex.com/irony"&gt;Irony&lt;/a&gt; next, but the "no runtime dependency" and existing familiarity made &lt;a href="http://www.ssw.uni-linz.ac.at/coco/"&gt;Coco/R&lt;/a&gt; the winner this time.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-3499236465424133963?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2009/09/writing-tag-algebra-compiler-with-cocor.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-2451226340231783092</guid><pubDate>Mon, 07 Sep 2009 21:49:00 +0000</pubDate><atom:updated>2009-09-07T15:11:05.815-07:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>DAO</category><category domain='http://www.blogger.com/atom/ns#'>IQueryable</category><category domain='http://www.blogger.com/atom/ns#'>NHibernate</category><category domain='http://www.blogger.com/atom/ns#'>linq</category><title>Hiding NHibernate with Linq</title><description>Been using NHibernate a lot recently, and just love having POCO data objects. This means that i can just hand out objects and manipulate them and then save them back to the DB without ever exposing my persistence model. For this purpose, I'd been using Data Access Objects to give me access to the objects. But like stored procedures, after a while you DAOs have this mess of Find methods on them that either have many overloads or, even worse, optionally nullable parameters. Never mind the acrobatics you jump through once you want to provide methods that query entities, based on some other entity, that's abstracted by its on DAO.

&lt;p&gt;The option was to expose the NHibernate query api (talking ICriteria here, never touched HQL because the reason i went NHibernate in the first place is because i didn't want queries in strings), but that didn't taste right, so i added more methods on my DAO instead, hiding the criteria queries.

&lt;p&gt;Once i started playing with the experimental Linq support, i didn't change my abstraction, just started using Linq instead of criteria inside the DAO. But last week, I finally broke down and just exposed &lt;code&gt;session.Linq&amp;lt;T&amp;gt;();&lt;/code&gt; as an &lt;code&gt;IQueryable&amp;lt;T&amp;gt;&lt;/code&gt; on my DAO. For example my Account DAO, &lt;code&gt;AccountService&lt;/code&gt; now simply looks like this:

&lt;pre class="brush: csharp;"&gt;
public interface IAccountService
{
  Account CreateAccount(JObject json);
  Account GetAccount(int accountId);
  IQueryable&amp;lt;Account&amp;gt; Accounts { get; }
  void Save(Account account);
}
&lt;/pre&gt;

NHibernate is completely invisible, I have full query capabilities and even mocking has become easier, just returning a &lt;code&gt;List&amp;lt;T&amp;gt;.AsQueryable()&lt;code&gt; from my mock DAO. I was able to remove all my Find methods. I did leave the &lt;i&gt;by Id&lt;/i&gt; accessor &lt;code&gt;GetAccount&lt;/code&gt; in there, just because it's the predominant use case, and i didn't want to litter code with identical Linq queries.

&lt;p&gt;I have to say, i like this approach a lot.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-2451226340231783092?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2009/09/hiding-nhibernate-with-linq.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-5765564640629937859</guid><pubDate>Thu, 03 Sep 2009 06:06:00 +0000</pubDate><atom:updated>2009-09-02T23:43:55.177-07:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>yagni</category><title>Teh Shiny</title><description>For technology geeks, one of the greatest enemies of productivity is &lt;i&gt;teh Shiny&lt;/i&gt;, i.e. some algorithm, framework, language that is a possible solution to the problem at hand, but mostly attracts because of its dazzling awesomeness. When something seems like the cool way to do it, chances are you are about to step into a big pile of &lt;a href="http://en.wikipedia.org/wiki/You_Ain%27t_Gonna_Need_It"&gt;YAGNI&lt;/a&gt;.

&lt;p&gt;Often, the &lt;b&gt;simplest possible solution&lt;/b&gt; or, even more importantly, &lt;b&gt;using what you know&lt;/b&gt;, rather than what appears to be the "best", is the way to go.

&lt;p&gt;A good example is the boolean algebra parser for my tag queries. Once I realized I had a mini-DSL on my hands, my google fingers were refreshing my knowledge of &lt;a href="http://www.ssw.uni-linz.ac.at/coco/"&gt;Coco/R&lt;/a&gt; and evaluating &lt;a href="http://www.codeplex.com/irony"&gt;Irony&lt;/a&gt; in order to build a parser to build me my AST. It took stepping back to realize that to get this to the prototype stage, some regex and a simple state machine could handle the parsing much more quickly (mostly because it avoided the tooling learning curve). It may not be the final solution, but it's one that works well enough to serve as a place holder until the rest of the tech proves out.

&lt;p&gt;Don't get me wrong, this does not mean, hack up the simplest bit of code to get the job done. A straight path to the solution is likely to result in an unmaintainable mess. &lt;b&gt;Certain standards of code quality need to be met&lt;/b&gt;, so that you can still test the result and be able to refactor it without starting from scratch. But if you meet that criteria, getting it done fast first, buys you the time to evaluate whether a) the problem you're solving is the right problem, b) the solution provided is sufficient for the intended use and c) whether the shiny tech really would improve the implementation.

&lt;p&gt;Determining whether a path is just &lt;i&gt;shiny&lt;/i&gt; or appropriate isn't always easy. One bit of tech that's been consuming a bit more time than I wish, is basing my persistence story on NHibernate, instead of rolling my own. The temptation to &lt;b&gt;use what I know&lt;/b&gt; is strong, but fortunately (or &lt;i&gt;unfortunately&lt;/i&gt;?), I have enough experience from rolling my own ORM and hand-coded SQL to know that down that road lies &lt;i&gt;madness&lt;/i&gt;. So, be sure &lt;b&gt;not to mistake "learning curve" for yagni&lt;/b&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-5765564640629937859?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2009/09/teh-shiny.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-8466080001638868216</guid><pubDate>Wed, 02 Sep 2009 04:47:00 +0000</pubDate><atom:updated>2009-09-01T22:44:49.514-07:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>tags</category><category domain='http://www.blogger.com/atom/ns#'>lambda</category><category domain='http://www.blogger.com/atom/ns#'>linq</category><category domain='http://www.blogger.com/atom/ns#'>c#</category><category domain='http://www.blogger.com/atom/ns#'>boolean algebra</category><title>Boolean Algebra for Tag queries</title><description>Currently working on a tag query engine and couldn't find anything all that useful in the published approaches. I want to do arbitrary boolean algebras against a set of tags in a database, which seems to be out of scope of SQL approaches. All the various tagging schemas out there reduce to either just &lt;b&gt;AND&lt;/b&gt; or just &lt;b&gt;OR&lt;/b&gt; queries, but not complex logic. However, I want to be able to do something like:
&lt;pre class="brush: csharp;"&gt;
(foo+bar)|(foo+baz)|(bar+^baz)
&lt;/pre&gt;
If there is a way to do this with SQL, i'd love to know. But the way i look at it, i really have to fetch all tags for each item and then do apply that formula to the list of tags on the item.

&lt;p&gt;But let's break down the matching problem itself into something i can execute. Let's assume I've got a simple parser that can turn the above into an AST. Really, i can decompose any variation into three operations, &lt;b&gt;AND(a,b)&lt;/b&gt;, &lt;b&gt;OR(a,b)&lt;/b&gt; and &lt;b&gt;NOT(a)&lt;/b&gt;. And I can represent those with some simple Func&amp;lt;&amp;gt; definitions:

&lt;pre class="brush: csharp;"&gt;
Func&amp;lt;bool, bool, bool&amp;gt; AND = (a, b) =&amp;gt; a &amp;amp;&amp;amp; b;
Func&amp;lt;bool, bool, bool&amp;gt; OR = (a, b) =&amp;gt; a || b;
Func&amp;lt;bool, bool&amp;gt; NOT = (a) =&amp;gt; !a;
&lt;/pre&gt;

Assuming that i have boolean tokens for &lt;i&gt;foo&lt;/i&gt;, &lt;i&gt;bar&lt;/i&gt; and &lt;i&gt;baz&lt;/i&gt;, the expressions becomes:

&lt;p&gt;&lt;b&gt;OR&lt;/b&gt;(&lt;b&gt;AND&lt;/b&gt;(&lt;i&gt;foo, bar&lt;/i&gt;), &lt;b&gt;OR&lt;/b&gt;(&lt;b&gt;AND&lt;/b&gt;(&lt;i&gt;foo, baz&lt;/i&gt;), &lt;b&gt;AND&lt;/b&gt;(&lt;i&gt;bar&lt;/i&gt;,&lt;b&gt;NOT&lt;/b&gt;(&lt;i&gt;baz&lt;/i&gt;))))

&lt;p&gt;Now, the above expression can be expressed as a function that takes three booleans describing the presence of the mentioned tags, ignoring any other tags that the item has, returning a boolean indicating a successful match. In C# that expression would look like this:

&lt;pre class="brush: csharp;"&gt;
Func&amp;lt;bool[], bool&amp;gt; f = x =&amp;gt; OR(AND(x[0], x[1]), OR(AND(x[0], x[2]), AND(x[1],NOT(x[2]))));
&lt;/pre&gt;

&lt;p&gt;Next we need to generate this boolean map from the list of tags on the item. Assuming that the tag list is a list of strings, we can define an extension methods on IEnumerable&amp;lt;string&amp;gt; to generate the boolean map like this:

&lt;pre class="brush: csharp;"&gt;
public static bool[] GetBinaryMap(this IEnumerable&amp;lt;string&amp;gt; tags, string[] mask) {
    var map = new bool[mask.Length];
    foreach(var x in tags) {
        for(var i = 0; i &amp;lt; mask.Length; i++) {
            if(x == mask[i]) {
                map[i] = true;
            }
        }
    }
    return map;
}
&lt;/pre&gt;

And with this we can define a linq query that will return us all matching items:
&lt;pre class="brush: csharp;"&gt;
var mask = new[] { &amp;quot;foo&amp;quot;, &amp;quot;bar&amp;quot;, &amp;quot;baz&amp;quot;};
Func&amp;lt;bool[], bool&amp;gt; f = x =&amp;gt; OR(AND(x[0], x[1]), OR(AND(x[0], x[2]), AND(x[1],NOT(x[2]))));
var match = from item in items
            where f(item.Tags.GetBinaryMap(mask))
            select item;
&lt;/pre&gt;

&lt;p&gt;Clearly this is isn't the fastest executing query, since we first had to create our items, each item in which has a collection of tags. But there is a lot of optimizations left on the table here, such as using our tag mask to pre-qualify items, breaking down the AST into sub-matches that could be used against a cache to find items, etc.

&lt;p&gt;But at least we have a fairly simple way to take complex boolean algebra on tags and convert them into something that we can evaluate generically&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-8466080001638868216?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2009/09/boolean-algebra-for-tag-matching.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-8423560480638013899</guid><pubDate>Mon, 24 Aug 2009 00:21:00 +0000</pubDate><atom:updated>2009-08-23T17:21:00.461-07:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>lambda</category><category domain='http://www.blogger.com/atom/ns#'>tdd</category><category domain='http://www.blogger.com/atom/ns#'>moq</category><category domain='http://www.blogger.com/atom/ns#'>autofac</category><title>Setting up mocks for an inner autofac container</title><description>This is definitely an edge case testing scenario, so i don't know how useful this utility class is in general, but i thought it was kinda fun deferred execution stuff, so why not post it?

&lt;p&gt;Here's my scenario. I've built some &lt;a href="http://developer.mindtouch.com/dream"&gt;Dream&lt;/a&gt; REST services that i've set up to create an inner &lt;a href="http://code.google.com/p/autofac/"&gt;Autofac&lt;/a&gt; container per request to create per request instances of objects -- things like NHibernate ISession and other disposable resources that only make sense in a per request context.

&lt;p&gt;Now i'm writing my unit tests around these services, and need to provide mocks for these inner container created objects. I should also mention that to test the services, i am firing up a &lt;code&gt;DreamHost&lt;/code&gt;, since the services can only be tested in the context of the full pipeline. Yeah, i know, smells a bit functional, but that's what I have to work with right now. And i need these objects to be &lt;code&gt;ContainerScoped&lt;/code&gt; (i.e. per inner container singletons), so that multiple &lt;code&gt;Resolve&lt;/code&gt;'s return the same instance, but still return different instances on multiple requests. &lt;i&gt;Ok, ok, i know the tests are doing too much...&lt;/i&gt; Like i said, this is an edge case. It's not strictly a unit test, but i still want coverage on this code. Getting around this would require refactoring of code that's not part of my project, so there you go.

&lt;p&gt;What I want to do is set up the mock for the inner container instance on creation, which doesn't happen until i've handed over execution control to the &lt;b&gt;Act&lt;/b&gt; part of the test. This lead me to create a factory that provides a hook for setting up the mock on creation of the mock:

&lt;pre class="brush: csharp;"&gt;
public class DelegatedMoqFactory&amp;lt;T&amp;gt; where T : class
{
 private Action&amp;lt;Mock&amp;lt;T&amp;gt;, IContext&amp;gt; setupCallback;
 private Mock&amp;lt;T&amp;gt; mock;

 public Mock&amp;lt;T&amp;gt; CurrentMock { get { return mock; } }

 public T CreateInstance(IContext container)
 {
  mock = new Mock&amp;lt;T&amp;gt;();
  if (setupCallback != null)
  {
   setupCallback(mock, container);
  }
  return mock.Object;
 }

 public void OnResolve(Action&amp;lt;Mock&amp;lt;T&amp;gt;, IContext&amp;gt; setupCallback)
 {
  this.setupCallback = setupCallback;
 }
}
&lt;/pre&gt;

A sample autofac wire-up looks like this:

&lt;pre class="brush: csharp;"&gt;
builder.RegisterGeneric(typeof(DelegatedMoqFactory&amp;lt;&amp;gt;));
builder.Register(c =&amp;gt; c.Resolve&amp;lt;DelegatedMoqFactory&amp;lt;IAuthService&amp;gt;&amp;gt;().CreateInstance(c))
    .ContainerScoped();
&lt;/pre&gt;

With a test setup of the IAuthService being done like this:
&lt;pre class="brush: csharp;"&gt;
container.Resolve&amp;lt;DelegatedMoqFactory&amp;lt;IAuthService&amp;gt;&amp;gt;()
    .OnResolve(m =&amp;gt; m.Setup(x =&amp;gt;
        x.AuthenticateAndGetAccountId(&amp;quot;authtoken&amp;quot;)).Returns(1234);
&lt;/pre&gt;

The open generic of &lt;code&gt;DelegateMoqFactory&lt;/code&gt; is registered with default scope, since i want it to exist outside the inner scope, so that i can resolve it to wire up my expectations for the mock. Then on the first access for &lt;code&gt;IAuthService&lt;/code&gt; inside the inner scope, the &lt;code&gt;DelegateMoqFactory&lt;/code&gt; creates the mock and calls my &lt;code&gt;OnResolve&lt;/code&gt; callback to set up the mock.

&lt;p&gt;The reason there is also a &lt;code&gt;CurrentMock&lt;/code&gt; accessor is so that I can do verification on the mock after the inner container has gone out of scope, like this:
&lt;pre class="brush: csharp;"&gt;
container.Resolve&amp;lt;DelegatedMoqFactory&amp;lt;IAuthService&amp;gt;&amp;gt;()
    .CurrentMock.Verify(x =&amp;gt;
        x.CreateAuthToken(It.IsAny&amp;lt;IAccount&amp;gt;()), Times.Never());
&lt;/pre&gt;

&lt;p&gt;This class should be useful whenever you are testing some code that internally creates an inner container and scoping the objects usually created under &lt;code&gt;ContainerScope&lt;/code&gt; as default scope doesn't work (likely because there's multiple inner containers). We still get per inner container instances, but get to wire them up with deferred setups that don't come into play until the mocks are actually pulled from the inner container.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-8423560480638013899?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2009/08/setting-up-mocks-for-inner-autofac.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-7160565482551375010</guid><pubDate>Sun, 23 Aug 2009 02:01:00 +0000</pubDate><atom:updated>2009-08-22T22:24:14.281-07:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>mock</category><category domain='http://www.blogger.com/atom/ns#'>tdd</category><category domain='http://www.blogger.com/atom/ns#'>moq</category><category domain='http://www.blogger.com/atom/ns#'>dream</category><title>Moq rocks</title><description>Ok, so i'm not proud of it, but i've been a hold-out on mocking frameworks for a while. With the auto-gen of interfaces that resharper gives me, i'd just gotten pretty fast at rolling my own mocks. Once or twice a year, i'd dip my toe into a mocking framework, find its syntax frustrating and rather than get a good used to it, I'd soon find myself replacing &lt;code&gt;NotImplementedException&lt;/code&gt; in a stub for yet another custom Mock object.

&lt;p&gt;My reasoning was that if i can roll my mocks just as fast as wiring up a mock, then why bother with the dependency. And I thought I wasn't really causing myself too much extra work.

&lt;/p&gt;&lt;p&gt;In the meantime, I even wrote a simple &lt;a href="http://blog.developer.mindtouch.com/2009/05/18/consuming-rest-services-and-tdd-with-plug/"&gt;Arrange/Act/Assert mocking harness&lt;/a&gt; for &lt;a href="http://developer.mindtouch.com/dream"&gt;Dream&lt;/a&gt;, so i could better test REST services. So, it's not like i didn't believe in the benefits of mocking harnesses.

&lt;/p&gt;&lt;p&gt;Well, for the last couple of weeks, I've been using &lt;a href="http://code.google.com/p/moq/"&gt;Moq&lt;/a&gt; and it's pretty much killed off all my desire to roll my own. I'm generally a huge fan of lambdas and have gotten used thinking in expressions. Although even with that, I wasn't able to get comfortable with the latest &lt;a href="http://ayende.com/projects/rhino-mocks.aspx"&gt;Rhino.Mocks&lt;/a&gt;. Probably just me. But from the very first attempt, Moq worked like i think and I was up and running.

&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;
var mock = new Mock&lt;ifoo&gt;();
mock.Setup(x=&gt; x.Bar).Returns("bar").AtMostOnce();
var foo = mock.Object;
Assert.AreEqual("bar",foo.Bar);
&lt;/ifoo&gt;&lt;/pre&gt;
I'm a convert!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-7160565482551375010?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2009/08/moq-rocks.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-3661073666829205581</guid><pubDate>Fri, 21 Aug 2009 21:45:00 +0000</pubDate><atom:updated>2009-08-21T15:20:10.424-07:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>tdd</category><category domain='http://www.blogger.com/atom/ns#'>moq</category><category domain='http://www.blogger.com/atom/ns#'>autofac</category><title>Using TDD to learn new code</title><description>When I pick up a new framework or library, there's usually that learning curve where I get familiar with its API, find what works, what doesn't work, etc. One habit I've gotten into is that I create a &lt;code&gt;TestFixture&lt;/code&gt; for everything i think i should be able to do and build a test for that assumption. The purpose of these tests is both to make sure the code does what I expect it to, but also to serve as a record of what I've already learned. If i later on wonder how some call would function, i first check my test signatures, to see if i've already tested that behavior. If there is an appropriate test, I immediately know what the behavior will be, plus i now have working sample code or how to do it.

&lt;p&gt;For example, I was playing around with setting up &lt;a href="http://code.google.com/p/moq/"&gt;Moq&lt;/a&gt;'s through &lt;a href="http://code.google.com/p/autofac/"&gt;Autofac&lt;/a&gt; and wanted to come up with a registration that would give me a container scoped Moq object that i could set up before executing a particular test. The resulting test looked like this:

&lt;pre class="brush: csharp;"&gt;
public interface IMockWithAccessor
{
 IMockAccessorValue Accessor { get; }
}
public interface IMockAccessorValue
{
 string Foo { get; }
}

[Test]
public void Create_nested_mock_so_it_can_be_altered_in_container_scope()
{
 var builder = new ContainerBuilder();
 builder.Register(c =&amp;gt; new Mock&amp;lt;IMockAccessorValue&amp;gt;())
  .As&amp;lt;Mock&amp;lt;IMockAccessorValue&amp;gt;&amp;gt;().ContainerScoped();
 builder.Register(c =&amp;gt; c.Resolve&amp;lt;Mock&amp;lt;IMockAccessorValue&amp;gt;&amp;gt;().Object)
  .As&amp;lt;IMockAccessorValue&amp;gt;().ContainerScoped();
 builder.Register(c =&amp;gt;
 {
  var mockBuilder = new Mock&amp;lt;IMockWithAccessor&amp;gt;();
  mockBuilder.Setup(x =&amp;gt; x.Accessor)
                       .Returns(c.Resolve&amp;lt;IMockAccessorValue&amp;gt;());
  return mockBuilder.Object;
 }).As&amp;lt;IMockWithAccessor&amp;gt;().ContainerScoped();

 using (var container = builder.Build().CreateInnerContainer())
 {
  var mockAccessorBuilder = container
                     .Resolve&amp;lt;Mock&amp;lt;IMockAccessorValue&amp;gt;&amp;gt;();
  mockAccessorBuilder.Setup(x =&amp;gt; x.Foo).Returns(&amp;quot;bar&amp;quot;);
  Assert.AreEqual(&amp;quot;bar&amp;quot;, container
                     .Resolve&amp;lt;IMockWithAccessor&amp;gt;().Accessor.Foo);
 }
}
&lt;/pre&gt;

&lt;p&gt;Sometimes, of course, my expectations are not met and the code does not allow me to do what i set out to do. These test are even more valuable for future reference, as long as i make sure to rename the test to reflect the failed expectation, and alter the asserts to reflect the actual behavior.

&lt;p&gt;I was trying to figure out parametrized component registrations in Autofac. The example showed it being used with &lt;code&gt;FactoryScope&lt;/code&gt;. I wondered whether, in default (Singleton) scope, Autofac would use the parameters to create singletons per parameter set. My original test was named &lt;b&gt;Parametrized_resolve_creates_different_singleton_per_parameter_Value&lt;/b&gt;. Well, it turned out that, &lt;i&gt;no, autofac does not vary singletons, and parametrized registrations only make sense in &lt;code&gt;FactoryScope&lt;/code&gt;&lt;/i&gt;. The final test looks like this:

&lt;pre class="brush: csharp;"&gt;
public class ParametrizedSingleton { }
[Test]
public void Parametrized_resolve_without_factory_scope_is_always_a_singleton()
{
 var builder = new ContainerBuilder();
 builder.Register((c, p) =&amp;gt; new ParametrizedSingleton());
 using (var container = builder.Build())
 {
  var foo1 = container.Resolve&amp;lt;ParametrizedSingleton&amp;gt;(
                     new NamedParameter(&amp;quot;type&amp;quot;, &amp;quot;foo&amp;quot;));
  var foo2 = container.Resolve&amp;lt;ParametrizedSingleton&amp;gt;(
                     new NamedParameter(&amp;quot;type&amp;quot;, &amp;quot;foo&amp;quot;));
  var bar1 = container.Resolve&amp;lt;ParametrizedSingleton&amp;gt;(
                     new NamedParameter(&amp;quot;type&amp;quot;, &amp;quot;bar&amp;quot;));
  Assert.AreSame(foo1, foo2);
  Assert.AreSame(foo1, bar1);
 }
}
&lt;/pre&gt;

&lt;p&gt;I usually keep these test fixtures in a separate test project in my solution as permanent reference, as i continue to develop the main code. It's proven useful a number of times when coming back to some old code and having to reacquaint myself with a third party bit of code.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-3661073666829205581?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2009/08/using-tdd-to-learn-new-code.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-6735694430926980917</guid><pubDate>Mon, 22 Jun 2009 01:05:00 +0000</pubDate><atom:updated>2009-06-21T18:21:47.605-07:00</atom:updated><title>Designing a Delegate Injection Container</title><description>In &lt;a href="http://www.claassen.net/geek/blog/2009/06/ultimate-interface-segregation.html"&gt;my last post&lt;/a&gt; I proposed using delegates instead of interfaces to declare dependencies for injection. While delegates are limited to a single function call, this is often sufficient for service dependencies. In addition, this is not a wholesale replacement for traditional IoC, since at the end of the day, you have to have some class instances that provide the methods bound by the delegates and want to return instances require those delegates, so our container will still need to resolve class instances.

&lt;p&gt;The main benefit of using delegates instead of interfaces is that delegates do not impose any requirements on the providing class, and thereby dependencies can be defined by what the client needs rather than what a service provides.

&lt;h2&gt;Mapping Delegate Dependencies&lt;/h2&gt;

&lt;p&gt;To illustrate this mapping, let's bring back the classes defined in the &lt;a href="http://www.claassen.net/geek/blog/2009/06/ultimate-interface-segregation.html"&gt;last post&lt;/a&gt;:

&lt;pre class="brush: csharp;"&gt;
public class MessageQueue
{
 public void Enqueue(string recipient, string message) { ... }
 public string TryDequeue(string recipient) { ... }
}

public class Producer : IProducer
{
 public delegate void EnqueueDelegate(string recipient, string message);
 public Producer(EnqueueDelegate dispatcher) { ... }
}

public class Consumer : IConsumer
{
 public delegate string TryDequeueDelegate(string recipient);
 public Consumer(TryDequeueDelegate inbox) { ... }
}
&lt;/pre&gt;

&lt;p&gt;What we need is a way to map a delegate to a method:
&lt;pre class="brush: csharp;"&gt;
EnqueueDelegate =&amp;gt; MessageQueue.Enqueue
TryDequeueDelegate =&amp;gt; MessageQueue.TryDequeue
&lt;/pre&gt;

Aside from the fact that the above is not a legal C# syntax, the above has the implicit assumption that we can resolve a canonical instance of &lt;code&gt;MessageQueue&lt;/code&gt;, since &lt;code&gt;MessageQueue.Enqueue&lt;/code&gt; really refers to a method on an instance of &lt;code&gt;MessageQueue&lt;/code&gt;. I.e. our container must function like a regular IoC container so we can resolve that instance.

&lt;p&gt;The above solves the scenario of a mapping one delegate to one implementation. In addition, we'd probably want the flexibility to map a particular implementation to a particular client class, such that:

&lt;pre class="brush: csharp;"&gt;
Producer =&amp;gt;
  EnqueueDelegate =&amp;gt; MessageQueue.Enqueue
Consumer =&amp;gt;
  TryDequeueDelegate =&amp;gt; MessageQueue.TryDequeue
&lt;/pre&gt;

&lt;h2&gt;Using Expressions to capture delegate mappings&lt;/h2&gt;

&lt;p&gt;The usage scenarios described are simple enough to understand. If our container were initialized using strings or some external configuration file (Xml, custom DSL, etc.), the actual reflection required for the injection of mappings isn't too complex either. However, I abhor defining typed mappings without type-safety. This is isn't so much about making mistakes in spelling, etc. that the compiler can't catch. It is mostly about being able to navigate the mappings and the dependencies they describe and the ability to refactor while keeping the mappings in sync.

&lt;p&gt;It would be great if we could just say:
&lt;blockquote&gt;&lt;i&gt;&lt;b&gt;Note:&lt;/b&gt; I'm purposely using a syntax that mimics &lt;a href="http://code.google.com/p/autofac/"&gt;Autofac&lt;/a&gt;, since the implementation later on will be done as a hack on top of Autofac&lt;/i&gt;&lt;/blockquote&gt;
&lt;pre class="brush: csharp;"&gt;
builder.Define&amp;lt;Producer.EnqueueDelegate&amp;gt;.As&amp;lt;MessageQueue.Enqueue&amp;gt;();
&lt;/pre&gt;
&lt;p&gt;That looks fine and could even work in the face of polymorphism, since knowing the signature of &lt;code&gt;Producer.EnqueueDelegate&lt;/code&gt; we could reflect the proper overload of &lt;code&gt;MessageQueue.Enqueue&lt;/code&gt;. However, C# has no syntax for getting at the &lt;code&gt;MethodInfo&lt;/code&gt; of a method via Generics (it is not a type). There isn't even an equivalent to &lt;code&gt;typeof(T)&lt;/code&gt; for members, the reason for which was well explained by Eric Lippert in &lt;a href="http://blogs.msdn.com/ericlippert/archive/2009/05/21/in-foof-we-trust-a-dialogue.aspx"&gt;In Foof We Trust: A Dialogue&lt;/a&gt;. The only way to get &lt;code&gt;MethodInfo&lt;/code&gt; relies on string based reflection. 

&lt;p&gt;Fortunately, C#3.0 introduced a syntax that allows us to capture method calls as expression trees that we can decompose programatically. This lets us to express our method call like this:

&lt;pre class="brush: csharp;"&gt;
MessageQueue messageQueue = new MessageQueue();
Expression&amp;lt;Producer.EnqueueDelegate&amp;gt; expr = (a,b) =&amp;gt; messageQueue.Enqueue(a,b);
&lt;/pre&gt;

This expression conveniently infers the type of &lt;b&gt;a&lt;/b&gt; and &lt;b&gt;b&lt;/b&gt;. As a sidenote, &lt;code&gt;Producer.EnqueueDelegate&lt;/code&gt; does not mean that &lt;code&gt;EnqueueDelegate&lt;/code&gt; is a member of &lt;code&gt;Producer&lt;/code&gt;. It's just a syntax artifact of nested declarations in C#, which in this case conveniently makes the delegate look attached to the class.

&lt;p&gt;Unfortunately, there we can't just include &lt;code&gt;MessageQueue&lt;/code&gt; in the parameter list of the lambda. If we were to include it in the argument list, it could not be inferred, and if we were to define &lt;code&gt;MessageQueue&lt;/code&gt; explicitly as a lambda parameter, then we'd be forced to declare all arguments. We want to express the above and only explicitly define &lt;code&gt;MessageQueue&lt;/code&gt;. To accomplish this we need to create a composite expression that previously was told about &lt;code&gt;MessageQueue&lt;/code&gt;:

&lt;pre class="brush: csharp;"&gt;
Expression&amp;lt;Func&amp;lt;MessageQueue, Expression&amp;lt;Producer.EnqueueDelegate&amp;gt;&amp;gt;&amp;gt; expr
  = x =&amp;gt; (a,b)=&amp;gt; messageQueue.Enqueue(a,b);
&lt;/pre&gt;

Now we have enough syntactic sugar to describe our two registration scenarios in terms of the container builder. First, the global registration of the delegate against an implementation:
&lt;pre class="brush: csharp;"&gt;
builder.Define&amp;lt;Consumer.TryDequeueDelegate&amp;gt;()
  .As&amp;lt;MessageQueue&amp;gt;(x =&amp;gt; a =&amp;gt; x.TryDequeue(a));
builder.Define&amp;lt;Producer.EnqueueDelegate&amp;gt;()
  .As&amp;lt;MessageQueue&amp;gt;(x =&amp;gt; (a, b) =&amp;gt; x.Enqueue(a, b));
&lt;/pre&gt;
And alternately, the registration of delegates and their implementation in the context of a particular class:
&lt;pre class="brush: csharp;"&gt;
builder.Register&amp;lt;Consumer&amp;gt;().As&amp;lt;IConsumer&amp;gt;()
  .With&amp;lt;Consumer.TryDequeueDelegate&amp;gt;()
  .As&amp;lt;MessageQueue&amp;gt;(x =&amp;gt; a =&amp;gt; x.TryDequeue(a));

builder.Register&amp;lt;Producer&amp;gt;().As&amp;lt;IProducer&amp;gt;()
  .With&amp;lt;Producer.EnqueueDelegate&amp;gt;()
  .As&amp;lt;MessageQueue&amp;gt;(x =&amp;gt; (a, b) =&amp;gt; x.Enqueue(a, b));
&lt;/pre&gt;

Next time, I'll go over the implementation of the above to get it working as an injection framework.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-6735694430926980917?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2009/06/designing-delegate-injection-container.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-1135416927809144</guid><pubDate>Sat, 20 Jun 2009 05:00:00 +0000</pubDate><atom:updated>2009-06-21T18:18:26.765-07:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>IoC</category><category domain='http://www.blogger.com/atom/ns#'>c#</category><category domain='http://www.blogger.com/atom/ns#'>SOLID</category><category domain='http://www.blogger.com/atom/ns#'>delegate</category><title>Ultimate Interface Segregation: Dependency injection by Delegate</title><description>&lt;p&gt;I've been on a bit of a tear about declaring dependency contracts and injecting only what is required. While examining the use of Interfaces in IoC and their shortcomings, I decided that taken to the extreme, dependencies come down to call dependencies, which could be modeled with delegates rather than interfaces. Instead of writing a novel, as I've been prone to, i thought I'd do a shorter post on my approach to this solution, and expand on the implementation in later posts.

&lt;p&gt;To recap, in the &lt;a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod"&gt;SOLID&lt;/a&gt; principles, the &lt;b&gt;Interface Segregation Principle&lt;/b&gt; states: &lt;i&gt;&lt;b&gt;Clients should not be forced to depend upon interfaces that they do not use&lt;/b&gt;&lt;/i&gt;. This means that interfaces should be fine-grained enough to expose no more than one responsibility. Taken to the extreme, this could be taken to mean that each interface only has a single method. There are valid &lt;a href="http://en.wikipedia.org/wiki/Single_responsibility_principle"&gt;SRP &lt;/a&gt; scenarios where a responsibility is modeled by more than one call, but let's start with the simplest scenario first, then see how well it applies to more complex responsibilities later.

&lt;p&gt;In C# we have delegates, which describe a single method call. A delegate instance is a reference to a method that encapsulates a specific instance of a class, without exposing the underlying class (unless your delegate is a static method). A delegate can even be used to expose &lt;code&gt;internal&lt;/code&gt;, &lt;code&gt;protected&lt;/code&gt; and &lt;code&gt;private&lt;/code&gt; methods.

&lt;p&gt;Instead of declaring a list of interfaces that the IoC container should inject, classes would define their dependencies as delegates. Taking the example from &lt;a href="http://www.claassen.net/geek/blog/2009/06/c-duck-typing-to-rescue-for.html"&gt;my duck typing post&lt;/a&gt;, we would get the following dependency declarations.

&lt;p&gt;First, we have the same service provider, &lt;code&gt;MessageQueue&lt;/code&gt;, which still doesn't need to implement an interface:

&lt;pre class="brush: csharp;"&gt;
public class MessageQueue
{
 public void Enqueue(string recipient, string message) { ... }
 public string TryDequeue(string recipient) { ... }
}
&lt;/pre&gt;
Next, we have the new &lt;code&gt;Producer&lt;/code&gt;, now declaring its dependency has a delegate:
&lt;pre class="brush: csharp;"&gt;
public class Producer : IProducer
{
 public delegate void EnqueueDelegate(string recipient, string message);
 public Producer(EnqueueDelegate dispatcher) { ... }
}
&lt;/pre&gt;
And finally, we have the new &lt;code&gt;Consumer&lt;/code&gt;, also declaring a delegate for construction time injection:
&lt;pre class="brush: csharp;"&gt;
public class Consumer : IConsumer
{
 public delegate string TryDequeueDelegate(string recipient);
 public Consumer(TryDequeueDelegate inbox) { ... }
}
&lt;/pre&gt;

&lt;p&gt;Think of the delegate as your &lt;b&gt;Method Interface&lt;/b&gt;. You could define your dependencies as &lt;code&gt;Func&lt;/code&gt;'s and &lt;code&gt;Action&lt;/code&gt;'s, but that would obfuscate your dependencies beyond recognition in most scenarios. By using an explicit delegate, you get to attach the dependency to the class that has the dependency, in addition to having a descriptive signature.

&lt;p&gt;Now, if we were to wire this up manually we'd get something like this:

&lt;pre class="brush: csharp;"&gt;
var queue = new MessageQueue();
IProducer producer = new Producer(queue.Enqueue); 
IConsumer consumer = new Consumer(queue.TryDequeue);
&lt;/pre&gt;

That's simple enough, but not really very scalable, once you get a lot of dependencies to wire up. What we really need is an IoC container that let's us register delegates against classes, instead of having to have instances at dependency declaration time. Delegates can't be cast from one to another and are not, strictly speaking, types, which posts some challenges with creating a type-safe registration interface. There are a number of ways to accomplish this syntax, which I will elaborate on in &lt;a href="http://www.claassen.net/geek/blog/2009/06/designing-delegate-injection-container.html"&gt;my next post&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-1135416927809144?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2009/06/ultimate-interface-segregation.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-8892271901849894528</guid><pubDate>Thu, 18 Jun 2009 06:00:00 +0000</pubDate><atom:updated>2009-06-19T22:10:06.074-07:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>Dynamic Proxy</category><category domain='http://www.blogger.com/atom/ns#'>Castle</category><category domain='http://www.blogger.com/atom/ns#'>interface</category><category domain='http://www.blogger.com/atom/ns#'>LinFu</category><category domain='http://www.blogger.com/atom/ns#'>c#</category><title>C# duck-typing to the rescue for  Interface Segregation</title><description>Interfaces are the method by which we get multiple inheritance in C#, Java, etc. They are contracts without implementation. We don't get the messy resolution of which code to use from multiple base classes, because there's only one inheritance chain that includes code.

&lt;p&gt;They're useful to let us provide one contract and multiple implementations or simply describe a contract for our code and allow someone else to come along and replace our implementation entirely.

&lt;p&gt;In practice, though, I almost always use them purely for decoupling the contract from the code, so that I can replace the implementation with a mock version in unit tests. &lt;i&gt;Hmm..&lt;/i&gt; So, I use interfaces just to get around the yoke of the type system? Wait, why I am so in love with statically typed languages again?

&lt;p&gt;&lt;i&gt;Right...&lt;/i&gt; While the above sounds like the interface exists just so that I can mock my implementation, the real purpose of the interface is the ability for the consuming code to express a contract for its dependencies. It's unfortunate that interface implementation forces them to be attached at the implementation side, which is why I say that &lt;a href="http://www.claassen.net/geek/blog/2009/06/interfaces-put-contract-at-wrong-end-of.html"&gt;Interface attachment is upside down&lt;/a&gt;. And it's deep rooted in the language, after all it's called &lt;b&gt;Interface Inheritance&lt;/b&gt; not &lt;b&gt;Dependency Contract Definition&lt;/b&gt;.

&lt;h2&gt;Dynamic Proxy&lt;/h2&gt;

&lt;p&gt;So, it's not surprising that there is no CLR-level way around this limitation. Fortunately, you can always create a dynamic proxy that wraps your class and implements the Interface. Both &lt;a href="http://www.castleproject.org/"&gt;Castle&lt;/a&gt;'s &lt;code&gt;DynamicProxy&lt;/code&gt; and &lt;a href="http://code.google.com/p/linfu/"&gt;LinFu&lt;/a&gt;'s &lt;code&gt;DynamicProxy&lt;/code&gt; are excellent frameworks for writing your own proxies. I've never tested them against each other, but have used both in production and neither showed up as culprits when time for profiling came about.

&lt;p&gt;With a dynamic proxy, you can generate an object that claims to implement an interface but under the hood just has a interceptors that provide the call signature to let you respond correctly or proxy the call on to a class you are wrapping. I've &lt;a href="http://www.claassen.net/geek/blog/2007/10/dynamicproxy-rocks.html"&gt;previously covered&lt;/a&gt; how you can even use them to have a class inherit from more than one base class via a proxy. This is necessary if you want to remote an object, which requires a base of &lt;code&gt;MarshalByRefObject&lt;/code&gt;, but you already have a base class.

&lt;p&gt;However, proxies require a fair bit of hand-rolling so they are not the most lightweight way, development time wise, to attach an Interface.

&lt;h2&gt;Duck Typing&lt;/h2&gt;

&lt;p&gt;What would be really useful would be the ability to cast an object to an interface:

&lt;pre class="brush: csharp;"&gt;
IUser user = new User() as IUser;
&lt;/pre&gt;

&lt;p&gt;The above code would even be compile time verifiable, since we can simply see if the &lt;code&gt;User&lt;/code&gt; implements the call signatures promised by &lt;code&gt;IUser&lt;/code&gt;. This would be provide us strongly typed &lt;a href="http://en.wikipedia.org/wiki/Duck_typing"&gt;Duck Typing&lt;/a&gt; -- an object that can &lt;i&gt;quack&lt;/i&gt; ought to be able to be treated as a duck.

&lt;p&gt;This is where LinFu goes a step further than just &lt;code&gt;DynamicProxy&lt;/code&gt; and provides duck typing as well:

&lt;pre class="brush: csharp;"&gt;
IUser user = DynamicObject(new User()).CreateDuck&amp;lt;IUser&amp;gt;();
&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;DynamicObject&lt;/code&gt;'s constructor takes an instance of a class to wrap. You can then create a duck from that dynamic object which automatically proxies the given interface and will call the appropriate method on the wrapped class on demand.

&lt;h2&gt;Using duck typing to satisfy the Interface Segregation Principle&lt;/h2&gt;

&lt;p&gt;Saying that you may have a class that has the perfect method signature but doesn't implement an interface you already have, does sound rather contrived. However, forcing a class to implement an interface of your choosing does have some real benefits, aside from being able to abstract an existing class into a mockable dependency:

&lt;blockquote&gt;&lt;i&gt;&lt;a href="http://www.lostechies.com/blogs/rhouston/archive/2008/03/14/ptom-the-interface-segregation-principle.aspx"&gt;Clients should not be forced to depend upon interfaces that they do not use&lt;/a&gt;&lt;/i&gt;&lt;/blockquote&gt;

One problem with interfaces is that they tell you everything an implementation can do. And often a class acts as a service that provides functionality to more than one client class, but provides just a single interface. That single interface may expose capabilities that you don't care about.

&lt;p&gt;Instead, interfaces should be fine-grained to only include the methods appropriate to the client. But that's not always feasible. Aside from having a class implement lots of tiny interfaces, the service class does not know about the client's requirements, so it really doesn't know what the interfaces should include. The client, on the other hand, does know and can tailor exactly the right interface it wants as a contract with the dependency.

&lt;p&gt;Suppose we have message queue for passing data between decoupled classes:

&lt;pre class="brush: csharp;"&gt;
public class MessageQueue
{
 public void Enqueue(string recipient, string message) { ... }
 public string TryDequeue(string recipient) { ... }
}
&lt;/pre&gt;

Proper interface segregation would have us create a Dispatcher interface for our message Producer
&lt;pre class="brush: csharp;"&gt;
public interface IMessageDispatcher
{
 void Enqueue(string recipient, string message);
}

public class Producer : IProducer
{
 public Producer(IMessageDispatcher dispatcher) { ... }
}
&lt;/pre&gt;
and an inbox interface for our message Consumer
&lt;pre class="brush: csharp;"&gt;
public interface IMessageBox
{
 string TryDequeue(string recipient);
}

public class Consumer : IConsumer
{
 public Consumer(IMessageBox inbox) { ... }
}
&lt;/pre&gt;
Assuming that &lt;code&gt;MessageQueue&lt;/code&gt; does not implement our interfaces &lt;i&gt;(yes, in this case it would not have been a problem to have the class implement them both, but this is a simplified example with obvious segregation lines)&lt;/i&gt;, we can now configure our IoC container (example uses &lt;a href="http://code.google.com/p/autofac/"&gt;AutoFac&lt;/a&gt;) to create the appropriately configured IProducer and IConsumer, each receiving exactly those capabilities they should depend on:
&lt;pre class="brush: csharp;"&gt;
var queue = new MessageQueue();
var builder = new ContainerBuilder();
builder.Register&amp;lt;Producer&amp;gt;().As&amp;lt;IProducer&amp;gt;();
builder.Register&amp;lt;Consumer&amp;gt;().As&amp;lt;IConsumer&amp;gt;();
builder.Register(c =&amp;gt; new DynamicObject(queue).CreateDuck&amp;lt;IMessageDispatcher&amp;gt;()).As&amp;lt;IMessageDispatcher&amp;gt;();
builder.Register(c =&amp;gt; new DynamicObject(queue).CreateDuck&amp;lt;IMessageBox&amp;gt;()).As&amp;lt;IMessageBox&amp;gt;();

using (var container = builder.Build())
{
 var producer = container.Resolve&amp;lt;IProducer&amp;gt;();
 var consumer = container.Resolve&amp;lt;IConsumer&amp;gt;();
}&lt;/pre&gt;


&lt;h2&gt;But what about C# 4.0 &amp; Dynamic&lt;/h2&gt;
While I think Dynamic objects in C# 4.0 are very cool, as of right now, they seem to have skipped over &lt;i&gt;duck typing&lt;/i&gt;, at least in a strongly typed fashion.

&lt;p&gt;Sure, once you have a dynamic instance, the compiler will let you call whatever signature you wish on it and defers checking until execution time. But that means we have no contract on it, if used as a dependency, nor can we use it to dynamically create objects that provide implementations for existing contracts. So, you've have to wrap a dynamic object with a proxy, in which case, LinFu's existing &lt;i&gt;duck typing&lt;/i&gt; already provides a superior solution.

&lt;p&gt;The lack of casting to an interface, &lt;i&gt;imho&lt;/i&gt; was already oversight with C# 3.0, which introduced anonymous classes that are so convenient for Linq projections, but can't be passed out of the scope of the current method, due to a lack of type.

&lt;p&gt;So don't expect C# 4.0 to do anything to let you more easily attach your contracts at the dependency level. For the foreseeable future, this remains the territory of Dynamic Proxy.

&lt;h2&gt;Next time: Delegate injection&lt;/h2&gt;
&lt;p&gt;However, there is another way to deal with dependency injection that provides a fine-grained contract and imposes no proxies nor other requirement on the classes providing the dependency: &lt;b&gt;Injection of the required capabilities as delegates&lt;/b&gt;

&lt;p&gt;I've been experimenting with a framework to make this as painless as traditional IoC containers make dependency resolution. It's still a bit rough around the edges, but I hope to &lt;a href="http://www.claassen.net/geek/blog/2009/06/ultimate-interface-segregation.html"&gt;have some examples to write about soon&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-8892271901849894528?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2009/06/c-duck-typing-to-rescue-for.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>1</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-1016572290949190429</guid><pubDate>Tue, 16 Jun 2009 06:00:00 +0000</pubDate><atom:updated>2009-06-16T11:01:20.223-07:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>dynamic</category><category domain='http://www.blogger.com/atom/ns#'>contracts</category><category domain='http://www.blogger.com/atom/ns#'>interface</category><category domain='http://www.blogger.com/atom/ns#'>c#</category><title>Interfaces put contracts at the wrong end of the dependency</title><description>&lt;p&gt;Over the years I've hopped back and forth between static and dynamically typed languages, trying to find the sweet spot. I currently still favor managed, static languages like C# and Java. But I agree that sometimes I have to write a whole lot of code to express my intent to the compiler without any great benefit. And no, i don't think that code-generation is a way out of this.

&lt;h2&gt;What's not to like about static?&lt;/h2&gt;

&lt;p&gt;I won't go over the usual arguments for dynamic, which basically boil down to &lt;i&gt;"you can do what you want without having to explain it to the type system first"&lt;/i&gt;. I'll stipulate that that is why most people choose dynamic, but it's not a significant a pain point with static for me. I did spend a good many years in dynamic land and switched to static of my own free will. Instead, I want to concentrate on some specific cases.

&lt;h3&gt;Fine grained basic types are usually overkill&lt;/h3&gt;
I generally don't care whether i am dealing with &lt;code&gt;int&lt;/code&gt; or &lt;code&gt;long&lt;/code&gt;, or &lt;code&gt;int64&lt;/code&gt;, or &lt;code&gt;double&lt;/code&gt; vs. &lt;code&gt;decimal&lt;/code&gt;. For the most part, &lt;code&gt;number&lt;/code&gt; would do just fine. I think these types can be useful optimizations for both speed and memory, but certainly something that would be better optimized by a tracing rather than declaratively at compile time. And having to call special converters all over the place to go between these various types, is just not useful. I think type inference can handle these scenarios just fine.  

&lt;h3&gt;Execution speed is a red-herring&lt;/h3&gt;
&lt;p&gt;I'm not saying that there aren't areas where speed isn't important enough to drop down to C/C++ levels, but anywhere where you are willing to use a statically typed managed language, a dynamic language can either perform right now or is only a short time away from being performant. After all, i already sacrifice performance to be in managed land, so a little more sacrifice for the development benefits seems arbitrary. Besides, recent javascript optimizations paint a pretty good picture that tracing and JIT compilation can make dynamic code fast enough for most scenarios.

&lt;h2&gt;Declaration and Discoverability of Dependencies&lt;/h2&gt;
&lt;p&gt;So what's the pain point of dynamic for me? I care neither about the locking down of a class to handle only statically defined things, nor about the guarantee that a type is really a particular type. Frankly "&lt;i&gt;types&lt;/i&gt;" are not important to me. However, &lt;b&gt;declaration of dependencies in a discoverable fashion&lt;/b&gt; is!

&lt;p&gt;What do I mean by that? &lt;b&gt;A class should tell me via a machine discoverable contract what it expects the passed instance to be capable of.&lt;/b&gt; If I use a class that has service dependencies at construction time, or instance dependencies at method invocation time, I want to be able to discover this in code, rather than by looking at documentation or going by naming convention. After all, hasn't documentation been deemed a code smell? Why is it then, that in dynamic languages the expected capabilities of the object to be passed is not expressed in a fashion that can be discovered without breaking encapsulation and looking at what the code expects to do with the passed instance? 
&lt;p&gt;Sure, dynamic languages pride themselves on not requiring an IDE. This is often held up as a strength and a key reason why they are faster to develop in. In my experience, however, I find dynamic languages faster for small things but as the project grows, my velocity decreases:
&lt;ul&gt;
&lt;li&gt;I have to memorize more and more code and refer back to docs more, instead of letting the IDE guide me on available signatures&lt;/li&gt;
&lt;li&gt;Instead of navigating by concrete signatures, i do lots of string searches&lt;/li&gt;
&lt;li&gt;Instead of using long, self-documenting class and method names, I use terse syntax to ease typing and recollection&lt;/li&gt;
&lt;li&gt;Instead of symbolic refactoring, I do regex replaces, hoping there isn't a syntax collision between classes that replaces the wrong thing&lt;/li&gt;
&lt;li&gt;And handing off code or integrating someone else's code is slower because domain knowledge moves out of the code into tribal knowledge and documentation&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;Declaring Requirements instead of Capabilities&lt;/h2&gt;

&lt;p&gt;All the above is not a problem in static languages, but at the cost of inflexible, rigid &lt;i&gt;types&lt;/i&gt;. &lt;b&gt;Types are a solution that are a trojan horse of limitations that are completely orthogonal to the problem of dependency discovery&lt;/b&gt;. A class requiring an object of type &lt;b&gt;User&lt;/b&gt; should have no dependence on the implementation details of &lt;b&gt;User&lt;/b&gt;. Having such a dependence would be a clear violation of encapsulation. The class should simply want an instance of an object that has the capabilities of a &lt;b&gt;User&lt;/b&gt;, i.e. it has a requirement for an object that exposes certain capabilities. The class should be able to declare a contract for the instance to be passed in.

&lt;p&gt;In C# and similar languages this contract is an Interface. Interfaces allow the declaration of capabilities without an implementation. In interface inheritance, a class commits to providing the contract expressed by the interface. So a class requiring an a specific interface can declare its requirements without any knowledge of implementation. All right, problem solved! Right?

&lt;h2&gt;Interfaces as Contracts are upside down&lt;/h2&gt;

&lt;p&gt;Interfaces unfortunately do not solve the problem, because the way the are attached to implementation inverts the dependence hierarchy. I.e. &lt;b&gt;User&lt;/b&gt; implements an interface its author declared, called &lt;b&gt;IUser&lt;/b&gt;. Now &lt;b&gt;IUser&lt;/b&gt; becomes my dependency, which is still a declaration outside of my control. I should not care where the implementation comes from. But an interface, puts the burden on a third party to implement my interface, which means I cannot use anything pre-existing, since it wouldn't have implemented my interface, or the burden is put on the third party to provide an interface tome to use, which means another third party solving the same problem, provides their own interface.

&lt;p&gt;This may be wonderful for mocking and unit testing, but it still ties me to a contract not of my own making and usually violates the &lt;b&gt;Interface Segregation Principle&lt;/b&gt;: &lt;i&gt;Clients should not be forced to depend upon interfaces that they do not use&lt;/i&gt;&lt;/p&gt;. So interfaces provide a solution, but they still enforce rigidity that has no benefit to the definition of dependency contracts.

&lt;h2&gt;Contracts for dependencies&lt;/h2&gt;

&lt;p&gt;At the end of the day, I have less to quarrel about dynamic vs. static, than tribal definition (naming conventions, documentation, etc.) of dependencies vs. declarative definition of dependencies. Until I can discover what a class expects as its input without being told or cracking open the man page, I will suffer the yoke of interfaces. Especially since I can still use Dynamic Proxies to fake a class implementing an interface -- in yet another "&lt;i&gt;more code than you'd think&lt;/i&gt;" way of working, tho.

&lt;p&gt;Are there any static or dynamic languages that have tackled declarative contracts that are not attached at the implementation side that I'm not aware of? It seems like a sweet spot that isn't yet addressed.

&lt;p&gt;&lt;b&gt;Update:&lt;/b&gt; I realize i left those wanting a solution to the interface issue in C# wanting. There are two ways to solve the problem that I'm aware of, Duck Typing as offered by &lt;a href="http://code.google.com/p/linfu/"&gt;LinFu&lt;/a&gt; and delegate injection, both of which I will cover in future posts.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-1016572290949190429?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2009/06/interfaces-put-contract-at-wrong-end-of.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>3</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-7938527667934374725</guid><pubDate>Sat, 13 Jun 2009 03:12:00 +0000</pubDate><atom:updated>2009-06-12T20:12:00.351-07:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>finally</category><category domain='http://www.blogger.com/atom/ns#'>using</category><category domain='http://www.blogger.com/atom/ns#'>c#</category><category domain='http://www.blogger.com/atom/ns#'>IDisposable</category><title>When using won't Dispose</title><description>The &lt;code&gt;using&lt;/code&gt; statement/block in C# &lt;i&gt;(not the one used to pull in namespaces)&lt;/i&gt; is meant to aid in the IDisposable pattern, i.e. cleaning up resources that won't be handled by garbage collection and to do so in a deterministic fashion. I.e. everything that &lt;b&gt;finalization&lt;/b&gt; is not. It really is just syntactic sugar to avoid &lt;code&gt;try/finally&lt;/code&gt; all the time. I.e. this

&lt;pre class="brush: csharp;"&gt;
using(var disposable = new DisposableObject())
{
  // do something with disposable
}
&lt;/pre&gt;
is pretty much the same as 
&lt;pre class="brush: csharp;"&gt;
var disposable = new Disposable();
try
{
  // do something with disposable
}
finally
{
  disposable.Dispose();
}
&lt;/pre&gt;

&lt;p&gt;But there is a common pitfall with using, &lt;i&gt;err,&lt;/i&gt; &lt;code&gt;using&lt;/code&gt;. It's in the first line above: &lt;b&gt;The disposable object is created outside the &lt;code&gt;try/finally&lt;/code&gt; block!&lt;/b&gt; Now, a constructor failing shouldn't ever have allocated disposable resources, so you're usually safe here. But beware if the construction of the Disposable object is a Method.

&lt;pre class="brush: csharp;"&gt;
using(var disposable = CreateDisposable())
{
  // do something with disposable
}
&lt;/pre&gt;

If &lt;code&gt;CreateDisposable()&lt;/code&gt; fails after it has created &lt;code&gt;Disposable&lt;/code&gt;, you'll end up with a resource leak!

&lt;p&gt;You can easily avoid this by catching failure in your method and cleaning up, but you can't use &lt;code&gt;using&lt;/code&gt; for this purpose, since success would return an already disposed instance. A safe implementation of &lt;code&gt;CreateDisposable()&lt;/code&gt; looks like this:

&lt;pre class="brush: csharp;"&gt;
public Disposable CreateDisposable()
{
  Disposable disposable = new Disposable();
  try {
    // do some extra initialization of disposable
  }
  catch
  {
    if( disposable != null )
      disposable.Dispose();
    throw;
  }
  return disposable; 
}
&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;IDisposable&lt;/code&gt; is an important pattern in .NET, but because it is a pattern rather than a construct enforced by the compiler, it is a common source of "leaks" in .NET. &lt;code&gt;using&lt;/code&gt; is very useful for handling the disposable, but it is important to remember that the only code covered by the automatic disposition logic is the code inside the &lt;code&gt;using&lt;/code&gt; block, not the code inside the &lt;code&gt;using&lt;/code&gt; statement.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-7938527667934374725?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2009/06/when-using-wont-dispose.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-5878543158810508147</guid><pubDate>Thu, 11 Jun 2009 16:47:00 +0000</pubDate><atom:updated>2009-06-12T09:16:04.922-07:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>depth-first</category><category domain='http://www.blogger.com/atom/ns#'>.net</category><category domain='http://www.blogger.com/atom/ns#'>Extension method</category><category domain='http://www.blogger.com/atom/ns#'>breadth-first</category><category domain='http://www.blogger.com/atom/ns#'>yield</category><category domain='http://www.blogger.com/atom/ns#'>linq</category><category domain='http://www.blogger.com/atom/ns#'>c#</category><category domain='http://www.blogger.com/atom/ns#'>tree</category><title>Searching a Tree of Objects with Linq, Revisited</title><description>A while back, &lt;a href="http://www.claassen.net/geek/blog/2007/11/searching-tree-of-objects-with-linq.html"&gt;I wrote about searching through a tree using linq to objects&lt;/a&gt;. That post was mostly snippets of code about delegates, lambda's, yield and how it applies to linq -- more a technical exploration than an example. So I thought I'd follow it up with concrete extension methods to make virtually any tree searchable by Linq.

&lt;h2&gt;Linq, IEnumerable&amp;lt;T&amp;gt;, yield&lt;/h2&gt;

&lt;p&gt;All that is required to search a tree with Linq is creating a list of all nodes in the tree. Linq to Objects can operate on IEnumerable&amp;lt;T&amp;gt;. Really, &lt;b&gt;Linq to objects is a way of expressing operations we've been doing forever in loops with if/else blocks&lt;/b&gt;. That means there isn't any &lt;i&gt;search magic&lt;/i&gt; going on, it is a linear traversal of all elements in a set and examining each to determine whether it matches our search criteria.

&lt;p&gt;To turn a tree into a list of node we need to walk and collect all children of every node. A simple task for a recursive list that carries along a list object to stuff every found node into. But there is a better way, using yield to return each item as it is encountered. Now we don't have to carry along a collection. &lt;b&gt;Iterators using yield implement a pattern in which a method can return more than once.&lt;/b&gt; For this reason, a method using yield in C# must return an IEnumerable, so that the caller gets a handle to an object it can traverse the result of the multiple return values.

&lt;p&gt;IEnumerable is basically an unbounded set. This is also the reason why unlike collections, it does not have a Count Property. It is entirely possible for an enumerator to return an infinite series of items.

&lt;p&gt;Together IEnumerable&amp;lt;T&amp;gt; and yield are a perfect match for our problem, i.e. recursively walking a tree of nodes and return an unknown number of nodes.

&lt;h2&gt;Two types of Tree Traversal&lt;/h2&gt;

&lt;h3&gt;Depth First&lt;/h3&gt;

&lt;p&gt;In &lt;a href="http://en.wikipedia.org/wiki/Depth-first_search"&gt;depth-first&lt;/a&gt; traversal, the algorithm will dig continue to dig down a nodes children until it reaches a leaf node (a node without children), before considering the next child of the current parent node.

&lt;h3&gt;Breadth First&lt;/h3&gt;

&lt;p&gt;In &lt;a href="http://en.wikipedia.org/wiki/Breadth-first_search"&gt;breadth-first&lt;/a&gt; traversal, the algorithm will return all nodes at a particular depth first before considering the children at the next level. I.e. First return all the nodes from level 1, then all nodes from level 2, etc.

&lt;h2&gt;Tree to IEnumerable&amp;lt;T&amp;gt; Extension methods&lt;/h2&gt;

&lt;pre class="brush: csharp;"&gt;
public static class TreeToEnumerableEx
{
 public static IEnumerable&amp;lt;T&amp;gt; AsDepthFirstEnumerable&amp;lt;T&amp;gt;(this T head, Func&amp;lt;T, IEnumerable&amp;lt;T&amp;gt;&amp;gt; childrenFunc)
 {
  yield return head;
  foreach (var node in childrenFunc(head))
  {
   foreach (var child in AsDepthFirstEnumerable(node, childrenFunc))
   {
    yield return child;
   }
  }
 }

 public static IEnumerable&amp;lt;T&amp;gt; AsBreadthFirstEnumerable&amp;lt;T&amp;gt;(this T head, Func&amp;lt;T, IEnumerable&amp;lt;T&amp;gt;&amp;gt; childrenFunc)
 {
  yield return head;
  var last = head;
  foreach(var node in AsBreadthFirstEnumerable(head,childrenFunc))
  {
   foreach(var child in childrenFunc(node))
   {
    yield return child;
    last = child;
   }
   if(last.Equals(node)) yield break;
  }
 }
}&lt;/pre&gt;

&lt;p&gt;This static class provides two extension methods that can be used on any object, as long as it's possible to express a function that returns all children of that object, i.e. the object is a node in some type of tree and has a method or property for accessing a list of its children.

&lt;h2&gt;An Example&lt;/h2&gt;
&lt;p&gt;Let's use a hypothetical Tree model defined by this Node class:

&lt;pre class="brush: csharp;"&gt;
public class Node
{
 private readonly List&amp;lt;Node&amp;gt; children = new List&amp;lt;Node&amp;gt;();
 
 public Node(int id)
 {
  Id = id;
 }
 
 public IEnumerable&amp;lt;Node&amp;gt; Children { get { return children; } }

 public Node AddChild(int id)
 {
  var child = new Node(id);
  children.Add(child);
  return child;
 }
 
 public int Id { get; private set; }
}
&lt;/pre&gt;

Each node simply contains a list of children and has an Id, so that we know what node we're looking at. The AddChild() method is a convenience method so we don't expose the child collection and no node can ever be added as a child twice.

&lt;p&gt;The calling convention for a depth-first collection is:

&lt;pre class="brush: csharp;"&gt;
IEnumerable&amp;lt;Node&amp;gt; = node.AsDepthFirstEnumerable(n =&amp;gt; n.Children);
&lt;/pre&gt;

&lt;p&gt;The lambda expression &lt;code&gt;n =&amp;gt; n.Children&lt;/code&gt; is the function that will return the children of a node. It simply states &lt;i&gt;given n, return the value of the Children property of n&lt;/i&gt;. A simple test to verify that our extension works and to show us using the extension in linq looks like this:

&lt;pre class="brush: csharp;"&gt;
[Test]
public void DepthFirst()
{
 // build the tree in depth-first order
 int id = 1;
 var depthFirst = new Node(id);
 var df2 = depthFirst.AddChild(++id);
 var df3 = df2.AddChild(++id);
 var df4 = df2.AddChild(++id);
 var df5 = depthFirst.AddChild(++id);
 var df6 = df5.AddChild(++id);
 var df7 = df5.AddChild(++id);

 // find all nodes in depth-first order and select just the Id of each node
 var IDs = from node in depthFirst.AsDepthFirstEnumerable(x =&amp;gt; x.Children)
        select node.Id;

 // confirm that this list of IDs is in depth-first order
 Assert.AreEqual(new int[] { 1, 2, 3, 4, 5, 6, 7 }, IDs.ToArray());
}
&lt;/pre&gt;

&lt;p&gt;For breadth-first collections, the calling convention is:

&lt;pre class="brush: csharp;"&gt;
IEnumerable&amp;lt;Node&amp;gt; = node.AsBreadthFirstEnumerable(n =&amp;gt; n.Children);
&lt;/pre&gt;

&lt;p&gt;Again, we can test that the extension works like this:

&lt;pre class="brush: csharp;"&gt;
[Test]
public void BreadthFirst()
{
 // build the tree in breadth-first order
 var id = 1;
 var breadthFirst = new Node(id);
 var bf2 = breadthFirst.AddChild(++id);
 var bf3 = breadthFirst.AddChild(++id);
 var bf4 = bf2.AddChild(++id);
 var bf5 = bf2.AddChild(++id);
 var bf6 = bf3.AddChild(++id);
 var bf7 = bf3.AddChild(++id);

 // find all nodes in breadth-first order and select just the Id of each node
 var IDs = from node in breadthFirst.AsBreadthFirstEnumerable(x =&amp;gt; x.Children)
       select node.Id;

 // confirm that this list of IDs is in depth-first order
 Assert.AreEqual(new int[] { 1, 2, 3, 4, 5, 6, 7 }, IDs.ToArray());
}&lt;/pre&gt;

&lt;h2&gt;Searching Trees&lt;/h2&gt;

&lt;p&gt;The tree used in the example is of course extremely simple, i.e. it doesn't even have any worthwhile data to query attached to a node. But these extension methods could be used on a node of any kind of tree, &lt;b&gt;allowing the full power of Linq, grouping, aggregation, sorting, projection, etc. to be used on the tree&lt;/b&gt;.

&lt;p&gt;As a final note, you may wonder, &lt;b&gt;why bother with depth-first vs. breadth first?&lt;/b&gt; After all, in the end we do examine every node! There is however one particular case where the choice of algorithm can be very important: &lt;b&gt;You are looking for one match or a particular number of matches.&lt;/b&gt; Since we are using yield, we can terminate the traversal at any time. Using the &lt;code&gt;FirstOrDefault()&lt;/code&gt; extension on our Linq expression, the traversal would stop as soon as one match is found. And if have any knowledge where that node might be in the tree, the choice of search algorithm can be a significant performance factor.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-5878543158810508147?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2009/06/searching-tree-of-objects-with-linq.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-5519884757426387318</guid><pubDate>Sun, 07 Jun 2009 17:57:00 +0000</pubDate><atom:updated>2009-06-07T11:36:10.632-07:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>c#</category><category domain='http://www.blogger.com/atom/ns#'>debugging</category><category domain='http://www.blogger.com/atom/ns#'>log4net</category><title>Log4Net filtering by logger</title><description>Since i keep overwriting my App.Config with revision control configs and promptly forgetting how to set up filters, I figured i might was well write a brief article on filters here, so i have a place to look it up next time :)

&lt;p&gt;My basic tenet with logging is that lots of debug statements is good. Now some may say that it just gets too noisy after a while, so don't put them in unless you need to debug. The problem is that you usually don't know when you'll need to debug, and if the code is deployed on a server or worse with a customer, generating a new release so they can run the debug is a burden you shouldn't have to shoulder. And commenting out log statements (or even conditional compiles) are a code smell reeking of &lt;code&gt;Console.Writeline&lt;/code&gt; debugging

&lt;p&gt;&lt;i&gt;But it does get noisy! And noisy also means slow!&lt;/i&gt; However &lt;b&gt;with log4net, noisy and performance degradation are non-arguments&lt;/b&gt;, since aside from levels, it has excellent filtering, which not only reduces the noise, but also cuts out 99% of the logging overhead. Worst case debugging example I've had was tracking down behavior in the motion control software for Full Motion Racing. The physics calculations in this software ran between 60Hz and 100Hz. When i added debug logging in that physics loop, the rate dropped down to about 20Hz because of I/O overhead, and this was with either &lt;code&gt;RollingFile&lt;/code&gt; or &lt;code&gt;Udp&lt;/code&gt; appenders. Needless to say, motion became jerky and unusable for a rider. But I got the debug data i needed. Disabling those logging statements with filters rather than removing left no appreciable degradation in the performance of the physics loop.

&lt;p&gt;So, again, &lt;b&gt;lots of debug logging == good&lt;/b&gt;. Because when you need that data, you need that data. But you may want to ship your code with a log4net configuration that pre-filters the loggers you know to be noisy, so that a user turning on debug logging doesn't overwhelm them.

&lt;h2&gt;How to filter&lt;/h2&gt;
&lt;p&gt;The basic deal with log4net filters is that they are applied in order and the first filter that matches short-circuits the matching logger. I.e. if the first filter is a &lt;code&gt;DenyAllFilter&lt;/code&gt;, nothing else will even be considered, since it matches all loggers. That means there are generally two approaches to filtering, &lt;b&gt;whitelisting&lt;/b&gt; and &lt;b&gt;blacklisting&lt;/b&gt;. It also means that if you match a logger and a subsequent filter would remove that logger, the subsequent filter is never reached, since consideration of the filter chain stops at the first match&lt;/p&gt;

&lt;h3&gt;Whitelisting by logger&lt;/h3&gt;

&lt;pre class="brush: xml;"&gt;
&amp;lt;filter type=&amp;quot;log4net.Filter.LoggerMatchFilter&amp;quot;&amp;gt;
  &amp;lt;loggerToMatch value=&amp;quot;Only.Logger.To.Match&amp;quot; /&amp;gt;
&amp;lt;/filter&amp;gt;
&amp;lt;filter type=&amp;quot;log4net.Filter.DenyAllFilter&amp;quot; /&amp;gt;
&lt;/pre&gt;

&lt;code&gt;LoggerMatchFilter&lt;/code&gt; filters default to &lt;code&gt;acceptOnMatch&lt;/code&gt; being true, i.e. if omitted, the filter is a accepts (includes in logging) on match. The above will only emit logging statements for the &lt;i&gt;Only.Logger.To.Match&lt;/i&gt; logger, since all others will hit the &lt;code&gt;DenyAllFilter&lt;/code&gt; and be excluded.

&lt;h3&gt;Blacklisting by logger&lt;/h3&gt;

&lt;pre class="brush: xml;"&gt;
&amp;lt;filter type=&amp;quot;log4net.Filter.LoggerMatchFilter&amp;quot;&amp;gt;
  &amp;lt;loggerToMatch value=&amp;quot;Logger.To.Filter.Out&amp;quot; /&amp;gt;
  &amp;lt;acceptOnMatch value=&amp;quot;false&amp;quot; /&amp;gt;
&amp;lt;/filter&amp;gt;
&lt;/pre&gt;

This filter will show all logging statements except those for &lt;i&gt;Logger.To.Filter.Out&lt;/i&gt;. 
&lt;p&gt;&lt;code&gt;LoggerMatchFilter&lt;/code&gt; also matches on partial namespaces, which is very useful when you have a noisy namespace, but one logger in that namespace that you do want in your logs such as:

&lt;pre class="brush: xml;"&gt;
&amp;lt;filter type=&amp;quot;log4net.Filter.LoggerMatchFilter&amp;quot;&amp;gt;
  &amp;lt;loggerToMatch value=&amp;quot;Noisy.Namespace.But.Important&amp;quot; /&amp;gt;
&amp;lt;/filter&amp;gt;
&amp;lt;filter type=&amp;quot;log4net.Filter.LoggerMatchFilter&amp;quot;&amp;gt;
  &amp;lt;loggerToMatch value=&amp;quot;Noisy.Namespace&amp;quot; /&amp;gt;
  &amp;lt;acceptOnMatch value=&amp;quot;false&amp;quot; /&amp;gt;
&amp;lt;/filter&amp;gt;
&lt;/pre&gt;

With these filters, all of &lt;i&gt;Noisy.Namespace.*&lt;/i&gt; will be filtered out, except for &lt;i&gt;Noisy.Namespace.But.Important&lt;/i&gt;.

&lt;h2&gt;Filters are your friend&lt;/h2&gt;

&lt;p&gt;So, don't get locked into thinking that your choice for verbosity lies only in log levels and once committed to a level it's either all the noise or none of it. But to keep things sane, pre-populate your config with filters, because you are the one that knows best which loggers are of general use and which are special case only.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-5519884757426387318?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2009/06/log4net-filtering-by-logger.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>1</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-479064448684254016</guid><pubDate>Sat, 23 May 2009 05:49:00 +0000</pubDate><atom:updated>2009-05-22T22:58:12.386-07:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>rest</category><category domain='http://www.blogger.com/atom/ns#'>async programming</category><category domain='http://www.blogger.com/atom/ns#'>mindtouch</category><category domain='http://www.blogger.com/atom/ns#'>dream</category><title>Blogging on MindTouch Dev Blog</title><description>Once again, there's been extended silence over here. I have several article drafts that keep getting the short end of my time in favor of coding. In the meantime, I have blogged a couple of article's over on the &lt;a href="http://blog.developer.mindtouch.com/"&gt;MindTouch Dev blog&lt;/a&gt;.

&lt;ul&gt;
&lt;li&gt;&lt;a href="http://blog.developer.mindtouch.com/2009/04/16/hooking-into-the-mindtouch-event-bus/"&gt;Hooking into the MindTouch Event Bus&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.developer.mindtouch.com/2009/04/22/advanced-dekiscript-extension-in-c-tutorial/"&gt;Advanced DekiScript extension in C# tutorial&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.developer.mindtouch.com/2009/04/28/a-user-timeline-publishing-events-for-retrieval-by-dekiscript/"&gt;A User Timeline: Publishing events for retrieval by DekiScript&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.developer.mindtouch.com/2009/05/18/consuming-rest-services-and-tdd-with-plug/"&gt;Consuming REST services and TDD with Plug&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

In general, I've just been spending a lot of time working on RESTful services, both for MindTouch and designing the new &lt;a href="http://wiki.notify.me/API/REST_API"&gt;Notify.me REST API&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-479064448684254016?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2009/05/blogging-on-mindtouch-dev-blog.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-1115902980646457342</guid><pubDate>Mon, 16 Feb 2009 22:00:00 +0000</pubDate><atom:updated>2009-02-16T14:00:00.779-08:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>resharper</category><category domain='http://www.blogger.com/atom/ns#'>c#</category><category domain='http://www.blogger.com/atom/ns#'>SOLID</category><title>How I became a SOLID advocate and didn't even know it</title><description>&lt;p&gt;There's been a lot of chatter of late about &lt;a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod" title="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod" class="external"&gt;SOLID&lt;/a&gt;. It started with &lt;a href="http://objectmentor.com/omTeam/martin_r.html" title="http://objectmentor.com/omTeam/martin_r.html" class="external"&gt;Uncle Bob&lt;/a&gt; talking on a couple of podcasts about the SOLID principles, but it really got the chatter going when &lt;a href="http://www.joelonsoftware.com/" title="http://www.joelonsoftware.com/" class="external"&gt;Joel Spolsky&lt;/a&gt; and &lt;a href="http://www.codinghorror.com/blog/" title="http://www.codinghorror.com/blog/" class="external"&gt;Jeff Atwood&lt;/a&gt; started talking smack about Uncle Bob on the &lt;a href="http://blog.stackoverflow.com/2009/01/podcast-38/" title="http://blog.stackoverflow.com/2009/01/podcast-38/" class="external"&gt;Stackoverflow podcast&lt;/a&gt;. Since then &lt;a href="http://blog.objectmentor.com/articles/2009/02/06/on-open-letter-to-joel-spolsky-and-jeff-atwood" title="http://blog.objectmentor.com/articles/2009/02/06/on-open-letter-to-joel-spolsky-and-jeff-atwood" class="external"&gt;battle&lt;/a&gt; &lt;a href="http://www.codinghorror.com/blog/archives/001225.html" title="http://www.codinghorror.com/blog/archives/001225.html" class="external"&gt;lines &lt;/a&gt;seem to have been drawn between the TDD/SOLID folks and those who finally found a champion fighting to get them out from under the pattern yoke. Ok, that's a bunch of hyperbole, but it seems that the main objection to SOLID seems to be that having a list of Principles like that just feels bureaucratic and dogmatic, which rubs free thinking developers the wrong way. Since I've been practicing SOLID longer than I've been aware of, I wanted to walk through how I got here and to illustrate that the principles espoused by Uncle Bob are not a yoke, but rather helpful guidelines that will save you a lot of grief down the line.&lt;/p&gt;
&lt;p&gt;The overall goal of development should be delivering software that solves the stated problem. Beyond that I do have some personal guiding principles for programming, i.e. what I personally want to get out of it once the &lt;em&gt;raison d'&lt;/em&gt;&lt;em&gt;être&lt;/em&gt; is accomplished:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;I want to learn new things rather than maintain old things&lt;/li&gt;
  &lt;li&gt;I never want to have to fix the same bug twice&lt;/li&gt;
  &lt;li&gt;I don't want to be prevented from doing something better by legacy decisions&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;To me, 1) means writing code that's easy to maintain, so that maintenance does not become a time suck interfering with new things, 2) means that i protect myself from regressions and 3) means that my code should allow me to refactor it without screwing up 1) or 2). So far that seems pretty non-controversial.&lt;/p&gt;
&lt;p&gt;As I go on, the common theme will be testing, not because testing is some higher goal and end in itself, but because testing, in my experience, let's me prove that code does what it claims and I didn't break anything else by the addition/change. For those who think that writing tests is a lot of tedium that only leads to test maintenance rather than code maintenance, I can only respond &lt;em&gt;"you're probably doing it wrong"&lt;/em&gt; and address that statement under &lt;strong&gt;Pain points of TDD&lt;/strong&gt; below.&lt;/p&gt;
&lt;h2&gt;Doesn't QA test code?&lt;/h2&gt;
&lt;p&gt;In the early days of the web, testing was what the programmer did to make sure things didn't break and then you relied on the customer telling you if it didn't work correctly -- the wild west days of CGI scripts. Once I started at MP3.com, testing became more refined via QA. Sure, everybody tested their web apps before handing them off to QA (or at least they should), but there wasn't really any formalized testing on the development side. It was all manual functional testing of firing up the app, trying out the things that should work and looking at logs. QA was responsible for test plans, regression tests, etc.&lt;/p&gt;
&lt;p&gt;Early on I switched from web apps to running the databases and with that came dealing with the pain of maintaining schemas when everyone had raw SQL in strings throughout their code. So I set out to write a DB API. Being an OO geek, it quickly morphed from an API into an ORM instead, which abstracted the DB and built the SQL on demand. This gave the DB group more freedom to refactor the database as needed without having to have every developer track down their SQL.&lt;/p&gt;
&lt;p&gt;Developing the ORM did mean that I was now out of the QA loop, since my deliverables went to developers and had to work long before QA ever got involved. So I developed test suites that I could run from the shell whenever i changed something. These tests gave me confidence that I didn't just break live apps with code for a new app.&lt;/p&gt;
&lt;p&gt;Part of having these type of tests, however, was a giant &lt;em&gt;WTF &lt;/em&gt;in itself. Why was I constantly risking the codebase by futzing around in the guts? Yes, the ORM suffered horribly from fragile baseclass problems and I had designed myself into a number of corners that could only be addressed by modifying the base. Learning this lesson, I spent a lot more time trying to build object hierarchies to provide the proper hooks to let subclasses extend the functionality without affecting or overriding the base functionality. Little did I know that I had started practicing SOLID's &lt;strong&gt;O&lt;/strong&gt;, or the &lt;strong&gt;Open/Closed Principle (&lt;a class="external" title="http://en.wikipedia.org/wiki/Open/closed_principle" href="http://en.wikipedia.org/wiki/Open/closed_principle"&gt;OCP&lt;/a&gt;)&lt;/strong&gt;.&lt;/p&gt;
&lt;h2&gt;Unit tests, but not really&lt;/h2&gt;
&lt;p&gt;When I started at Printable Technologies a number years later, I became part of an effort to migrate the existing application from ASP to ASP.NET. Like most legacy ASP applications it was the usual single code file per page mixing data access, business logic and html rendering. It was something we did not want to repeat. We set out to separate our logical layers carefully so that we would get greater re-use and transparency of what was going on in the application. I wanted to start off on the right foot and played around with NUnit to try out unit testing our new code base. This was before TestDriven.Net or similar tools for integration into the IDE. But at least it gave me an automated test suite, rather than a series of console apps. I thought, "&lt;em&gt;Now I'm doing unit testing!&lt;/em&gt;".&lt;/p&gt;
&lt;p&gt;Except, like many test adoptees, I really wasn't. I was doing functional tests with a test running harness. I was hitting test databases to check my DB Abstraction Layer, and as you moved up the object hierarchy, the graphs of dependent code supporting the code to be tested got deeper and deeper. Testing something that was at the front end, really tested all pieces beneath it. It certainly gave us good test coverage, but the tests were fragile, took a lot time to write, and it was often difficult to dig out what actually failed. That didn't seem right and made me wonder if this unit testing thing was really so great. But the test coverage did help to achieve my personal guiding principles, so I wasn't ready to give up on it just yet. I just need to work through the pain points.&lt;/p&gt;
&lt;h2&gt;Towards actual unit testing&lt;/h2&gt;
&lt;p&gt;The two major problems we had in our tests were that each test really tested many things at once and that the setup to get to test running was tedious and pulled in too many dependencies.&lt;/p&gt;
&lt;p&gt;The first was a problem with our class design. We needed to break classes up into smaller functional pieces that each could be tested before testing the whole. While testability was the driving force for this change, it requiring this change was really a symptom of how badly coupled things were, i.e. that the design was flawed. This is a pattern in testing that has since repeated itself many times: &lt;strong&gt;If your test is fragile or difficult, it's generally the fault of the design of the code to be tested not the testing process&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;There were a bunch of monolithic classes that did lots of things at once, which meant a test failure could be one of a hundred things. I started to break up classes into smaller pieces, each dedicated to one functional area. Now I could take those &lt;em&gt;helper&lt;/em&gt; classes that the main class was composed of and test them independently. When the composite broke but none of the components did, I knew where to look for failure. This compartmentalization just happens to be &lt;strong&gt;Single Responsibility Principle (&lt;a class="external" title="http://en.wikipedia.org/wiki/Single_responsibility_principle" href="http://en.wikipedia.org/wiki/Single_responsibility_principle"&gt;SRP&lt;/a&gt;)&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;So far so good, but our second problem still dogged us. Tests were still annoying to write the further you got into business logic, since everything built on the supporting infrastructure. I had heard about mocking and started looking into it hoping for some magic bullet that could just create me fakes (which had been easy back in the perl days). This was before TypeMock hit the scene, so I couldn't create a fake version of my concrete type. It was either making everything virtual (&lt;em&gt;yuck&lt;/em&gt;) or using interfaces instead of concrete classes. Interfaces won out, but because I had yet to discover the &lt;strong&gt;D&lt;/strong&gt; in SOLID, introducing a lot of interfaces also led us to a pattern that itself became a major pain point. This pattern was the use of singletons and the static factory methods, both well meaning static accessors to get around the inability of &lt;em&gt;new&lt;/em&gt;'ing up an interface. But before realizing this separate morrass, using interfaces had lead to using the &lt;strong&gt;L&lt;/strong&gt;, &lt;strong&gt;Liskov Substitution&lt;/strong&gt; and &lt;strong&gt;I, Interface Segregation&lt;/strong&gt; principles.&lt;/p&gt;
&lt;p&gt;Mocking out classes with interfaces exposed a couple of places where we had an abstract baseclass and code accepting the base class using &lt;strong&gt;typeof() &lt;/strong&gt;to determine what class was actually provided. Well, with an interface being passed in instead of the abstract baseclass, the &lt;strong&gt;typeof()&lt;/strong&gt; logic still worked, until the first test with a mock object was run. That failure illustrated what a bad idea that bit of code was. If we say we require an object implementing an interface, any object implementing that interface should work, and that right there is the &lt;strong&gt;Liskov Substitution Principle&lt;/strong&gt; &lt;strong&gt;(&lt;a class="external" title="http://en.wikipedia.org/wiki/Liskov_substitution_principle" href="http://en.wikipedia.org/wiki/Liskov_substitution_principle"&gt;LSP&lt;/a&gt;)&lt;/strong&gt;. Making sure that our interfaces really represented the required functionality enabled mocking and cleaned out some inappropriate knowledge embedded in code.&lt;/p&gt;
&lt;p&gt;Another aspect of mocking (rolling mocks by hand rather than using a mocking framework) was that lazyness dictated that you didn't want to implement a lot of things just to get a test working. So large interfaces got widdled down to just the methods required by the object taking in that interface. And that happens to be the &lt;strong&gt;Interface Segregation Principle (&lt;a class="external" title="http://www.objectmentor.com/resources/articles/isp.pdf" href="http://www.objectmentor.com/resources/articles/isp.pdf"&gt;ISP&lt;/a&gt;)&lt;/strong&gt;.&lt;/p&gt;
&lt;h2&gt;A brand new pain: wiring up lots of SRP objects&lt;/h2&gt;
Many of the above principles were only partially applied because they imposed a new pain and a whole new set of plumbing code that was tedious to write and maintain. The issue with separation of concerns and abstracting those concerns with interfaces was two-fold:

&lt;ol&gt;
  &lt;li&gt;You can't &lt;em&gt;new&lt;/em&gt; up an interface, so you needed factories everywhere&lt;/li&gt;
  &lt;li&gt;Suddenly half the code seemed to be plumbing to wire up increasingly complex object graphs.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;As I said, a lot of this was dealt with via Singleton's and static factory methods. Both are really just degenerate implementations of the &lt;a href="http://martinfowler.com/articles/injection.html#UsingAServiceLocator" title="http://martinfowler.com/articles/injection.html#UsingAServiceLocator" class="external"&gt;&lt;strong&gt;Service Locator Pattern&lt;/strong&gt;&lt;/a&gt;, but we weren't even aware of that. Since this plumbing had it's own set of pain points, we often skipped the abstractions unless we really needed them to keep life simpler. Generally that meant we paid for that convenience in maintenance debt.&lt;/p&gt;
&lt;p&gt;When I started writing code for Full Motion Racing, like every new project, I wanted to take the lessons learned from Printable and avoid the pains I had come across. I once again had need for object graphs that required access to singleton type service objects, but wanted to avoid statics as much as I could because of previous experience. I built a repository of objects that I could stuff instances into, providing me a &lt;strong&gt;Service Locator&lt;/strong&gt;. Looking more into how other people were doing this, I came across talk about service locator still being an inappropriate coupling, since it itself is a dependency that had nothing to do with the responsibility of the consuming objects. Instead, services should be passed in at construction time whenever possible. &lt;em&gt;Wow, really?&lt;/em&gt; That just seemed to take the pain of wiring up object graphs to unprecedented heights. That just couldn't be how people were writing their code.&lt;/p&gt;
&lt;p&gt;Wanting to understand how this way of building decoupled systems could actually work in the real world, I learned about the &lt;strong&gt;D&lt;/strong&gt; of SOLID, or the &lt;strong&gt;Dependency Inversion Principle&lt;/strong&gt; &lt;strong&gt;(&lt;a href="http://en.wikipedia.org/wiki/Dependency_inversion_principle" title="http://en.wikipedia.org/wiki/Dependency_inversion_principle" class="external"&gt;DIP&lt;/a&gt;)&lt;/strong&gt; also (and maybe more accurately) known as &lt;a href="http://martinfowler.com/articles/injection.html" title="http://martinfowler.com/articles/injection.html" class="external"&gt;&lt;strong&gt;Inversion of Control&lt;/strong&gt;&lt;/a&gt;. In my opinion, &lt;strong&gt;DIP&lt;/strong&gt; may be the last principle mentioned, but in many ways it is the enabling plumbing without which the remaining principles are all well in theory but often feel worse than the disease they aim to cure.&lt;/p&gt;
&lt;h2&gt;Agile in action&lt;/h2&gt;
&lt;p&gt;Early use of IoC for Full Motion Racing still relied on a singleton container that factory classes could use to create their dependencies for creating transient objects. Only over time did I learn to trust the container to build up all my objects for me, and learned how to register factories to support lifestyles other than singleton via the container.&lt;/p&gt;
&lt;p&gt;It wasn't until I started at &lt;a href="http://www.bunkspeed.com/" title="http://www.bunkspeed.com/" class="external"&gt;Bunkspeed&lt;/a&gt;, that I really saw IoC used properly and was able to reap the true benefits of this design pattern. If you've ever seen Bunkspeed's &lt;a href="http://www.bunkspeed.com/hypershot/" title="http://www.bunkspeed.com/hypershot/" class="external"&gt;HyperShot&lt;/a&gt; or &lt;a href="http://www.bunkspeed.com/hyperdrive/" title="http://www.bunkspeed.com/hyperdrive/" class="external"&gt;HyperDrive&lt;/a&gt; in action you know that the visualizations they create are mind blowing, especially once you realize it's real-time. Needless to say, sitting down with this codebase was initially intimidating. It still is the largest single codebase i've worked on. Maybe some of the distributed web apps I've worked on had more code in total, but they were disparate systems that largely had no interdependence. The main Visual Studio Solution I worked on at Bunkspeed was one application with hundreds of projects all loaded at once.&lt;/p&gt;
&lt;p&gt;I assumed this meant lots of branching, lots of areas of expertise where certain people would be responsible for a subset of the code. This was not the case. Everyone was trusted and had authority to modify, extend and refactor everything as they required it. Making a change that required a change much lower down in the system could be made by anyone. Tests ran with every build in addition to a full set of CI servers building various configurations on each check-in. And it all ran smoother than any other shop I'd been in and was easier to ramp up on then other, far simpler projects.&lt;/p&gt;
&lt;p&gt;Bunkspeed employs every one of the SOLID principles. Systems were composed of lots of small classes with very limited responsiblity, each being abstracted by an interface. One of the reasons for the many projects rather than fewer, larger projects was that areas of responsiblity were segregated, including their interfaces being in separate DLLs so that low level changes wouldn't cause rebuilds of the entire system. Deep reaching refactors were not the norm but rather an indication that some inappropriate coupling had been done at some previous time and the refactor served to rectify the situation so that technical debt was accruing at much slower rates than is the norm. This was not some academic application of patterns from a book, but a truly agile development shop able to make significant changes with a small team in record time.&lt;/p&gt;
&lt;p&gt;SOLID wasn't some rule set put before me, but a natural evolution of trying to make development easier. It wasn't until about 9 months ago that I read Robert C. Martin and Micah Martin's &lt;a href="http://www.amazon.com/Principles-Patterns-Practices-Robert-Martin/dp/0131857258" title="http://www.amazon.com/Principles-Patterns-Practices-Robert-Martin/dp/0131857258" class="external"&gt;&lt;em&gt;Agile Principles, Patterns, and Practices in C#&lt;/em&gt;&lt;/a&gt; because it was sitting on a co-worker's desk and for the first time I put names to the patterns I'd been applying this entire time.&lt;/p&gt;
&lt;h2&gt;Pain points of SOLID&lt;/h2&gt;
&lt;p&gt;There is definitely a different cost occured by applying SOLID to design. Most of this cost is in navigating the granularity of the design and in this tooling is an important aid to make this not only painless but more productive than the alternatives. The issue is that Visual Studio really isn't all that well suited to navigating large object hierarchies, especially when using interfaces for abstraction. There are those who will point to this pain as evidence of SOLID being a bad practice. "&lt;em&gt;I don't want to have to get special tools just to do development.&lt;/em&gt;" But if tooling really is your enemy then you probably shouldn't be working with a language like C# in the first place, because it already does rely on the many crutches VS offers up. Try writing C# without an IDE and you'll quickly understand why people love the simple and terse syntax of Ruby and other dynamic Languages. Saying "&lt;em&gt;well, Visual Studio is as much tooling as I accept, beyond that it's ridiculous&lt;/em&gt;" is not an argument I can relate to, so if that's the objection to SOLID, I'll have to admit that I can't convince you.&lt;/p&gt;
&lt;p&gt;The issue just is that VS does not provide efficient ways to navigate from class to class and from interface to implementers and from implementers to usage of the interface. This is where &lt;a href="http://www.jetbrains.com/resharper" title="http://www.jetbrains.com/resharper" class="external"&gt;ReSharper&lt;/a&gt; entered the picture for me, and after adding more keybindings for some of their extended commands, the number of classes and abstractions really becomes a non-issue. I simply couldn't do development in C# without ReSharper at this point and that's more because of Visual Studio's shortcomings than anything else (eclipse, for example, provides most of the same features I rely on out of the box).&lt;/p&gt;
&lt;p&gt;The other pain created by lack of tooling is that the larger surface area of code and the increased abstraction means that refactoring ususally touch more code than before, meaning that refactoring takes more work. However with proper tooling this also happens automatically. In addition, the flexibility of loose coupling introduced by SOLID generally makes code more pliable to refactoring.&lt;/p&gt;


&lt;h2&gt;Pain points of TDD&lt;/h2&gt;
&lt;p&gt;Finally there is the whole concept of TDD itself which to many seems like such a "&lt;em&gt;making work&lt;/em&gt;" paradigm. Usually the examples of TDD failure pointed to are &lt;strong&gt;fragile tests&lt;/strong&gt; and&lt;strong&gt; lost productivity due to writing tests instead of code&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Fragile tests refers to a simple change breaking a lot of tests and thereby incurring extra work instead of saving work. But if a simple change breaks a lot of tests, it's a clear indication that your design needs another look, because there seems to be coupling that is getting in the way. The only time (ideally at least) that more than one test breaks is when you change the expected behavior of a class, and in that case, refactoring the expected behavior would have included the refactoring of all dependencies, including the tests.&lt;/p&gt;
&lt;p&gt;The lost productivity argument only holds water if you are not responsible for extension or maintenance. And all you are doing then is pushing the work that should have been yours in the first place on the poor sucker that's inheriting your legacy. It has been my experience that any time I find a bug or break something with a new feature, it's because I didn't have test coverage on the affected code. Which means I get to lose productivity when I am likely already under time pressue rather than up front.&lt;/p&gt;
&lt;p&gt;Another part of the lost productivity argument usually refers to the amount of code required to test a particular object vs. just using that object in production code. Between DIP for wiring things up and the numerous mocking frameworks available to declare your expectations on dependencies, wiring up your test harness should be short. If there is a lot of plumbing required just to set up the test conditions something's wrong with the design.&lt;/p&gt;
&lt;h2&gt;Not dogmatic, just providing guidance&lt;/h2&gt;
&lt;p&gt;Since I arrived at practicing the SOLID principles, without being aware of them, I just can't see the dogma or beaurecracy in them. The recommendation in those 5 principles when taken as a whole is about making your life easier not forcing some philosophy down your throat.&lt;/p&gt;
&lt;p&gt;If someone had put them front of me and told me "&lt;em&gt;this is the way you must code, because &lt;strong&gt;good &lt;/strong&gt;programmers do this&lt;/em&gt;", I'd likely be dismissive as well. Being thrown into implementing some process from a whitepaper without having seen it in practice and understood why it was useful, has a high likelyhood of leading to improper implementation which makes the presumed failure a self-fullfilling prophecy. However if taken as guidance, there is a lot of useful information there that can make projects, especially large projects, a lot less painful.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-1115902980646457342?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2009/02/how-i-became-solid-advocate-and-didnt.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>1</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-5614366076746848342</guid><pubDate>Mon, 26 Jan 2009 17:44:00 +0000</pubDate><atom:updated>2009-01-26T09:48:06.902-08:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>deki</category><category domain='http://www.blogger.com/atom/ns#'>mindtouch</category><title>Yet another blog to divert my attention</title><description>I'm now posting on yet another blog, diverting my attention from here. Just added a post on the &lt;a href="http://blog.developer.mindtouch.com"&gt;MindTouch Developers blog&lt;/a&gt; about the &lt;a href="http://blog.developer.mindtouch.com/2009/01/25/bing-your-deki-has-changed/"&gt;upcoming pubsub/event&lt;/a&gt; system for &lt;a href="http://wiki.developer.mindtouch.com/MindTouch_Deki"&gt;Deki&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-5614366076746848342?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2009/01/yet-another-blog-to-divert-my-attention.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-9991642.post-5165303867913638071</guid><pubDate>Sat, 10 Jan 2009 18:38:00 +0000</pubDate><atom:updated>2009-01-10T10:43:43.201-08:00</atom:updated><category domain='http://www.blogger.com/atom/ns#'>db4o</category><category domain='http://www.blogger.com/atom/ns#'>mono</category><category domain='http://www.blogger.com/atom/ns#'>c#</category><title>db4o 7.4 binaries for mono</title><description>As I &lt;a href="http://www.claassen.net/geek/blog/2009/01/db4o-on-net-and-mono.html"&gt;talked about recently&lt;/a&gt;, the standard binaries for db4o have some issues with mono, so I recompiled the unmodified source with the MONO configuration flag. I've packed up both the debug and release binaries and you can get them &lt;a href="http://www.claassen.net/geek/blog/db4o-7.4.mono.tar.gz"&gt;here&lt;/a&gt;. These are just the binaries (plus license). It's not the full db4o package. If you want the full package, just get it directly from the &lt;a href="http://db4o.com/"&gt;db4o site&lt;/a&gt;, since the MONO config flag and have Visual Studio rebuild the package.

&lt;p&gt;This package should show up on the &lt;a href="http://developer.db4o.com/ProjectSpaces/view.aspx/Mono"&gt;official db4o mono page&lt;/a&gt; shortly as well.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9991642-5165303867913638071?l=www.claassen.net%2Fgeek%2Fblog%2Findex.html' alt='' /&gt;&lt;/div&gt;</description><link>http://www.claassen.net/geek/blog/2009/01/db4o-74-binaries-for-mono.html</link><author>noreply@blogger.com (ether)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>4</thr:total></item></channel></rss>