<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="http://feeds.feedburner.com/~d/styles/atom10full.xsl" type="text/xsl" media="screen"?><?xml-stylesheet href="http://feeds.feedburner.com/~d/styles/itemcontent.css" type="text/css" media="screen"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"><id>tag:blogger.com,1999:blog-7624394686148711990</id><updated>2008-07-25T14:29:15.040+10:00</updated><title type="text">dave^2 = -1</title><link rel="alternate" type="text/html" href="http://davesquared.blogspot.com/" /><link rel="next" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default?start-index=26&amp;max-results=25&amp;redirect=false" /><link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://davesquared.blogspot.com/feeds/posts/default" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email></author><generator version="7.00" uri="http://www.blogger.com">Blogger</generator><openSearch:totalResults>251</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><link rel="self" href="http://feeds.feedburner.com/davesquared" type="application/atom+xml" /><entry><id>tag:blogger.com,1999:blog-7624394686148711990.post-2737861461231277696</id><published>2008-07-25T10:56:00.006+10:00</published><updated>2008-07-25T14:29:15.056+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".net" /><title type="text">Dodgy .NET memory measurements using counters</title><content type="html">&lt;p&gt;There are a few profilers around that can measure CLR memory usage: Microsoft's free &lt;a href="http://www.microsoft.com/downloads/details.aspx?familyid=a362781c-3870-43be-8926-862b40aa0cd0"&gt;CLR Profiler 2.0&lt;/a&gt;, &lt;a href="http://www.jetbrains.com/profiler/"&gt;JetBrains' dotTrace&lt;/a&gt;, &lt;a href="http://www.red-gate.com/Products/ants_profiler/index.htm"&gt;Redgate's ANTS Profiler&lt;/a&gt; etc. However these don't seem to help me much when I'm trying to get some data about specific allocations (say, plotting the size of a list with varying numbers of objects). This could just be my inexperience with the tools, but I think it is more to do with the complexities of memory management for managed code.&lt;/p&gt;

&lt;p&gt;I've also been playing around with taking measurements by programatically accessing the relevant counters, like the Private Bytes counter in the Process category, in the effort to take a number of snapshots before and after some simple allocations and plug them into a spreadsheet.&lt;/p&gt;

&lt;pre&gt;
  privateBytesCounter = new PerformanceCounter(&amp;quot;Process&amp;quot;, &amp;quot;Private Bytes&amp;quot;, name, true);
  var currentMemoryInKB = privateBytesCounter.NextValue()/1024.0;
&lt;/pre&gt;

&lt;p&gt;The name is the relevant instance that appears within perfmon. You need to watch out for invalid characters, but with some care you can derive this value from &lt;code&gt;AppDomain.CurrentDomain.FriendlyName&lt;/code&gt; (you might need to strip off the &amp;quot;.exe&amp;quot; extension in addition to getting rid of any funny characters).&lt;/p&gt;

&lt;p&gt;My aim was to work out the size of some specific objects, but I haven't had too much success with this approach as it's giving me some funny values. A couple of gotchas: You have to watch the timing of the calls getting counter data (don't sample too fast), and if you are measuring a single allocation you can also change the results by forcing a garbage collection prior to measuring (&lt;code&gt;GC.Collect()&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;I think it's time for me to invest in a good CLR book and get better acquainted with .NET's memory model. :)&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/davesquared?a=9vidpj"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=9vidpj" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=J7hhgJ"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=J7hhgJ" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=7jTIUj"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=7jTIUj" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=Pb4tLJ"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=Pb4tLJ" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=wLjLjJ"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=wLjLjJ" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/345191681" height="1" width="1"/&gt;</content><link rel="alternate" type="text/html" href="http://davesquared.blogspot.com/2008/07/dodgy-net-memory-measurements.html" title="Dodgy .NET memory measurements using counters" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=2737861461231277696" title="0 Comments" /><link rel="replies" type="application/atom+xml" href="http://davesquared.blogspot.com/feeds/2737861461231277696/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/2737861461231277696" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/2737861461231277696" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email></author><feedburner:awareness xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://api.feedburner.com/awareness/1.0/GetItemData?uri=davesquared&amp;itemurl=http%3A%2F%2Fdavesquared.blogspot.com%2F2008%2F07%2Fdodgy-net-memory-measurements.html</feedburner:awareness></entry><entry><id>tag:blogger.com,1999:blog-7624394686148711990.post-2370242890567483728</id><published>2008-07-25T00:40:00.020+10:00</published><updated>2008-07-25T08:37:16.303+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".net" /><category scheme="http://www.blogger.com/atom/ns#" term="tdd" /><category scheme="http://www.blogger.com/atom/ns#" term="kata" /><title type="text">Brackets, braces, parentheses, and other such creatures</title><content type="html">&lt;p&gt;I've been fairly busy the last couple of weeks finishing up my current job and preparing for my new one (a really exciting role with a team practising Scrum, TDD etc.), so I haven't been able to dedicate much time to the three potentially bloggable projects I am working on at the moment. The other day I found &lt;a href="http://www.dev102.com/2008/07/21/a-programming-job-interview-challenge-13-brackets/"&gt;Part 13&lt;/a&gt; of a series of coding challenges posted to &lt;a href="http://www.dev102.com"&gt;dev102.com&lt;/a&gt;, and thought I'd give it a go as a quick little exercise.&lt;/p&gt;

&lt;div class="note"&gt;&lt;b&gt;Note:&lt;/b&gt; potential spoiler ahead, in the event you were intending to work through this yourself. That's not to say my solution is even vaguely correct, but if you want to do it completely off your own bat then have a go before you have all my mistakes to help you :)&lt;/div&gt;

&lt;h2&gt;The problem&lt;/h2&gt;
&lt;p&gt;This aim of this challenge was to determine whether any given string has a legal bracket structure. Basically, make sure all the '(', '[', '{', and '&lt;' have matching ')', ']', '}' and '&gt;'. We also need to take nesting into account, so that &amp;quot;({)}&amp;quot; is incorrect, and &amp;quot;({}&lt;{}&gt;)&amp;quot; will pass.&lt;/p&gt;

&lt;p&gt;Part of the challenge is also to &amp;quot;Provide the most efficient, elegant and simple solution&amp;quot;. I'm not even going to attempt that, but I'll try and get something vaguely efficient and, much like this author, simple.&lt;/p&gt;

&lt;h2&gt;Some quick planning&lt;/h2&gt;
&lt;p&gt;Shahar Yair (who posted the challenge) notes &amp;quot;I think that this is a well known problem&amp;quot;. I think (although without a good googling I can't be sure due to my limited cranial capacity) one of the common implementations is to use a stack, and push brackets on as you find them, and pop them off when you close them. If you have an empty stack at the end your string is ok. If a closing bracket doesn't match the bracket on the top of the stack then you have a problem. The beautiful image below (crafted in that great image editor, MS Word) shows the basic idea: pushing on open brackets and popping them off once they get closed.&lt;/p&gt;

&lt;a href="http://bp3.blogger.com/_wEsHWMWy090/SIiVZI9h7UI/AAAAAAAAAng/_7ywVHW8ycg/s1600-h/BracketStackExample.png"&gt;&lt;img src="http://bp3.blogger.com/_wEsHWMWy090/SIiVZI9h7UI/AAAAAAAAAng/_7ywVHW8ycg/s400/BracketStackExample.png" border="0" alt="Using a stack to keep track of open brackets." id="BLOGGER_PHOTO_ID_5226591626698288450" /&gt;&lt;/a&gt;

&lt;p&gt;In terms of efficiency, the worst case for this is when you have a valid string, as you will have had to checked every character at least once (to see if it is a bracket). Using a stack will let us make a single pass through the string.&lt;/p&gt;

&lt;p&gt;With this basic plan in mind, let's start writing some tests. We're not doing real TDD here I guess, as we have an end implementation in mind, but I still feel more comfortable working with the protection of some tests. It will hopefully cut down the amount of silly mistakes I normally make :).&lt;/p&gt;

&lt;h2&gt;Starting small&lt;/h2&gt;
&lt;p&gt;Here are a few easy tests to start off with (I'm using XUnit.NET here. I'm kind of growing attached to the simplicity of it :)):&lt;/p&gt;

&lt;pre&gt;
public class When_matching_brackets {
    BracketMatcher matcher = new BracketMatcher();
    [Fact]
    public void Empty_string_should_pass() {
        should_pass(String.Empty);
    }
    [Fact]
    public void Null_string_should_pass() {
        should_pass(null);
    }    
    private void should_pass(String input) {
        Assert.True(matcher.IsValid(input));
    }
    private void should_fail(String input) {
        Assert.False(matcher.IsValid(input));
    }    
}
public class BracketMatcher {
    public bool IsValid(string input) { return true; }
}&lt;/pre&gt;

&lt;p&gt;We can pass these by just returning true. Let's write a test that will make this fail:&lt;/p&gt;

&lt;pre&gt;
[Fact]
public void Single_bracket() {
    should_fail("(");
}
&lt;/pre&gt;

&lt;p&gt;We can cheat again to pass this:&lt;/p&gt;

&lt;pre&gt;
public class BracketMatcher {
    public bool IsValid(string input) { 
        if (input == null) return true;
        return input.Length &lt; 1;
    }
}&lt;/pre&gt;

&lt;p&gt;To drive the next bit of our algorithm we can add another failing test:&lt;/p&gt;

&lt;pre&gt;
[Fact]
public void Matched_brackets() {
    should_pass("()");
}
&lt;/pre&gt;

&lt;p&gt;We could dodgy this up again, but let's start writing something a bit more realistic -- but only a little.&lt;/p&gt;

&lt;pre&gt;
public class BracketMatcher {
    public bool IsValid(string input) {
        if (input == null) return true;
        int openBrackets = 0;

        foreach (var c in input) {
            if (c == '(') { openBrackets++; }
            else if (c == ')') { openBrackets--; }                                
        }
        return openBrackets == 0;
    }
}
&lt;/pre&gt;

&lt;p&gt;This passes, but it is obviously going to incorrectly return true for an input like &amp;quot;)(&amp;quot;. We'll use this to write our next test. What we are doing here is slowly building up a number of cases that should have a specific result, and writing a minimal (and trivial) implementation to make the test cases pass. The actual time spent doing this is quite short. I doubt anyone would spend any more than a few minutes typing this out. What we gain is momentum, and a test suite for when the time comes to refactor. Maybe it's just me, but if I were going straight to an implementation, I'd generally make great progress for a while but stuff up a sign or an end case or similar, and then spend and inordinate amount of time manually tracing through the code to find where I had gone wrong. The slow-and-steady approach here means less initial speed, but no speed bumps later, and usually a faster* trip overall.&lt;/p&gt;

&lt;p style="font-size: x-small"&gt;* Caution: unsubstantiated anecdote! YMMV&lt;/p&gt;

&lt;h2&gt;Skipping ahead to our first major refactoring&lt;/h2&gt;

&lt;p&gt;After plugging away for a little while I've got the following test cases:&lt;/p&gt;

&lt;pre&gt;
public class When_matching_brackets {
    BracketMatcher matcher = new BracketMatcher();

    [Fact]
    public void Empty_string_should_pass() {
        should_pass(String.Empty);
    }

    [Fact]
    public void Null_string_should_pass() {
        should_pass(null);
    }

    [Fact]
    public void Single_bracket_should_fail() {
        should_fail(&amp;quot;(&amp;quot;);
    }

    [Fact]
    public void Single_bracket_within_string_should_fail() {
        should_fail(&amp;quot;abc(&amp;quot;);
    }

    [Fact]
    public void Matched_brackets_should_pass() {
        should_pass(&amp;quot;()&amp;quot;);
    }

    [Fact]
    public void Matched_brackets_within_string_should_pass() {
        should_pass(&amp;quot;This is (a test).&amp;quot;);
    }

    [Fact]
    public void Matched_brackets_with_single_brace_should_fail() {
        should_fail(&amp;quot;This {is (a test).&amp;quot;);
    }

    [Fact]
    public void Matched_brackets_and_braces_should_pass() {
        should_pass(&amp;quot;This {is} a (test).&amp;quot;);
    }

    &lt;b&gt;[Fact]
    public void Correct_number_but_wrong_nesting_of_brackets_and_braces_should_fail() {
        should_fail(&amp;quot;This {is a (test}).&amp;quot;);
    }&lt;/b&gt;

    private void should_pass(String input) {
        Assert.True(matcher.IsValid(input));
    }

    private void should_fail(String input) {
        Assert.False(matcher.IsValid(input));
    }
}
&lt;/pre&gt; 

&lt;p&gt;The last test (emphasised) is failing with the following implementation (which passes all the other tests), because it fails to take bracket nesting into account:&lt;/p&gt;

&lt;pre&gt;
public class BracketMatcher {             
    public bool IsValid(string input) {
        if (input == null) return true;
        
        var bracketCount = 0;
        var braceCount = 0;
        foreach (var c in input) {                
            if (c == '(') {
                bracketCount++;
            } else if (c == ')') {
                bracketCount--;
            } else if (c == '{') {
                braceCount++;
            } else if (c == '}') {
                braceCount--;
            }
        }
        return bracketCount == 0 &amp;&amp; braceCount == 0;
    }
}
&lt;/pre&gt;

&lt;p&gt;You can also see I have duplicated the counters for braces and brackets, and we'll only be adding to this problem when it comes time to add the other bracket types. Let's refactor to remove this, and get in the stack idea we talked about earlier.&lt;/p&gt;

&lt;pre&gt;
public class BracketMatcher {                  
    public bool IsValid(string input) {            
        if (input == null) return true;

        var bracketStack = new Stack&amp;lt;char&amp;gt;();
        foreach (var c in input) {                
            if (c == '(') {
                bracketStack.Push(c);
            } else if (c == ')') {
                if (bracketStack.Pop() != '(') return false;
            } else if (c == '{') {
                bracketStack.Push(c);
            } else if (c == '}') {
                if (bracketStack.Pop() != '{') return false;
            }
        }
        return bracketStack.Count == 0;
    }
}
&lt;/pre&gt; 

&lt;p&gt;This passes all our tests, but it's still ugly. The pushes and pops obscure the algorithm we are using. Sure, you can pick it out by tracing through a few cases, but it would be nicer to get the gist of it by inspection alone. We also have some duplicated &lt;code&gt;if (bracketStack.Pop() != '(') return false;&lt;/code&gt; style code happening, but now we are at least passing all our tests, we can continue to work toward removing the ugliness without breaking what we have.&lt;/p&gt;

&lt;pre&gt;
public class BracketMatcher {
    private static Dictionary&amp;lt;char, char&amp;gt; bracketPairs
        = new Dictionary&amp;lt;char, char&amp;gt; { {'(', ')'}, {'{', '}'} };

    public bool IsValid(string input) {
        if (input == null) return true;

        var bracketStack = new Stack&amp;lt;char&amp;gt;();
        foreach (var c in input) {
            if (bracketPairs.ContainsKey(c)) {
                bracketStack.Push(c);
            } else if (bracketPairs.ContainsValue(c)) {
                char lastBracket = bracketStack.Pop();
                if (bracketPairs[lastBracket] != c) return false;
            }
        }
        return bracketStack.Count == 0;
    }
}
&lt;/pre&gt;

&lt;p&gt;This version is a bit of an improvement: we have removed the duplication by adding a dictionary of bracket pairs. It still isn't exactly intention revealing though with those key/value checks and pushing and popping. I'll go out on a limb here though, and suggest that it's much better than the implementation we opened this section with.&lt;/p&gt;    

&lt;h2&gt;Finishing up&lt;/h2&gt;
&lt;p&gt;A few more tests, and a refactoring later, and here's what I ended up with:&lt;/p&gt;

&lt;pre&gt;
public class BracketMatcher {
    private static readonly Dictionary&amp;lt;char, char&amp;gt; bracketPairs
        = new Dictionary&amp;lt;char, char&amp;gt; { {'(', ')'}, {'{', '}'}, {'[', ']'}, {'&amp;lt;', '&amp;gt;'} };

    private Stack&amp;lt;char&amp;gt; bracketStack;

    &lt;b&gt;public bool IsValid(string input) {        
        if (input == null) return true;
        clearOpenedBrackets();
        foreach (var c in input) {
            if (isOpenBracket(c)) {
                recordBracketOpening(c);
            } else if (isCloseBracket(c)) {
                if (!canCloseLastOpenBracket(c)) return false;
                closeLastOpenedBracket();                    
            }
        }
        return areAllBracketsClosed();
    }&lt;/b&gt;

    private void clearOpenedBrackets() {
      bracketStack = new Stack&amp;lt;char&amp;gt;();
    }

    private bool areAllBracketsClosed() {
      return bracketStack.Count == 0;
    }

    private void closeLastOpenedBracket() {
        bracketStack.Pop();
    }

    private bool canCloseLastOpenBracket(char bracket) {
        if (areAllBracketsClosed()) return false;
        char lastOpenBracket = bracketStack.Peek();
        char closingBracket = bracketPairs[lastOpenBracket];
        return bracket == closingBracket;
    }

    private void recordBracketOpening(char bracket) {
        bracketStack.Push(bracket);
    }

    private bool isOpenBracket(char c) {
        return bracketPairs.ContainsKey(c);
    }

    private bool isCloseBracket(char c) {
        return bracketPairs.ContainsValue(c);
    }
}
&lt;/pre&gt;

&lt;p&gt;I think &lt;code&gt;IsValid(...)&lt;/code&gt; is actually reading pretty well here. The intent of the operation is fairly clear from a quick read through, with no implementation details like pops and pushes scattered around the code. The implementation itself is pushed to fairly simple helper methods.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;canCloseLastOpenBracket(...)&lt;/code&gt; method is a bit ugly, but it is only four lines, has descriptive variable names, and is tucked away in a private method. It's also a bit inefficient, as we are doing an unecessary &lt;code&gt;Peek()&lt;/code&gt; before &lt;code&gt;Pop()&lt;/code&gt;ing the value off the stack. I rewrote the code several ways, but any approach that combined the &lt;code&gt;Pop()&lt;/code&gt; with matching the brackets tended to obscure what the code was doing. I've had a minor method-count explosion, but they are all small and self-explanatory (less lines that commenting the previous version in any event ;)).&lt;/p&gt;

&lt;p&gt;We might be able to simplify this in a number of ways, like putting the required closing brackets on the stack to make the matching more straightforward, but the other approaches I tried all seemed to compromise readability to some extent, so I ended up sticking with the verbosity of this version. I'm sure you can do better (leave a comment!), but for now it's passing the tests thrown at it and I can live with how it reads. Which means we're as good as done. :)&lt;/p&gt;

&lt;p&gt;Speaking of done, here's the test suite it passes:&lt;/p&gt;

&lt;pre&gt;
public class When_matching_brackets {
    BracketMatcher matcher = new BracketMatcher();

    [Fact]
    public void Empty_string() {
        should_pass(String.Empty);
    }

    [Fact]
    public void Null_string() {
        should_pass(null);
    }

    [Fact]
    public void Single_bracket() {
        should_fail(&amp;quot;(&amp;quot;);
    }

    [Fact]
    public void Single_closing_bracket() {
        should_fail(&amp;quot;)&amp;quot;);
    }

    [Fact]
    public void Single_bracket_within_string() {
        should_fail(&amp;quot;abc(&amp;quot;);
    }

    [Fact]
    public void Matched_brackets() {
        should_pass(&amp;quot;()&amp;quot;);
    }

    [Fact]
    public void Matched_brackets_within_string() {
        should_pass(&amp;quot;This is (a test).&amp;quot;);
    }

    [Fact]
    public void Missing_a_brace() {
        should_fail(&amp;quot;This {is (a test).&amp;quot;);
    }

    [Fact]
    public void Pairs_of_matched_brackets_and_braces() {
        should_pass(&amp;quot;This {is} a (test).&amp;quot;);
    }

    [Fact]
    public void Incorrect_nesting_of_brackets_and_braces() {
        should_fail(&amp;quot;This {is a (test}).&amp;quot;);
    }

    [Fact]
    public void Valid_nesting_with_multiple_types() {
        should_pass(&amp;quot;&amp;lt;Hello (World), ({how} are) you today&amp;gt;?&amp;quot;);
    }

    [Fact]
    public void Multiple_pairs() {
        should_pass(&amp;quot;(Hello) {World}, &amp;lt;how&amp;gt; are (you) today?&amp;quot;);
    }

    [Fact]
    public void Multiple_lines_with_valid_brackets() {
        should_pass(@&amp;quot;(Hello {World,
                        How are you}
                        ?)&amp;quot;);
    }

    [Fact]
    public void Multiple_lines_with_invalid_brackets() {
        should_fail(@&amp;quot;(Hello {World,
                        How are you)
                        ?)&amp;quot;);
    }

    [Fact]
    public void Valid_example_from_problem_statement() {
        should_pass(&amp;quot;([](&amp;lt;{}&amp;gt;))&amp;quot;);
    }

    [Fact]
    public void Invalid_example_from_problem_statement() {
        should_fail(&amp;quot;({&amp;lt;)&amp;gt;}&amp;quot;);
    }

    [Fact]
    public void Matching_square_brackets() {
        should_pass(&amp;quot;[asdf]&amp;quot;);
    }

    [Fact]
    public void Single_square_bracket() {
        should_fail(&amp;quot;[&amp;quot;);
    }

    [Fact]
    public void Single_angle_bracket() {
        should_fail(&amp;quot;&amp;lt;&amp;quot;);
    }
    [Fact]
    public void Matching_angle_brackets() {
        should_pass(&amp;quot;&amp;lt;&amp;gt;&amp;quot;);  
    }

    private void should_pass(String input) {
        Assert.True(matcher.IsValid(input));
    }

    private void should_fail(String input) {
        Assert.False(matcher.IsValid(input));
    }
}
&lt;/pre&gt;

&lt;p&gt;Was a bit of fun for a half hour or so :) Please feel free to leave a comment if you have any suggested improvements (or better yet, some failing tests!).&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/davesquared?a=XXacgj"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=XXacgj" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=KrP9vJ"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=KrP9vJ" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=LfR1Xj"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=LfR1Xj" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=lNlr1J"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=lNlr1J" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=RBwD1J"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=RBwD1J" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/344674879" height="1" width="1"/&gt;</content><link rel="alternate" type="text/html" href="http://davesquared.blogspot.com/2008/07/brackets-braces-parenthesis-and-other.html" title="Brackets, braces, parentheses, and other such creatures" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=2370242890567483728" title="0 Comments" /><link rel="replies" type="application/atom+xml" href="http://davesquared.blogspot.com/feeds/2370242890567483728/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/2370242890567483728" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/2370242890567483728" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email></author><feedburner:awareness xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://api.feedburner.com/awareness/1.0/GetItemData?uri=davesquared&amp;itemurl=http%3A%2F%2Fdavesquared.blogspot.com%2F2008%2F07%2Fbrackets-braces-parenthesis-and-other.html</feedburner:awareness></entry><entry><id>tag:blogger.com,1999:blog-7624394686148711990.post-144047951314503143</id><published>2008-07-18T09:34:00.004+10:00</published><updated>2008-07-18T13:26:22.260+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="database" /><title type="text">Getting results from Oracle procedures for TSQL people</title><content type="html">&lt;p&gt;I haven't used Oracle since Uni, and the small amount of PL/SQL I've had to do over the last year hasn't been enough to get me passed the awkward SQL Server developer-trapped-in-a-PL/SQL world phase yet. (Although I am enjoying it much more now I've got a real IDE in Toad, compared with the ancient, clunky piece of rubbish I was using before.)&lt;/p&gt;

&lt;p&gt;In SQL Server, anything you SELECT inside a procedure will be returned to the caller, which makes it really easy to call an SP in Query Analyzer or similar and see what's happening. Oracle is, well, different. You need to explicitly return cursors over results, and unless you call it the right way all you'll get is a handy &amp;quot;PL/SQL procedure successfully completed&amp;quot; message.&lt;/p&gt;

&lt;p&gt;Here's a quick example of how TSQL people can get results out of Oracle with a minimum of fuss. First, say we have a simple procedure that takes a postcode (aka ZIP code) and returns matching results:&lt;/p&gt;

&lt;pre&gt;
CREATE OR REPLACE PROCEDURE GetSamplesByPostcode 
(
    pi_postCode IN NUMBER,
    samples OUT SYS_REFCURSOR
) 
IS
BEGIN
    OPEN samples FOR
    SELECT *
    FROM SAMPLE s
    WHERE s.PostCode = pi_postCode;
END GetSamplesByPostcode;
&lt;/pre&gt;

&lt;p&gt;We can then call this within SQL*Plus or Toad, by turning on autoprint, and by using a bind variable to get the results out:&lt;/p&gt;

&lt;pre&gt;
SET AUTOPRINT ON
VAR sample_cur REFCURSOR;
BEGIN
    GetSamplesByPostcode(2000, :sample_cur);
END;
&lt;/pre&gt;

&lt;p&gt;This will print the relevant results returned by the bound &lt;code&gt;sample_cur&lt;/code&gt; variable, and give Toad users a nice grid view of the results too.&lt;/p&gt;

&lt;p&gt;Check the Oracle docs for more on &lt;a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14357/ch5.htm#sthref1118"&gt;bind variables&lt;/a&gt;.&lt;/p&gt;

&lt;div class="note"&gt;If you want to get at the data using .NET, check out the &lt;a href="http://download.oracle.com/docs/cd/B19306_01/win.102/b14307/toc.htm"&gt;Oracle .NET Data Provider documentation&lt;/a&gt;, or MSDN for an overview on using the &lt;a href="http://msdn.microsoft.com/en-us/library/ms971506.aspx"&gt;Microsoft .NET Oracle Provider&lt;/a&gt;.&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/davesquared?a=2ibGej"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=2ibGej" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=4BGhWJ"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=4BGhWJ" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=80gDlj"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=80gDlj" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=eSPVUJ"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=eSPVUJ" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=v8PSeJ"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=v8PSeJ" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/338579829" height="1" width="1"/&gt;</content><link rel="alternate" type="text/html" href="http://davesquared.blogspot.com/2008/07/getting-results-from-oracle-procedures.html" title="Getting results from Oracle procedures for TSQL people" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=144047951314503143" title="1 Comments" /><link rel="replies" type="application/atom+xml" href="http://davesquared.blogspot.com/feeds/144047951314503143/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/144047951314503143" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/144047951314503143" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email></author><feedburner:awareness xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://api.feedburner.com/awareness/1.0/GetItemData?uri=davesquared&amp;itemurl=http%3A%2F%2Fdavesquared.blogspot.com%2F2008%2F07%2Fgetting-results-from-oracle-procedures.html</feedburner:awareness></entry><entry><id>tag:blogger.com,1999:blog-7624394686148711990.post-4594826016224699468</id><published>2008-07-04T11:00:00.000+10:00</published><updated>2008-07-04T11:24:45.742+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="misc" /><title type="text">Full disclosure: Bought off with a ReSharper licence</title><content type="html">&lt;p&gt;In the interest of full disclosure, I recently got sent a free ReSharper 4.0 Personal Licence from JetBrains. I really don't know why. The explanation in the email I received was very generic: &lt;i&gt;&amp;quot;for donating so much of your time... whether in the form of plugin development, quality verifying, promoting or educating about ReSharper&amp;quot;&lt;/i&gt;.&lt;/p&gt;

&lt;p&gt;I emailed them back and asked why I got included in the list for a free licence, but haven't received a response. All I've done for ReSharper/JetBrains is left them a comment or two, downloaded the R# 4.0 nightlies and maybe even tried to submit one of those automated bug submission thingoes (which I think failed due to the proxy at my work). I have blogged a couple of times on ReSharper, although never anything high-traffic. So I'm at a loss to explain why.&lt;/p&gt;

&lt;p&gt;I haven't used the licence yet (was hoping to find out why I got it first), but I guess you can probably disregard anything positive I've ever said about R# now I'm owned by them after being sent free swag. In fact, just assume from now on that I have absolutely no integrity whatsoever. Luckily astute readers are already way ahead of me on that... :)&lt;/p&gt;

&lt;p&gt;And no, I can't give it to you instead because the licence is non-transferable :P&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/davesquared?a=GeHU8j"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=GeHU8j" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=UVuQkJ"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=UVuQkJ" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=ZNpA2j"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=ZNpA2j" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=PTiABJ"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=PTiABJ" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=wvbffJ"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=wvbffJ" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/326274033" height="1" width="1"/&gt;</content><link rel="alternate" type="text/html" href="http://davesquared.blogspot.com/2008/07/full-disclosure-bought-off-with.html" title="Full disclosure: Bought off with a ReSharper licence" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=4594826016224699468" title="3 Comments" /><link rel="replies" type="application/atom+xml" href="http://davesquared.blogspot.com/feeds/4594826016224699468/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/4594826016224699468" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/4594826016224699468" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email></author><feedburner:awareness xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://api.feedburner.com/awareness/1.0/GetItemData?uri=davesquared&amp;itemurl=http%3A%2F%2Fdavesquared.blogspot.com%2F2008%2F07%2Ffull-disclosure-bought-off-with.html</feedburner:awareness></entry><entry><id>tag:blogger.com,1999:blog-7624394686148711990.post-2721606840602232949</id><published>2008-07-02T14:04:00.006+10:00</published><updated>2008-07-02T15:58:56.457+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="javascript" /><title type="text">Write out the fields of a JavaScript object</title><content type="html">&lt;p&gt;I've found myself writing this bit of code a few times now, so thought I'd dump it here for future copy-and-paste.&lt;/p&gt;

&lt;pre&gt;
function writeObj(obj, message) {
  if (!message) { message = obj; }
  var details = &amp;quot;*****************&amp;quot; + &amp;quot;\n&amp;quot; + message + &amp;quot;\n&amp;quot;;
  var fieldContents;
  for (var field in obj) {
    fieldContents = obj[field];
    if (typeof(fieldContents) == &amp;quot;function&amp;quot;) {
      fieldContents = &amp;quot;(function)&amp;quot;;
    }
    details += &amp;quot;  &amp;quot; + field + &amp;quot;: &amp;quot; + fieldContents + &amp;quot;\n&amp;quot;;
  }
  console.log(details);
}
&lt;/pre&gt;

&lt;p&gt;This just dumps all the object's fields into the debugging console provided by the &lt;a href="http://getfirebug.com"&gt;Firebug&lt;/a&gt; extension for Firefox (the &lt;code&gt;console.log(...)&lt;/code&gt; call). If you don't have Firebug, you can easily create a custom &lt;code&gt;console&lt;/code&gt; object to provide an alternative log method. For example, put this snippet at the top of the script to use &lt;code&gt;window.alert(...)&lt;/code&gt; when &lt;code&gt;console&lt;/code&gt; is undefined:&lt;/p&gt;

&lt;pre&gt;
if (!console) {
  var console = {log: function(details) { window.alert(details); }}
}
&lt;/pre&gt;

&lt;p&gt;There are probably better ways of doing this, but I find this handy so I can quickly mash &lt;code&gt;writeObj(myObject)&lt;/code&gt; into the console and get a list of all the object's fields. For more fun with simple JavaScript reflection have a look at my &lt;a href="http://davesquared.blogspot.com/2007/11/reflecting-on-javascript-objects.html"&gt;earlier post on the subject&lt;/a&gt;.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/davesquared?a=bIwN2j"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=bIwN2j" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=RHMreJ"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=RHMreJ" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=IUETCj"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=IUETCj" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=tyH9kJ"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=tyH9kJ" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=jPpEbJ"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=jPpEbJ" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/324580794" height="1" width="1"/&gt;</content><link rel="alternate" type="text/html" href="http://davesquared.blogspot.com/2008/07/write-out-fields-of-javascript-object.html" title="Write out the fields of a JavaScript object" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=2721606840602232949" title="0 Comments" /><link rel="replies" type="application/atom+xml" href="http://davesquared.blogspot.com/feeds/2721606840602232949/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/2721606840602232949" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/2721606840602232949" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email></author><feedburner:awareness xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://api.feedburner.com/awareness/1.0/GetItemData?uri=davesquared&amp;itemurl=http%3A%2F%2Fdavesquared.blogspot.com%2F2008%2F07%2Fwrite-out-fields-of-javascript-object.html</feedburner:awareness></entry><entry><id>tag:blogger.com,1999:blog-7624394686148711990.post-2278078507427051348</id><published>2008-06-23T11:03:00.001+10:00</published><updated>2008-06-23T11:27:59.716+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".net" /><title type="text">@ prefix for C# names</title><content type="html">&lt;p&gt;Who'd have thought I'd learn something over &lt;a href="http://www.twitter.com"&gt;Twitter&lt;/a&gt; (during an uncharacteristic period of uptime)? Nothing overly useful mind you, just an interesting bit of trivia. :)&lt;/p&gt;    &lt;p&gt;Besides &amp;quot;yuck&amp;quot;, what would you think when you saw the following C# code?&lt;/p&gt;  &lt;pre&gt;
class @class {
  public string @someValue;
  public int @int;
}

[Test]
public void TestAtClass() {
  @class myclass = new @class();
  myclass.@int = 10;
  myclass.@someValue = &amp;quot;test&amp;quot;;
}
&lt;/pre&gt;

&lt;p&gt;Prior to today I'd have thought that it wouldn't compile, but after seeing &lt;a href="http://twitter.com/bradwilson/statuses/841213799"&gt;a tweet from Brad Wilson&lt;/a&gt; that mentioned you could use @ to prefix variable names I thought I'd give it a try, and sure enough the C# compiler is happy. Brad's tweet was about using @ to prefix reserved words so you can get names like @class.&lt;/p&gt;

&lt;p&gt;Bit evil perhaps, but all those @'s might make some &lt;a href="http://rubylearning.com/satishtalim/ruby_names.html"&gt;Rubyists feel a bit more at home&lt;/a&gt; in C# ;-)&lt;/p&gt;  &lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/davesquared?a=72vtAi"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=72vtAi" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=Gm8arI"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=Gm8arI" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=siRTii"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=siRTii" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=6Frq3I"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=6Frq3I" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=j5f1SI"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=j5f1SI" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/317746318" height="1" width="1"/&gt;</content><link rel="alternate" type="text/html" href="http://davesquared.blogspot.com/2008/06/prefix-for-c-names.html" title="@ prefix for C# names" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=2278078507427051348" title="2 Comments" /><link rel="replies" type="application/atom+xml" href="http://davesquared.blogspot.com/feeds/2278078507427051348/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/2278078507427051348" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/2278078507427051348" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email></author><feedburner:awareness xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://api.feedburner.com/awareness/1.0/GetItemData?uri=davesquared&amp;itemurl=http%3A%2F%2Fdavesquared.blogspot.com%2F2008%2F06%2Fprefix-for-c-names.html</feedburner:awareness></entry><entry><id>tag:blogger.com,1999:blog-7624394686148711990.post-889052059271844705</id><published>2008-06-21T23:16:00.008+10:00</published><updated>2008-06-26T09:26:58.239+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="imho" /><category scheme="http://www.blogger.com/atom/ns#" term=".net" /><category scheme="http://www.blogger.com/atom/ns#" term="dev practices" /><title type="text">Yet another way of raising events from mocks</title><content type="html">&lt;p&gt;&lt;i&gt;&lt;b&gt;Update 2008-06-26&lt;/b&gt;: This is &lt;a href="http://groups.google.com/group/RhinoMocks/browse_frm/thread/b7c865a8827594a0/6a70d267c4c33884?tvc=1#6a70d267c4c33884"&gt;now in the Rhino Mocks trunk&lt;/a&gt;, so it should be available as part of the 3.5 release.&lt;/i&gt;&lt;/p&gt;

&lt;p&gt;I've been playing around with raising events from mocks for the last couple of nights, and think I've finally come up with an approach that works for me. Finding a nice way of raising these events is particularly tricky for mock object frameworks, as the C# compiler is really picky about how you can use event references. For example, let's look at a very useful interface:&lt;/p&gt;

&lt;pre&gt;
public interface IDoSomething {    
    event EventHandler SomethingDone;
}
&lt;/pre&gt;

&lt;p&gt;Outside of a class that implements &lt;code&gt;IDoSomething&lt;/code&gt;, the only time we can reference &lt;code&gt;SomethingDone&lt;/code&gt; is when we are adding or removing listeners (&lt;code&gt;x.SomethingDone += someEventHandler;&lt;/code&gt; or &lt;code&gt;x.SomethingDone -= someEventHandler;&lt;/code&gt;). (&lt;a href="http://codebetter.com/blogs/matthew.podwysocki/archive/2008/06/06/functional-c-revisited-into-the-great-void.aspx"&gt;C#'s lack of real support for System.Void&lt;/a&gt; is partly to blame here, as both these operations are void.)&lt;/p&gt;

&lt;p&gt;To raise an event on a mock object, it would be lovely to be able to code something like this:&lt;/p&gt;

&lt;pre&gt;
var mock = mocks.DynamicMock&lt;IDoSomething&gt;();
mock.Raise(&lt;b&gt;mock.SomethingDone&lt;/b&gt;, mock, EventArgs.Empty);
&lt;/pre&gt;

&lt;p&gt;Unfortunately due to the aforementioned constraint, the emphasised part of the code will give a compiler error stating &lt;i&gt;&amp;quot;The event 'IDoSomething.SomethingDone' can only appear on the left hand side of += or -=&amp;quot;&lt;/i&gt;.&lt;/p&gt;

&lt;p&gt;There are a few workarounds for this. Let's start with the &lt;a href="http://www.ayende.com/Wiki/Rhino+Mocks+IEventRaiser.ashx"&gt;standard Rhino Mocks approach&lt;/a&gt;. (I'm using &lt;a href="http://www.ayende.com/Blog/archive/2008/05/16/Rhino-Mocks--Arrange-Act-Assert-Syntax.aspx"&gt;Rhino Mocks 3.5 beta&lt;/a&gt; and &lt;a href="http://www.codeplex.com/xunit"&gt;xUnit.net&lt;/a&gt; here -- feel free to translate from [Fact] to [Test] if you use NUnit, MBUnit et al.)&lt;/p&gt;

&lt;pre&gt;
[Fact]
public void Raise_event_old_style() {
    var mock = mocks.DynamicMock&amp;lt;IDoSomething&amp;gt;();
    &lt;b&gt;mock.SomethingDone += null;
    IEventRaiser eventRaiser = LastCall.IgnoreArguments().GetEventRaiser();&lt;/b&gt;
    mocks.ReplayAll();

    var wasCalled = false;
    mock.SomethingDone += (sender, e) =&amp;gt; wasCalled = true;
    &lt;b&gt;eventRaiser.Raise(mock, EventArgs.Empty);&lt;/b&gt;

    mocks.VerifyAll();  
    Assert.True(wasCalled);
}
&lt;/pre&gt;

&lt;p&gt;Rhino Mocks records the expectation that an event handler is added, then uses &lt;code&gt;LastCall&lt;/code&gt; to ignore the argument and gets an &lt;code&gt;IEventRaiser&lt;/code&gt; for the last event referenced. That &lt;code&gt;IEventRaiser&lt;/code&gt; can be used later on to raise our event. Phil Haack has &lt;a href="http://haacked.com/archive/2006/06/23/UsingRhinoMocksToUnitTestEventsOnInterfaces.aspx"&gt;a helpful post which explains a bit more&lt;/a&gt; about this approach.&lt;/p&gt;

&lt;p&gt;When I first saw this I must admit it seemed like a lot of noise that obscured what I was really trying to do. This got worse when I started playing around with the new &lt;a href="http://www.ayende.com/Blog/archive/2008/05/16/Rhino-Mocks--Arrange-Act-Assert-Syntax.aspx"&gt;Arrange - Act - Assert&lt;/a&gt; syntax and I didn't want to go through the whole replay / verify cycle. So I started looking at the Rhino Mocks implementation of &lt;code&gt;IEventRaiser&lt;/code&gt;, the &lt;code&gt;EventRaiser&lt;/code&gt; class. This class lets us do this:&lt;/p&gt;

&lt;pre&gt;
[Fact]
public void Raise_event_using_string_for_event_name() {
    var mock = mocks.DynamicMock&amp;lt;IDoSomething&amp;gt;();
    var wasCalled = false;
    mock.SomethingDone += (sender, e) =&amp;gt; wasCalled = true;

    &lt;b&gt;var eventRaiser = EventRaiser.Create(mock, &amp;quot;SomethingDone&amp;quot;);
    eventRaiser.Raise(mock, EventArgs.Empty);&lt;/b&gt;
    
    Assert.True(wasCalled);
}
&lt;/pre&gt;

&lt;p&gt;Here we can specify the relevant event using a string. This works nicely and is easy to read, but causes problems when refactoring and means we don't get intellisense or compiler assistance. &lt;a href="http://www.ayende.com/Blog/archive/2007/06/08/Rhino-Mocks-Events-Purity-vs.-Practicality.aspx"&gt;Ayende has written about this approach&lt;/a&gt;, comparing it with the &lt;code&gt;LastCall.GetEventRaiser()&lt;/code&gt; approach we used last time.&lt;/p&gt;

&lt;p&gt;I wasn't overjoyed about either of these, and while searching around for other options I found another of Ayende's posts (I think his blog is about 30% of the web... great stuff :)), asking for feedback on a &lt;a href="http://www.ayende.com/Blog/archive/2007/06/23/Natural-Event-Syntax-for-Rhino-Mocks.aspx"&gt;more natural syntax for raising events from mocks&lt;/a&gt;. This looked a bit like this:&lt;/p&gt;

&lt;pre&gt;
mock.MyEvent += EventRaiser.Raise(this, EventArgs.Empty);
&lt;/pre&gt;

&lt;p&gt;I quite liked this, but there were a few complaints in the comments about subscribing to and raising the event at the same time. The post was from about 12 months prior to me writing this and, as I'm using a recent Rhino Mocks build and couldn't find it, it looks like nothing came of this. Let's look for a compromise that also fits in nicely with our Arrange - Act - Assert approach. First we'll see what we can get working based on the first, &lt;code&gt;LastCall.GetEventRaiser()&lt;/code&gt; approach used:&lt;/p&gt;

&lt;pre&gt;
[Fact]
public void Raise_event_with_new_arrange_act_assert_syntax() {
    //Arrange
    var mock = MockRepository.GenerateMock&amp;lt;IDoSomething&amp;gt;();
    var wasCalled = false;
    mock.SomethingDone += (sender, e) =&amp;gt; wasCalled = true;
    
    &lt;b&gt;var eventRaiser = 
        mock
        .Stub(x =&amp;gt; x.SomethingDone += null)
        .IgnoreArguments()
        .GetEventRaiser();&lt;/b&gt;
    
    //Act
    &lt;b&gt;eventRaiser.Raise(mock, EventArgs.Empty);&lt;/b&gt;

    //Assert
    Assert.True(wasCalled);
}
&lt;/pre&gt;

&lt;p&gt;Here we are specifying a fairly useless stub so we can get an &lt;code&gt;IEventRaiser&lt;/code&gt;. We are still using ye olde  &lt;code&gt;x.SomethingDone += null&lt;/code&gt; trick (albeit with a lambda to neaten it up), but we are pretty much stuck with that if we want strong typing on this as discussed at the beginning of this post.&lt;/p&gt;

&lt;p&gt;I think this looks a bit more cohesive now we are using the lambda. We have one statement that is fairly obviously getting an &lt;code&gt;IEventRaiser&lt;/code&gt;, rather than a null event handler floating around on its own confusing poor people like me :). Beyond aesthetics, this cohesion can let us pull out this functionality and start getting closer to a neater syntax. For now we'll just whack this in a .NET 3.5 extension method, but we could probably find a better home for it (it can go in a standalone class but the final syntax doesn't read quite as well to me).&lt;/p&gt;

&lt;pre&gt;
public static class EventRaiserExtensions {
    private static IEventRaiser GetEventRaiserFromSubscription&amp;lt;TEventSource&amp;gt;(
        this TEventSource mock, Action&amp;lt;TEventSource&amp;gt; eventSubscription) {
        &lt;b&gt;return mock
            .Stub(eventSubscription)
            .IgnoreArguments()
            .GetEventRaiser();&lt;/b&gt;
    }
    
    public static void Raise&amp;lt;TEventSource&amp;gt;(this TEventSource mock, Action&amp;lt;TEventSource&amp;gt; eventSubscription, object sender, EventArgs args) {
        var eventRaiser = GetEventRaiserFromSubscription(mock, eventSubscription);
        eventRaiser.Raise(sender, args);
    }

    public static void Raise&amp;lt;TEventSource&amp;gt;(this TEventSource mock, Action&amp;lt;TEventSource&amp;gt; eventSubscription, params object[] args) {
        var eventRaiser = GetEventRaiserFromSubscription(mock, eventSubscription);
        eventRaiser.Raise(args);
    }        

    public static void Raise&amp;lt;TEventSource&amp;gt;(this TEventSource mock, Action&amp;lt;TEventSource&amp;gt; eventSubscription) {
        var eventRaiser = GetEventRaiserFromSubscription(mock, eventSubscription);
        eventRaiser.Raise(mock, EventArgs.Empty);
    }    
}
&lt;/pre&gt;

&lt;p&gt;The emphasised bit of code is the stub call we did last time, but this time pulled out into one method. The main bits are the &lt;code&gt;Raise&amp;lt;TEventSource&amp;gt;&lt;/code&gt; extension methods, which combine all the steps and give us an easy syntax for calling an event on a mock based on an event subscription delegate. So our example now looks like this:&lt;/p&gt;

&lt;pre&gt;
[Fact]
public void Suggestion_for_raising_events() {
    var mock = MockRepository.GenerateMock&amp;lt;IDoSomething&amp;gt;();
    var wasCalled = false;
    mock.SomethingDone += (sender, e) =&amp;gt; wasCalled = true;

    &lt;b&gt;mock.Raise(x =&amp;gt; x.SomethingDone += null, mock, EventArgs.Empty);&lt;/b&gt;

    Assert.True(wasCalled);
}
&lt;/pre&gt;

&lt;p&gt;The implementation itself might need work, but I reckon that syntax is pretty neat considering the limitations of C#. Of course, you're welcome to think otherwise, so please leave a comment expressing your outrage and/or contempt :).&lt;/p&gt;

&lt;p&gt;Disclaimer: I am fairly new to Rhino Mocks (have tended to stick to manual test doubles) and especially to Arrange - Act - Assert (it's only in beta at present), so this might fail pretty hard in other circumstances. Still, I thought I'd post the syntax in case it gave more knowledgable people some good ideas :)&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/davesquared?a=LwgkXi"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=LwgkXi" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=6tOkaI"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=6tOkaI" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=hDTAZi"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=hDTAZi" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=VpC68I"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=VpC68I" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=yCvrlI"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=yCvrlI" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/316896221" height="1" width="1"/&gt;</content><link rel="alternate" type="text/html" href="http://davesquared.blogspot.com/2008/06/yet-another-way-of-raising-events-from.html" title="Yet another way of raising events from mocks" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=889052059271844705" title="0 Comments" /><link rel="replies" type="application/atom+xml" href="http://davesquared.blogspot.com/feeds/889052059271844705/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/889052059271844705" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/889052059271844705" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email></author><feedburner:awareness xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://api.feedburner.com/awareness/1.0/GetItemData?uri=davesquared&amp;itemurl=http%3A%2F%2Fdavesquared.blogspot.com%2F2008%2F06%2Fyet-another-way-of-raising-events-from.html</feedburner:awareness></entry><entry><id>tag:blogger.com,1999:blog-7624394686148711990.post-3851447511485299387</id><published>2008-06-20T09:20:00.002+10:00</published><updated>2008-06-20T09:37:38.493+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="tools" /><title type="text">Subversion 1.5.0 released</title><content type="html">&lt;p&gt;Just saw that &lt;a href="http://blogs.open.collab.net/svn/2008/06/subversion-150.html"&gt;Subversion 1.5.0 has been released&lt;/a&gt;. There are quite a few new features, but the main ones of interest to me are:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://blog.red-bean.com/sussman/?p=92"&gt;basic merge tracking&lt;/a&gt; (to be improved in 1.5.1) &lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.open.collab.net/svn/2007/07/one-quality-of-.html"&gt;changelist support&lt;/a&gt; for working with common file groupings &lt;/li&gt;    &lt;li&gt;&lt;a href="http://subversion.tigris.org/svn_1.5_releasenotes.html#sparse-checkouts"&gt;sparse checkouts&lt;/a&gt; for working with large repos (say, one that includes multimedia assets) &lt;/li&gt;    &lt;li&gt;&lt;a href="http://subversion.tigris.org/svn_1.5_releasenotes.html#externals"&gt;improvements to &lt;code&gt;svn:externals&lt;/code&gt;&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;The usual performance improvements &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;See the &lt;a href="http://subversion.tigris.org/svn_1.5_releasenotes.html"&gt;svn 1.5 release notes&lt;/a&gt; for a run down of the main changes, or the &lt;a href="http://svn.collab.net/repos/svn/tags/1.5.0/CHANGES"&gt;CHANGES file&lt;/a&gt; for a complete list.&lt;/p&gt;  &lt;p&gt;Oh yeah, and the usual, major version, &lt;a href="http://subversion.tigris.org/svn_1.5_releasenotes.html#wc-and-repos-format-change"&gt;working copy and repository format provisos apply&lt;/a&gt;... while the API is backwards compatible and svn 1.5 server and tools work with older repo versions, working copies are a different story. Older client tools will not work with svn 1.5 working copies, nor with 1.5 repositories. Your existing working copies will automatically upgrade to the 1.5 format when you access them with the new tools. &lt;a href="http://subversion.tigris.org/svn_1.5_releasenotes.html#wc-and-repos-format-change"&gt;Read this&lt;/a&gt; for more information.&lt;/p&gt;

&lt;p&gt;You'll also need to upgrade your repository format to 1.5 to take full advantage of the new features like merge tracking (although you'll get &lt;a href="http://subversion.tigris.org/svn_1.5_releasenotes.html#new-feature-compatibility-table"&gt;a number of the improvements with older repo formats&lt;/a&gt; as well).&lt;/p&gt;  &lt;p&gt;Certified binaries will be coming out over the next couple of days &lt;a href="http://www.collab.net/downloads/subversion/"&gt;at CollabNet&lt;/a&gt; (other binary maintainers listed &lt;a href="http://subversion.tigris.org/getting.html#binary-packages"&gt;here&lt;/a&gt;). The &lt;a href="http://tortoisesvn.net/node/328"&gt;TortoiseSVN crew is pretty much ready&lt;/a&gt; to go too.&lt;/p&gt;  &lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/davesquared?a=Si2Rpi"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=Si2Rpi" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=QWdTMI"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=QWdTMI" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=CTse6i"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=CTse6i" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=DanFpI"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=DanFpI" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=UrYVYI"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=UrYVYI" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/315785446" height="1" width="1"/&gt;</content><link rel="alternate" type="text/html" href="http://davesquared.blogspot.com/2008/06/subversion-150-released.html" title="Subversion 1.5.0 released" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=3851447511485299387" title="0 Comments" /><link rel="replies" type="application/atom+xml" href="http://davesquared.blogspot.com/feeds/3851447511485299387/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/3851447511485299387" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/3851447511485299387" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email></author><feedburner:awareness xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://api.feedburner.com/awareness/1.0/GetItemData?uri=davesquared&amp;itemurl=http%3A%2F%2Fdavesquared.blogspot.com%2F2008%2F06%2Fsubversion-150-released.html</feedburner:awareness></entry><entry><id>tag:blogger.com,1999:blog-7624394686148711990.post-3860480911900303194</id><published>2008-06-19T10:39:00.003+10:00</published><updated>2008-06-19T10:40:33.369+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="dev practices" /><title type="text">DI and cross-cutting concerns</title><content type="html">&lt;p&gt;Just came across some great guidance from &lt;a href="http://devlicio.us/blogs/casey/"&gt;Casey Charlton&lt;/a&gt; on the &lt;a href="http://tech.groups.yahoo.com/group/altdotnet/"&gt;ALT.NET mailing list&lt;/a&gt;. My &lt;a href="http://davesquared.blogspot.com/2008/06/attempting-to-understand-dependency.html"&gt;last post on dependency injection&lt;/a&gt; mentioned the benefit of documenting class dependencies via the constructor used for DI. But what about cross cutting concerns like logging? From &lt;a href="http://tech.groups.yahoo.com/group/altdotnet/message/10141"&gt;Casey's mailing list post&lt;/a&gt;:&lt;/p&gt;  &lt;blockquote&gt;&amp;quot;Constructor properties shouldnt be used for cross cutting concerns like logging ... Put ILogger as a public property on the class, use the nulllogger as the default value, register the logging facility in Windsor, and all will magically happen&amp;quot;  &lt;/blockquote&gt;  &lt;p&gt;I like this -- unique dependencies in your constructor, others set via property-injection. I'm also pretty keen on the idea of AOP for doing a lot of basic logging, but I haven't had a good look at this in .NET yet. The &lt;a href="http://tech.groups.yahoo.com/group/altdotnet/message/10109"&gt;ALT.NET thread&lt;/a&gt; has a bit more of a discussion on logging.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/davesquared?a=twhLsi"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=twhLsi" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=T5aeAI"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=T5aeAI" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=Bq6RNi"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=Bq6RNi" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=Ait8JI"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=Ait8JI" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=phdLCI"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=phdLCI" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/315031734" height="1" width="1"/&gt;</content><link rel="alternate" type="text/html" href="http://davesquared.blogspot.com/2008/06/di-and-cross-cutting-concerns.html" title="DI and cross-cutting concerns" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=3860480911900303194" title="0 Comments" /><link rel="replies" type="application/atom+xml" href="http://davesquared.blogspot.com/feeds/3860480911900303194/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/3860480911900303194" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/3860480911900303194" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email></author><feedburner:awareness xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://api.feedburner.com/awareness/1.0/GetItemData?uri=davesquared&amp;itemurl=http%3A%2F%2Fdavesquared.blogspot.com%2F2008%2F06%2Fdi-and-cross-cutting-concerns.html</feedburner:awareness></entry><entry><id>tag:blogger.com,1999:blog-7624394686148711990.post-9209247493433878357</id><published>2008-06-12T23:40:00.016+10:00</published><updated>2008-06-13T10:51:34.211+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="patterns" /><category scheme="http://www.blogger.com/atom/ns#" term=".net" /><category scheme="http://www.blogger.com/atom/ns#" term="dev practices" /><title type="text">Attempting to understand Dependency Injection</title><content type="html">&lt;p&gt;Watching &lt;a href="http://blog.wekeroad.com/"&gt;Rob Conery&lt;/a&gt; and &lt;a href="http://codebetter.com/blogs/jeremy.miller/default.aspx"&gt;Jeremy Miller&lt;/a&gt; work through &lt;a href="http://blog.wekeroad.com/mvc-storefront/mvcstore-part-13/"&gt;Dependency Injection for the MVC Storefront project&lt;/a&gt; really helped me to piece together a few ideas that had been rattling around in my generally deserted cranium. Dependency injection (DI) is sometimes dismissed as &amp;quot;just&amp;quot; a tool for unit testing and mocking dependencies. But I think DI, and DI containers, offer a bit more to software design than simply providing a way to use mocks for interaction testing. So as usual I'm polluting the blogosphere with my ramblings in an effort to solidify my understanding. Let's work through an example and see what we can find.&lt;/p&gt;

&lt;p&gt;Here is how we could write a class to send invoice reminder emails without any thought given to design or testability:&lt;/p&gt;

&lt;pre&gt;
public class InvoiceReminderService {
  public void SendReminders() {
    var emailService = &lt;b&gt;new EmailService()&lt;/b&gt;;
    var invoiceRepository = &lt;b&gt;new InvoiceRepository()&lt;/b&gt;;  
    var invoicesDueForReminderEmail = invoiceRepository.GetInvoicesDueForReminders();
    foreach (var invoice in invoicesDueForReminderEmail) {
      var reminderMessage = createReminder(invoice);
      emailService.Send(reminderMessage);
    }
  }
  //...
}
&lt;/pre&gt;

&lt;p&gt;Here we have dependencies on &lt;code&gt;InvoiceRepository&lt;/code&gt;, for getting invoices due for reminder emails, and &lt;code&gt;EmailService&lt;/code&gt;, for sending out the emails over SMTP. These dependencies could be instantiated at many different places all over our code base. Without worrying about design principles or testability, let's simply pull out these dependencies and rely on constructor injection to instantiate them.&lt;/p&gt;

&lt;pre&gt;
public class InvoiceReminderService {
  private EmailService emailService;
  private InvoiceRepository invoiceRepository;

  public InvoiceReminderService(&lt;b&gt;InvoiceRepository invoiceRepository, EmailService emailService&lt;/b&gt;) {
    this.invoiceRepository = invoiceRepository;
    this.emailService = emailService;
  }

  public void SendReminders() {
    var invoicesDueForReminderEmail = invoiceRepository.GetInvoicesDueForReminders();
    foreach (var invoice in invoicesDueForReminderEmail) {
      var reminderMessage = createReminder(invoice);
      emailService.Send(reminderMessage);
    }
  }
  //...
}
&lt;/pre&gt;

&lt;p&gt;Here we've just created a constructor that takes the required dependencies and adds them to private fields. &lt;code&gt;SendReminders()&lt;/code&gt; has been updated so that it is no longer responsible for instantiating the dependencies. I can then instantiate an &lt;code&gt;InvoiceReminderService&lt;/code&gt; by creating the dependencies and passing them to the constructor, or I can use a DI container (I'm using a pre-release build of StructureMap 2.5 for this post) to automatically create my dependencies for me:&lt;/p&gt;

&lt;pre&gt;var invoiceReminderService = ObjectFactory.GetInstance&amp;lt;InvoiceReminderService&amp;gt;();&lt;/pre&gt;

&lt;p&gt;By default our DI container looks at the &lt;a href="http://structuremap.sourceforge.net/FAQ.htm#FAQ10"&gt;greediest constructor&lt;/a&gt; (the one with the most parameters) to see what dependencies it needs to create. Because &lt;code&gt;InvoiceRepository&lt;/code&gt; and &lt;code&gt;EmailService&lt;/code&gt; are both concrete classes (i.e. not interfaces or abstract), we don't need to give StructureMap any additional information, it can simply instantiate the required objects and pass them through to the &lt;code&gt;InvoiceReminderService&lt;/code&gt; constructor.&lt;/p&gt;

&lt;p&gt;So what has this accomplished? Well, &lt;code&gt;SendReminders()&lt;/code&gt; is now a lot clearer without the dependencies in the way. And we also have an easy way to tell exactly what the dependencies of the class are (the constructor). We are also skirting dangerously close to having a testable class that could easily be modified to follow the &lt;a href="http://en.wikipedia.org/wiki/Dependency_inversion_principle"&gt;Dependency Inversion Principle (DIP)&lt;/a&gt; (by extracting interfaces from our dependencies and relying on those instead of on concrete classes) and the &lt;a href="http://en.wikipedia.org/wiki/Open/closed_principle"&gt;Open/Closed Principle (OCP)&lt;/a&gt; (by allowing us to change the behaviour of our class by providing different implementations for the dependencies).&lt;/p&gt;

&lt;p&gt;But the main, obvious thing this has accomplished is that our class is no longer responsible for instantiating its dependencies. I guess you could almost link this back to the &lt;a href="http://en.wikipedia.org/wiki/Single_responsibility_principle"&gt;Single Responsibility Principle (SRP)&lt;/a&gt; -- we are limiting this class' responsibilities and given it one less reason to change. Why is this good? Well, let's imagine our &lt;code&gt;EmailService&lt;/code&gt; class is used by a number of classes throughout our application. We want to change our &lt;code&gt;EmailService&lt;/code&gt; so that it no longer sends emails directly via SMTP. Now it simply queues up the email in a database, and another process is responsible for firing off emails from the queue. To create an &lt;code&gt;EmailService&lt;/code&gt; without a DI container I now need to do this to every class that builds an &lt;code&gt;EmailService&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;emailService = new EmailService(new EmailRepository());&lt;/pre&gt;

&lt;p&gt;Or we can just let my DI container handle it for me, and keep our original &lt;code&gt;ObjectFactory&lt;/code&gt; call unchanged. This reduces the friction experienced whenever we need to factor out a new class to provide new functionality or to avoid an SRP violation.&lt;/p&gt;

&lt;pre&gt;//No change need here, even though the EmailService constructor has changed...
var invoiceReminderService = ObjectFactory.GetInstance&amp;lt;InvoiceReminderService&amp;gt;();&lt;/pre&gt;

&lt;p&gt;(Yes, this is slightly circular logic as I am assuming we using DI for the new &lt;code&gt;EmailRepository&lt;/code&gt; class too, but the logic is equally valid if we want to change the constructor to include a connection string or some other parameter. The point is that we can vary the instantiation without affect dependent classes.)

&lt;p&gt;Now I'm not suggesting for a moment that you want to globally replace &lt;code&gt;new&lt;/code&gt; with a DI container, but for me the realisation that DI containers were all about abstracting the responsibility of dependency creation, rather than simply providing a testing seam, was a bit of an A-HA! moment. Of course, I am a bit slower than your average developer, so sometimes the things like this take me a while :-)&lt;/p&gt;

&lt;h2&gt;From abstracting dependency creation to SOLID designs&lt;/h2&gt;

&lt;p&gt;Now there are still a number of &lt;a href="http://www.lostechies.com/blogs/chad_myers/archive/2008/03/07/pablo-s-topic-of-the-month-march-solid-principles.aspx"&gt;SOLID design principles&lt;/a&gt; the code above is violating. This doesn't mean we need to instantly refactor to be compliant (you're never going to be, they are general guidelines that can be somewhat contradictory when taken to the n'th degree), but it is something we can look at.&lt;/p&gt;

&lt;p&gt;First up is the &lt;a href="http://en.wikipedia.org/wiki/Dependency_inversion_principle"&gt;DIP&lt;/a&gt;. We are depending on concrete types rather than abstractions. This also limits our options of altering the behaviour of the class via its dependencies to subclassing those dependencies, which is a minor strike against the &lt;a href="http://en.wikipedia.org/wiki/Open/closed_principle"&gt;OCP&lt;/a&gt;. This is easily fixed by extracting interfaces from the dependencies:&lt;/p&gt;

&lt;pre&gt;
public class InvoiceReminderService {
  private IEmailService emailService;
  private IInvoiceRepository invoiceRepository;

  public InvoiceReminderService(&lt;b&gt;IInvoiceRepository invoiceRepository, IEmailService emailService&lt;/b&gt;) {
    this.invoiceRepository = invoiceRepository;
    this.emailService = emailService;
  }
  //...
}
&lt;/pre&gt;

&lt;p&gt;StructureMap will auto-wireup these dependencies, but if we are using our &lt;code&gt;EmailService&lt;/code&gt; implementation that depends on an extracted &lt;code&gt;IEmailRepository&lt;/code&gt; interface, then we'll need to tell StructureMap's configuration about it, either at compile time in code or using a configuration file:&lt;/p&gt;
&lt;pre&gt;
public static class Bootstrapper {
  public static void ConfigureIoC() {            
    StructureMapConfiguration.AddRegistry(new DiSampleRegistry());
  }  
}
public class DiSampleRegistry : Registry {
  protected override void configure() {
    ForRequestedType&amp;lt;IEmailRepository&amp;gt;()
      .TheDefaultIsConcreteType&amp;lt;EmailRepository&amp;gt;();                
  }
}
&lt;/pre&gt;

&lt;p&gt;We are now looking at a more traditional DI design. Our &lt;code&gt;InvoiceReminderService&lt;/code&gt; is now completely independent of the specific implementations of its dependencies. All the code in the class is cohesive -- working at one responsibility with minimal background noise. This project doesn't even need a reference to the DLL containing the dependency implementations. This means we are fine changing implementations (although not interface contracts!) and we know our &lt;code&gt;InvoiceReminderService&lt;/code&gt; is safe. If you were given this class to reuse, or simply to maintain, you wouldn't have to go pulling in a whole bunch of concrete dependencies. As a result and as a nice bonus, we have some good seams for running automated tests. We can easily stub or mock these dependencies and isolate the behaviour under test.&lt;/p&gt;

&lt;p&gt;&lt;i&gt;Aside: DI containers are an obvious way to get plugin and provider-style implementations, by loading specific implementations of an interface at runtime. I'm focusing on more general design effects here -- if you're looking for a plugin/component/provider model you'll obviously be designing more explicitly for loose coupling and will choose your approach based on that.&lt;/i&gt;&lt;/p&gt;

&lt;h2&gt;Not all beer and Skittles?&lt;/h2&gt;

&lt;p&gt;That's the DI theory, as far as I can tell. But as always there is &lt;a href="http://en.wikipedia.org/wiki/No_Silver_Bullet"&gt;no silver bullet&lt;/a&gt;. It is now tougher for us to navigate from the &lt;code&gt;InvoiceReminderService&lt;/code&gt; to the current implementations of its dependencies (as we've abstracted them away). We are also looking at a potential interface explosion. Why extract an interface for virtually every class you write? That's two units of code for every responsibility. And we now have a DI container to learn and troubleshoot when debugging. If we're happy with tight coupling between this class and its dependencies, then why go to these lengths? If you want to run unit tests why not just use &lt;a href="http://www.typemock.com/"&gt;TypeMock&lt;/a&gt; to break into tightly coupled dependencies? Or at the very least provide default implementations in the class' default constructor (a.k.a. the poor man's dependency injection, see &lt;a href="http://blog.vuscode.com/malovicn/archive/2008/06/07/design-for-testability-transparent-and-opaque-dependencies-part-8.aspx"&gt;Nikola's post&lt;/a&gt; for an interesting variation on this approach):&lt;/p&gt;

&lt;pre&gt;
public class InvoiceReminderService {
  private IEmailService emailService;
  private IInvoiceRepository invoiceRepository;

  &lt;b&gt;public InvoiceReminderService() {
    this.invoiceRepository = new InvoiceRepository();
    this.emailService = new EmailService();
  }&lt;/b&gt;

  public InvoiceReminderService(&lt;b&gt;IInvoiceRepository invoiceRepository, IEmailService emailService&lt;/b&gt;) {
    this.invoiceRepository = invoiceRepository;
    this.emailService = emailService;
  }  
  //...
}
&lt;/pre&gt;

&lt;p&gt;And how much of all this is just working around limitations of statically typed languages? To me these are all quite reasonable questions (some of these raised by Kevin Berridge in some nice posts &lt;a href="http://kevin-berridge.blogspot.com/2007/12/dependency-injection.html"&gt;here&lt;/a&gt; and &lt;a href="http://kevin-berridge.blogspot.com/2008/03/ioc-and-di.html"&gt;here&lt;/a&gt;, as well as a couple of posts from Jacob Proffitt starting &lt;a href="http://scruffylookingcatherder.com/archive/2007/08/07/dependency-injection.aspx"&gt;here&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;As always the key seems to lie in achieving a balance. The benefits of a loosely coupled design always need to be traded off with any additional complexity of that design. After watching the &lt;a href="http://blog.wekeroad.com/mvc-storefront/mvcstore-part-13/"&gt;MVC Storefont DI screencast&lt;/a&gt; and having a play around with StructureMap I can see a lot of very obvious benefits to DI containers, but at the same time it's not something to dive into without having an vague idea of the theory and problems it aims to solve (which is why I've spent so much time reading about DI containers, but generally sticking to poor man's DI until I had a pressing reason to move to a container). After all, we don't go around blindly applying the GOF patterns to every situation under the sun... right? :-)&lt;/p&gt;

&lt;h2&gt;Some interesting DI reads&lt;/h2&gt;
&lt;p&gt;As opposed to this post, here are a few interesting takes on DI.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Frederik's &lt;a href="http://frederikm.blogspot.com/2008/06/case-for-dependency-injection.html"&gt;Case for Dependency Injection&lt;/a&gt;, which looks at DI as evolved from interface-based design.&lt;/li&gt;
&lt;li&gt;Nikola Malovic on &lt;a href="http://blog.vuscode.com/malovicn/archive/2008/06/07/design-for-testability-transparent-and-opaque-dependencies-part-8.aspx"&gt;transparent dependencies&lt;/a&gt; and &lt;a href="http://blog.vuscode.com/malovicn/archive/2008/02/13/design-for-testability-dependency-injection-frameworks-part-4.aspx"&gt;DI frameworks&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Kevin Berridge on the DI-slippery slope: &lt;a href="http://kevin-berridge.blogspot.com/2007/12/dependency-injection.html"&gt;here&lt;/a&gt; and &lt;a href="http://kevin-berridge.blogspot.com/2008/03/ioc-and-di.html"&gt;here&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Jacob Proffitt's &lt;a href="http://scruffylookingcatherder.com/archive/2007/08/07/dependency-injection.aspx"&gt;war on dependency injection&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Nate Kohari's &lt;a href="http://kohari.org/2007/08/15/defending-dependency-injection/"&gt;response to Jacob&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Ayende's views DI in response to Jacob and Nate: &lt;a href="http://www.ayende.com/Blog/archive/2007/08/18/Dependency-Injection-IAmDonQuixote.aspx"&gt;here&lt;/a&gt; and &lt;a href="http://www.ayende.com/Blog/archive/2007/08/18/Dependency-Injection-More-than-a-testing-seam.aspx"&gt;here&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Jeremy Miller on the &lt;a href="http://codebetter.com/blogs/jeremy.miller/archive/2005/10/06/132825.aspx"&gt;Dependency Injection Pattern&lt;/a&gt;, and the &lt;a href="http://codebetter.com/blogs/jeremy.miller/archive/2007/09/07/dependency-injection-still-has-some-good-years-left.aspx"&gt;pros and cons of DI&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/davesquared?a=B3yh1i"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=B3yh1i" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=88tq1I"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=88tq1I" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=EcMm2i"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=EcMm2i" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=aozPcI"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=aozPcI" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=N81tPI"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=N81tPI" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/310430950" height="1" width="1"/&gt;</content><link rel="alternate" type="text/html" href="http://davesquared.blogspot.com/2008/06/attempting-to-understand-dependency.html" title="Attempting to understand Dependency Injection" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=9209247493433878357" title="3 Comments" /><link rel="replies" type="application/atom+xml" href="http://davesquared.blogspot.com/feeds/9209247493433878357/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/9209247493433878357" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/9209247493433878357" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email></author><feedburner:awareness xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://api.feedburner.com/awareness/1.0/GetItemData?uri=davesquared&amp;itemurl=http%3A%2F%2Fdavesquared.blogspot.com%2F2008%2F06%2Fattempting-to-understand-dependency.html</feedburner:awareness></entry><entry><id>tag:blogger.com,1999:blog-7624394686148711990.post-2913888238523388512</id><published>2008-05-28T13:35:00.003+10:00</published><updated>2008-05-28T13:54:11.661+10:00</updated><title type="text">Nothin' but .NET heading down under</title><content type="html">&lt;p&gt;I left a &lt;a href="http://www.jpboodhoo.com/blog/CommentView,guid,4862047e-58c7-4041-93b5-242631c675cc.aspx#commentstart"&gt;comment on JP Boodhoo's blog&lt;/a&gt; recently, and asked if there was any chance of him running a &lt;a href="http://www.jpboodhoo.com/training/courseschedule.aspx"&gt;Nothin' But .NET&lt;/a&gt; course in Sydney, Australia. I got an email response from him a short time later:&lt;/p&gt;

&lt;blockquote&gt;"As far as the course in Australia!! I will be there next year [2009] to give a course in Sydney!!"&lt;/blockquote&gt;

&lt;p&gt;I've been really keen to attend this course for ages now, but the commute to Canada each day was pushing it a bit :). In case you don't know what the course is all about, here's a &lt;a href="http://kyle.baley.org/NothinButNETOrHowToJustifyIgnoringYourHomeLife.aspx"&gt;review (and links to other reviews) from Kyle Bailey's old blog&lt;/a&gt;. To quote a bit of the blurb from a &lt;a href="http://www.acteva.com/booking.cfm?bevaid=150218"&gt;recently scheduled course&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
Nothin’ But .Net is a five day boot camp that will focus on pragmatically applying .Net within the context of developing a working N-Tiered application. Registrants will learn about advanced features of .Net (2.0/3.0/3.5) as they are applied to the task of building a complete application from the UI layer all the way down to the mapping layer.
&lt;br/&gt;&lt;br/&gt;
&lt;b&gt;Core Concepts Overview&lt;/b&gt;
&lt;br/&gt;
&lt;ul&gt;
&lt;li&gt;Expanding the capabilities of developing with VS.Net - Enter ReSharper (a productivity add-in for Visual Studio .Net)&lt;/li&gt;
&lt;li&gt;There’s more to life than generated code&lt;/li&gt;
&lt;li&gt;Automation for the developer&lt;/li&gt;
&lt;li&gt;Generics ( they’re not just for collections )&lt;/li&gt;
&lt;li&gt;Back to basics - Rules Of Good Object Oriented Design&lt;/li&gt;
&lt;li&gt;Dependency Injection&lt;/li&gt;
&lt;li&gt;Object Relational Mapping in .Net&lt;/li&gt;
&lt;li&gt;Applying the dependency inversion principle&lt;/li&gt;
&lt;li&gt;Domain Driven Design&lt;/li&gt;
&lt;li&gt;Passive View/Supervising Controller,MVC&lt;/li&gt;
&lt;li&gt;Creating layered architectures&lt;/li&gt;
&lt;li&gt;Driving out functionality and design through testing&lt;/li&gt;
&lt;li&gt;Taking Control Of Databinding&lt;/li&gt;
&lt;li&gt;Behavior (Test) Driven Development&lt;/li&gt;
&lt;li&gt;Core design patterns applied&lt;/li&gt;
&lt;li&gt;Pragmatic Productivity Tools For Developers&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;

&lt;p&gt;It sounds awesome. Hope to see a few like-minded Aussie developers there! In the mean time, if anyone knows of any current course in Sydney that covers any of this stuff please leave a comment or email me, as I'd try and attend that too during the looonnnggg wait 'til JP visits in 2009.&lt;/p&gt;

&lt;p&gt;This free advertisement was brought to you courtesy of an excited coder. :-)&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/davesquared?a=ccUl8i"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=ccUl8i" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=EyNuaH"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=EyNuaH" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=uCD6Ah"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=uCD6Ah" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=R9NYaH"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=R9NYaH" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=PnnNXH"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=PnnNXH" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/299554437" height="1" width="1"/&gt;</content><link rel="alternate" type="text/html" href="http://davesquared.blogspot.com/2008/05/nothin-but-net-heading-down-under.html" title="Nothin' but .NET heading down under" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=2913888238523388512" title="0 Comments" /><link rel="replies" type="application/atom+xml" href="http://davesquared.blogspot.com/feeds/2913888238523388512/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/2913888238523388512" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/2913888238523388512" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email></author><feedburner:awareness xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://api.feedburner.com/awareness/1.0/GetItemData?uri=davesquared&amp;itemurl=http%3A%2F%2Fdavesquared.blogspot.com%2F2008%2F05%2Fnothin-but-net-heading-down-under.html</feedburner:awareness></entry><entry><id>tag:blogger.com,1999:blog-7624394686148711990.post-8797728095296190032</id><published>2008-05-28T09:14:00.014+10:00</published><updated>2008-05-29T11:35:28.636+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="tools" /><category scheme="http://www.blogger.com/atom/ns#" term="downloads" /><title type="text">BDD test naming with AutoHotKey</title><content type="html">&lt;p&gt;&lt;i&gt;&lt;b&gt;Update 2008-05-29:&lt;/b&gt; &lt;a href="http://www.jpboodhoo.com/blog"&gt;JP&lt;/a&gt; has posted a &lt;a href="http://www.jpboodhoo.com/blog/BDDAutoHotKeyScriptUpdateTake2.aspx"&gt;much better version of this script&lt;/a&gt; (with suggestions from a few of his readers). I've updated the script on this post to work more like JP's version, but you're probably best off grabbing it from &lt;a href="http://www.jpboodhoo.com/blog/BDDAutoHotKeyScriptUpdateTake2.aspx"&gt;his post&lt;/a&gt;, or searching &lt;a href="http://www.jpboodhoo.com/blog"&gt;his site&lt;/a&gt; for his latest version.&lt;/i&gt;&lt;/p&gt;

&lt;p&gt;Was having a chat earlier with my good mate &lt;a href="http://www.jpboodhoo.com/blog"&gt;JP Boodhoo&lt;/a&gt;... er, well, more accurately, I left a comment on his blog and he was nice enough to email me back. Anyway, JP has &lt;a href="http://www.jpboodhoo.com/blog/SoLongBDDMacroHelloAutohotkey.aspx"&gt;started trying AutoHotKey rather than his previous macro&lt;/a&gt; for BDD-style test naming.&lt;/p&gt;

&lt;p&gt;I thought I'd post an extremely over-engineering version of this &lt;a href="http://www.autohotkey.com/"&gt;AutoHotKey&lt;/a&gt; script, which has a toggle-approach similar to the &lt;a href="http://davesquared.blogspot.com/2008/02/emacs-key-bindings-everywhere.html"&gt;Emacs Everywhere script&lt;/a&gt; I posted earlier.&lt;/p&gt;

&lt;p&gt;Once you have &lt;a href="http://www.autohotkey.com/"&gt;AHK&lt;/a&gt; installed, you can just extract the ZIP below and double click the .AHK file to load the script. The script will let you toggle &amp;quot;test-naming mode&amp;quot; (i.e. replacing spaces with underscores) using Ctrl + Shift + U. You can cancel out of test naming mode by pressing ENTER, ESCAPE or starting the method signature by typing a '('. Pressing Ctrl + Alt + U will insert a new test template before switching on test naming mode (although you might be better off using R# templates for this). All this is simply to make it easier to type out tests like this:&lt;/p&gt;

&lt;pre&gt;[Test]
public void Test_naming_mode_turns_spaces_to_underscores() {}
&lt;/pre&gt;


&lt;p&gt;Version 2 of the script can be downloaded here: 
&lt;ul&gt;&lt;li&gt;&lt;a href="http://davesquared.googlecode.com/files/TestNamingMode-v2.zip"&gt;TestNamingMode-v2.zip&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/p&gt;

&lt;p&gt;Feel free to change the hotkeys and the dodgy icons :). I haven't had a good test of it yet so use at your own risk.&lt;/p&gt;

&lt;p&gt;If you're happy with how it works you can add it to your Startup programs and have BDD-style test naming goodness whenever you like. Hope_this_helps! :-)&lt;/p&gt;

&lt;p style="font-size: x-small"&gt;&lt;b&gt;Change log&lt;/b&gt;
&lt;ul style="font-size: x-small"&gt;
&lt;li&gt;2008-05-29: Uploaded v2, synching with &lt;a href="http://www.jpboodhoo.com/blog/BDDAutoHotKeyScriptUpdateTake2.aspx"&gt;JP's version 2&lt;/a&gt;, adding test templates, and made test mode exit after typing '(' for test method signature&lt;/li&gt;
&lt;li&gt;2008-05-28: Updated hotkeys to match JP's version&lt;/li&gt;
&lt;li&gt;2008-05-28: Original post&lt;/li&gt;
&lt;/ul&gt;
&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/davesquared?a=J14BRi"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=J14BRi" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=tK7nXH"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=tK7nXH" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=hDeK5h"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=hDeK5h" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=AzjTWH"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=AzjTWH" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=grVFpH"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=grVFpH" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/299412798" height="1" width="1"/&gt;</content><link rel="alternate" type="text/html" href="http://davesquared.blogspot.com/2008/05/bdd-test-naming-with-autohotkey.html" title="BDD test naming with AutoHotKey" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=8797728095296190032" title="0 Comments" /><link rel="replies" type="application/atom+xml" href="http://davesquared.blogspot.com/feeds/8797728095296190032/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/8797728095296190032" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/8797728095296190032" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email></author><feedburner:awareness xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://api.feedburner.com/awareness/1.0/GetItemData?uri=davesquared&amp;itemurl=http%3A%2F%2Fdavesquared.blogspot.com%2F2008%2F05%2Fbdd-test-naming-with-autohotkey.html</feedburner:awareness></entry><entry><id>tag:blogger.com,1999:blog-7624394686148711990.post-702483270713934571</id><published>2008-05-27T12:39:00.002+10:00</published><updated>2008-05-27T12:44:50.564+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="imho" /><category scheme="http://www.blogger.com/atom/ns#" term="tdd" /><category scheme="http://www.blogger.com/atom/ns#" term="roundup" /><category scheme="http://www.blogger.com/atom/ns#" term="dev practices" /><title type="text">Top-down vs. bottom-up design</title><content type="html">&lt;p&gt;I've been having a think about top-down (a.k.a. outside-in) design during my recent &lt;a href="http://davesquared.blogspot.com/2008/05/garden-race-pt-2-adding-multiple.html"&gt;iterative development exercise&lt;/a&gt;. In the series I've been putting off testing from the client layer down, primarily because GUIs have a reputation for being hard to test and harder to test-drive, and I wanted to make some early, easy progress on the core logic of the game.&lt;/p&gt;

&lt;p&gt;I started to think that this approach might be a mistake. I'm dealing with the model that I &lt;i&gt;think&lt;/i&gt; we'll need, not one demanded from the primary client of the model -- the GUI. &lt;a href="http://www.lostechies.com/blogs/chad_myers/archive/2008/05/14/ping-pong-pairing-session-screencast-with-ben-scheirman.aspx"&gt;Chad&lt;/a&gt; and &lt;a href="http://flux88.com/ScreencastTestDrivingAnInventoryScreen.aspx"&gt;Ben&lt;/a&gt; mentioned in their &lt;a href="http://www.benscheirman.com/screencasts/tdd-inventory"&gt;recent screencast&lt;/a&gt; that bottom-up implementation tended to lead to mistaken assumptions about infrastructure required by the top layers. I saw a &lt;a href="http://groups.google.com/group/behaviordrivendevelopment/browse_thread/thread/329ee6604f56231b/edb191c2152a1572?hl=en#edb191c2152a1572"&gt;similar point made on the BDD mailing list by Pat Maddox&lt;/a&gt;. Pat wrote (emphasis mine):&lt;/p&gt;

&lt;blockquote&gt;"I find an outside-in style of development to be very helpful...  
It forces you to think of your objects at a high
level, so &lt;b&gt;your design is driven by real need&lt;/b&gt;, and then you apply your
design skills as you go on.  &lt;b&gt;When I use a pure bottom-up style, I
write more speculative code and go down the wrong path far more often
than I'd like&lt;/b&gt;.  That's not to say that it's a problem inherent with
that style, but rather a problem that I've personally experienced, and
have more or less solved by using an outside-in approach."&lt;/blockquote&gt;

&lt;p&gt;This is opinion is echoed in an &lt;a href="http://tech.groups.yahoo.com/group/testdrivendevelopment/message/28244"&gt;unrelated post to the TDD mailing list by Olof Bjarnason&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;&amp;quot;I've been using TDD [bottom-up] for 2 years now, and it's been mostly a _great_
experience. The thing that bothers me most with &amp;quot;classic TDD&amp;quot; is that
sometimes I build too much functionality in my classes, which isn't
used in the end application after all. Even whole objects are wasted
in the worst case.&amp;quot;&lt;/blockquote&gt;

&lt;p&gt;The view here is that bottom-up design can lead to speculation and waste. By having a design driven directly by the overall, required behaviour, you only implement (and test) things that directly serve that behaviour. This can help eliminate speculative implementations of lower-level behaviour based on what you think the overall required behaviour will be.&lt;/p&gt;

&lt;h2&gt;Not so fast...&lt;/h2&gt;
&lt;p&gt;Sounds great! So what about inside-out / bottom-up / middle-out design? &lt;a href="http://www.xprogramming.com/"&gt;Ron Jeffries&lt;/a&gt; recently stated on the TDD mailing list that he &lt;a href="http://tech.groups.yahoo.com/group/testdrivendevelopment/message/28250"&gt;generally prefers to start with the model&lt;/a&gt; (unless the project is simply to build a viewer). Maybe there's a bit more to it?&lt;/p&gt;

&lt;p&gt;Digging further into &lt;a href="http://tech.groups.yahoo.com/group/testdrivendevelopment/message/28243"&gt;that thread on the TDD list&lt;/a&gt;, there are a number of great points of view on the topic. Some TDD-ists argue that bottom-up design lets you build in small, easy steps, and refactor your way to the required behaviour that you would otherwise start with in top-down design. Others state that this leads to waste -- writing code and tests that just get refactored away. Which resulted in a couple of great quotes on the difference between refactored code and waste:&lt;/p&gt;

&lt;blockquote&gt;&amp;quot;I suppose we could also call the scaffold we use when
constructing a large building as waste, or the safety
harnesses as waste.&amp;quot; -- &lt;a href="http://tech.groups.yahoo.com/group/testdrivendevelopment/message/28260"&gt;John Roth to TDD list&lt;/a&gt;&lt;/blockquote&gt;

&lt;blockquote&gt;&amp;quot;The analogy with scaffolding for a house is an excellent one -
there is a lot of &amp;quot;stuff&amp;quot; constructed when building a house, *just* to
support the construction - it is then discarded.&amp;quot; -- &lt;a href="http://tech.groups.yahoo.com/group/testdrivendevelopment/message/28274"&gt;Casey Charlton to TDD list&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Top-down design can also lead to a &lt;a href="http://codebetter.com/blogs/ian_cooper/archive/2008/02/04/classicist-vs-mockist-test-driven-development.aspx"&gt;&amp;quot;mockist&amp;quot; approach to TDD&lt;/a&gt;, where you need to mock all the required dependencies to implement the high level behaviour. This isn't necessarily a bad thing, but over-reliance on mocking can &lt;a href="http://codebetter.com/blogs/ian_cooper/archive/2007/12/19/mocks-and-the-dangers-of-overspecified-software.aspx"&gt;result in fragile tests&lt;/a&gt;. Martin Fowler has a great article on the pros and cons of &lt;a href="http://martinfowler.com/articles/mocksArentStubs.html"&gt;&amp;quot;classic&amp;quot; and &amp;quot;mockist&amp;quot; TDD&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;Enough rambling already!&lt;/h2&gt;

&lt;p&gt;While planning for part 3 of my &lt;a href="http://davesquared.blogspot.com/2008/05/garden-race-series.html"&gt;recent development exercise&lt;/a&gt; I was coming to the conclusion that top-down was the way to go. After looking into it some more I was reminded of a whole host of advantages of bottom-up design. Even more importantly it reminded me that &lt;a href="http://en.wikipedia.org/wiki/No_Silver_Bullet"&gt;there is no silver bullet&lt;/a&gt;, and there are times when either, or a mix of both, approaches are fine. All this started to sound familiar, so firing up Google I noticed that I had read something to this effect in &lt;a href="http://codebetter.com/blogs/jeremy.miller/archive/2008/03/03/unit-testing-playing-tennis-and-the-lack-of-absolutes-in-tdd.aspx"&gt;Jeremy Miller's excellent (as usual) post on the topic&lt;/a&gt; (search for "Bottom Up versus Top Down", although the whole post is worth reading).&lt;/p&gt;

&lt;p&gt;I think the most important conclusion I've reached during this ramble is that if you are working in iterations to deliver a complete slice of the application (top &lt;i&gt;and&lt;/i&gt; bottom) then you're never going to go too far wrong. Any "waste" from a bottom-up approach will be minimal as you'll be working toward and implementing the top almost immediately. And you'll still end up with higher-level behaviour specified with unit tests. Likewise starting top-down you'll still get the advantages of designing in small steps, particularly as you drive down into the design.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/davesquared?a=Fjvsai"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=Fjvsai" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=3PAj6H"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=3PAj6H" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=jsDJbh"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=jsDJbh" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=dNRMGH"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=dNRMGH" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=nsgbmH"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=nsgbmH" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/298794407" height="1" width="1"/&gt;</content><link rel="alternate" type="text/html" href="http://davesquared.blogspot.com/2008/05/top-down-vs-bottom-up-design.html" title="Top-down vs. bottom-up design" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=702483270713934571" title="0 Comments" /><link rel="replies" type="application/atom+xml" href="http://davesquared.blogspot.com/feeds/702483270713934571/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/702483270713934571" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/702483270713934571" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email></author><feedburner:awareness xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://api.feedburner.com/awareness/1.0/GetItemData?uri=davesquared&amp;itemurl=http%3A%2F%2Fdavesquared.blogspot.com%2F2008%2F05%2Ftop-down-vs-bottom-up-design.html</feedburner:awareness></entry><entry><id>tag:blogger.com,1999:blog-7624394686148711990.post-8968751953913221813</id><published>2008-05-21T16:21:00.006+10:00</published><updated>2008-05-21T16:39:09.138+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".net" /><title type="text">Disable theming for an empty ASPX</title><content type="html">&lt;p&gt;I recently added an ASPX page whose sole purpose in life is to redirect in various ways (yes, I could use a handler, no I didn't in this case). It had no content other than the usual &lt;code&gt;&amp;lt;%@ Page ...%&amp;gt;&lt;/code&gt; declaration. No head, body, or html tag. I got the following error message:&lt;/p&gt;

&lt;pre&gt;Using themed css files requires a header control on the page. (e.g. &amp;lt;head runat=&amp;quot;server&amp;quot; /&amp;gt;).&lt;/pre&gt;

&lt;p&gt;So naturally I added &lt;code&gt;&amp;lt;%@ Page &lt;b&gt;EnableTheming=&amp;quot;false&amp;quot;&lt;/b&gt; ...%&amp;gt;&lt;/code&gt;, and ... got the same error. Bit of Googling later and found &lt;a href="http://blogs.visoftinc.com/archive/2007/09/12/theme-error-when-themes-are-disabled.aspx"&gt;this post&lt;/a&gt; from Damien White (which in turn references &lt;a href="http://www.west-wind.com/WebLog/posts/4662.aspx"&gt;a Rick Strahl post&lt;/a&gt;). End result is that &lt;code&gt;EnableTheming&lt;/code&gt; seems a bit useless (at least for this case):&lt;/p&gt;

&lt;pre&gt;&amp;lt;%@ Page Language=&amp;quot;C#&amp;quot; &lt;b&gt;Theme=&amp;quot;&amp;quot;&lt;/b&gt; ... %&amp;gt;&lt;/pre&gt;

&lt;p&gt;Setting &lt;code&gt;Theme&lt;/code&gt; to nothing works, &lt;code&gt;EnableTheming=&amp;quot;false&amp;quot;&lt;/code&gt; doesn't. Bit odd. I know this is old news, but given the trouble I had searching for a solution I thought an extra search result floating around wouldn't hurt anyone.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/davesquared?a=gzZDMi"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=gzZDMi" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=27YySH"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=27YySH" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=hNZjeh"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=hNZjeh" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=xCtWFH"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=xCtWFH" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=dJfl8H"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=dJfl8H" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/294837258" height="1" width="1"/&gt;</content><link rel="alternate" type="text/html" href="http://davesquared.blogspot.com/2008/05/disable-theming-for-empty-aspx.html" title="Disable theming for an empty ASPX" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=8968751953913221813" title="0 Comments" /><link rel="replies" type="application/atom+xml" href="http://davesquared.blogspot.com/feeds/8968751953913221813/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/8968751953913221813" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/8968751953913221813" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email></author><feedburner:awareness xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://api.feedburner.com/awareness/1.0/GetItemData?uri=davesquared&amp;itemurl=http%3A%2F%2Fdavesquared.blogspot.com%2F2008%2F05%2Fdisable-theming-for-empty-aspx.html</feedburner:awareness></entry><entry><id>tag:blogger.com,1999:blog-7624394686148711990.post-1529482479377434457</id><published>2008-05-20T07:32:00.007+10:00</published><updated>2008-05-22T09:56:35.615+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="tools" /><category scheme="http://www.blogger.com/atom/ns#" term=".net" /><title type="text">ReSharper 4.0 beta</title><content type="html">&lt;p&gt;&lt;i&gt;&lt;b&gt;Update 2008-05-22&lt;/b&gt;: The &lt;a href="http://resharper.blogspot.com/2008/05/resharper-4-beta.html"&gt;real beta release&lt;/a&gt; has just been announced. It is the same build (804) as the beta candidate, which pretty much answers my question below on the difference between the two :).&lt;/i&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="http://www.intellij.net/forums/thread.jspa?messageID=5214869&amp;tstart=0#5214869"&gt;R# 4.0 beta candidate has been released&lt;/a&gt;. I'm not quite sure of the difference between a beta and a beta &lt;i&gt;candidate&lt;/i&gt;, but I'm assuming its better than a standard nightly build :)&lt;/p&gt;

&lt;p&gt;You can get it &lt;a href="http://www.jetbrains.net/confluence/display/ReSharper/ReSharper+4.0+Nightly+Builds"&gt;here&lt;/a&gt;, build 804. I've had a pretty good experience with most of the &amp;quot;works here&amp;quot; builds, so am looking forward to firing this up today :)&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/davesquared?a=FUq9qi"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=FUq9qi" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=L66lHH"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=L66lHH" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=4T1Ygh"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=4T1Ygh" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=E5CvLH"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=E5CvLH" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=ws8BXH"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=ws8BXH" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/293788422" height="1" width="1"/&gt;</content><link rel="alternate" type="text/html" href="http://davesquared.blogspot.com/2008/05/resharper-40-beta-candidate.html" title="ReSharper 4.0 beta" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=1529482479377434457" title="0 Comments" /><link rel="replies" type="application/atom+xml" href="http://davesquared.blogspot.com/feeds/1529482479377434457/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/1529482479377434457" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/1529482479377434457" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email></author><feedburner:awareness xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://api.feedburner.com/awareness/1.0/GetItemData?uri=davesquared&amp;itemurl=http%3A%2F%2Fdavesquared.blogspot.com%2F2008%2F05%2Fresharper-40-beta-candidate.html</feedburner:awareness></entry><entry><id>tag:blogger.com,1999:blog-7624394686148711990.post-8123386564663563686</id><published>2008-05-20T06:58:00.005+10:00</published><updated>2008-05-20T07:17:08.054+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".net" /><category scheme="http://www.blogger.com/atom/ns#" term="linq" /><title type="text">LINQ To SQL crippled prior to RTM</title><content type="html">&lt;p&gt;I was reading Frans' post on the &lt;a href="http://weblogs.asp.net/fbouma/archive/2008/05/19/why-use-the-entity-framework-yeah-why-exactly.aspx"&gt;marketing hype around Entity Framework&lt;/a&gt; this morning. He left an &lt;a href="http://weblogs.asp.net/fbouma/archive/2008/05/19/why-use-the-entity-framework-yeah-why-exactly.aspx#6201298"&gt;interesting comment&lt;/a&gt; there, quoting Matt Warren's post on writing an &lt;a href="http://blogs.msdn.com/mattwar/archive/2008/05/04/mocks-nix-an-extensible-linq-to-sql-datacontext.aspx"&gt;extensible LINQ to SQL DataContext&lt;/a&gt;. Here's a snippet from Matt's original post (emphasis mine):&lt;/p&gt;

&lt;blockquote&gt;"If only LINQ to SQL had a public provider model, I could simply plug a new one in and use it to intercept all interaction with the database. Oh, double irony, as there is no such provider model, at least not a public one.  Grin.
&lt;br/&gt;&lt;br/&gt;
LINQ to SQL was actually designed to be host to more types of back-ends than just SQL server. &lt;b&gt;It had a provider model targeted for RTM, but was disabled before the release.  Don’t ask me why.  Be satisfied to know that is was not a technical reason.&lt;/b&gt; Internally, it still behaves that way."
&lt;/blockquote&gt;

&lt;p&gt;Cue conspiracy theories! :)&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/davesquared?a=FxOIki"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=FxOIki" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=DXEoFH"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=DXEoFH" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=51ysAh"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=51ysAh" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=j307dH"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=j307dH" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/davesquared?a=CI0y2H"&gt;&lt;img src="http://feeds.feedburner.com/~f/davesquared?i=CI0y2H" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/davesquared/~4/293772131" height="1" width="1"/&gt;</content><link rel="alternate" type="text/html" href="http://davesquared.blogspot.com/2008/05/linq-to-sql-crippled-prior-to-rtm.html" title="LINQ To SQL crippled prior to RTM" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=7624394686148711990&amp;postID=8123386564663563686" title="0 Comments" /><link rel="replies" type="application/atom+xml" href="http://davesquared.blogspot.com/feeds/8123386564663563686/comments/default" title="Post Comments" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/8123386564663563686" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7624394686148711990/posts/default/8123386564663563686" /><author><name>David</name><uri>http://www.blogger.com/profile/05155410712205848106</uri><email>noreply@blogger.com</email></author><feedburner:awareness xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://api.feedburner.com/awareness/1.0/GetItemData?uri=davesquared&amp;itemurl=http%3A%2F%2Fdavesquared.blogspot.com%2F2008%2F05%2Flinq-to-sql-crippled-prior-to-rtm.html</feedburner:awareness></entry><entry><id>tag:blogger.com,1999:blog-7624394686148711990.post-2202457914204588821</id><published>2008-05-18T23:43:00.008+10:00</published><updated>2008-05-21T22:00:38.954+10:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="agile" /><category scheme="http://www.blogger.com/atom/ns#" term="*Garden Race" /><category scheme="http://www.blogger.com/atom/ns#" term=".net" /><category scheme="http://www.blogger.com/atom/ns#" term="tdd" /><title type="text">Garden Race Pt 2: Adding multiple players</title><content type="html">&lt;p&gt;&lt;i&gt;This post is &lt;a href="http://davesquared.blogspot.com/2008/05/garden-race-series.html"&gt;part of a series&lt;/a&gt; on the (very) basics of iterative development using the example of a simple &lt;a href="http://en.wikipedia.org/wiki/Snakes_and_ladders"&gt;Snakes and Ladders&lt;/a&gt;-like game. Links to each post in the series will be added to the &lt;a href="http://davesquared.blogspot.com/2008/05/garden-race-series.html"&gt;index page&lt;/a&gt;.&lt;/i&gt;&lt;/p&gt;

&lt;p&gt;Um, ok, so the customers (firstborn and I) weren't overly impressed with the demo from &lt;a href="http://davesquared.blogspot.com/2008/05/garden-race-pt-1-snakes-ladders-and.html"&gt;part 1&lt;/a&gt;. It did help illustrate the most pressing deficiencies though:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Doesn't support multiple players&lt;/li&gt;
&lt;li&gt;Doesn't have anything even remotely resembling snakes or ladders, let alone fairies&lt;/li&gt;
&lt;li&gt;No gui&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Our story list currently looks like this:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strike&gt;A player can roll the die, and then move that many spaces along the board.&lt;/strike&gt;&lt;/li&gt;
&lt;li&gt;A player that ends his or her turn on a "feature square" (a square containing a creature or obstacle), will be moved to the square connected with that feature.&lt;/li&gt;
&lt;li&gt;There can be 1-4 players, and each player has their turn in sequence.&lt;/li&gt;
&lt;li&gt;&lt;strike&gt;A player that reaches the final square wins the game.&lt;/strike&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;There are no GUI stories currently defined, but we'll need &lt;i&gt;something&lt;/i&gt; resembling a GUI eventually. I am tempted to start working on some GUI stories, because I don't want to get too far through the code and then find that it won't play nice with a graphical interface. It is really the main point of this software after all. On the other hand, the &lt;code&gt;Game&lt;/code&gt; class is still very basic, so maybe it would be a good idea to knock over one of the original stories on our list. Story 2 seems like it could tie in with the GUI pretty strongly -- the view will have to show the player's move, then perform some kind of animation in the &lt;i&gt;event&lt;/i&gt; that the player lands on a feature square. How about Story 3? Pretty basic, and essential to the game. At least that way firstborn and I can race each other to the end of the command line demo :)&lt;/p&gt;

&lt;p&gt;I'll just check with the customers... be right back.&lt;/p&gt;

&lt;p&gt;Ok, customer is asleep, so I'll take that as &amp;quot;that's fine Dad&amp;quot; :)&lt;/p&gt;

&lt;p&gt;Quick aside, normally we would estimate &amp;quot;points&amp;quot; or some other unit of how much effort each story would take, and how many units could be done in an iteration, then have the customer prioritise the stories for this iteration.&lt;/p&gt;

&lt;h2&gt;Our test list&lt;/h2&gt;

&lt;p&gt;What tests could we write for multiple players?&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Should be able to set the number of players for a new game&lt;/li&gt;
&lt;li&gt;For a new, 2 player game, both player's should be off-the-board (square 0)&lt;/li&gt;
&lt;li&gt;After first player's roll, current player should be player 2&lt;/li&gt;
&lt;li&gt;After first player's roll, current player's position should be off-the-board (square 0)&lt;/li&gt;
&lt;li&gt;First player rolls a 3, second player rolls a 2, then current player should be player 1 on square 3.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Frankly, I don't really like how these look. Implementation details keep coming to mind, and I want to ignore them and focus on &lt;i&gt;what&lt;/i&gt; I want to achieve (not &lt;i&gt;how&lt;/i&gt; I want to achieve it). Let's start with these anyway and we'll see how it goes.&lt;/p&gt;

&lt;h2&gt;Starting iteration 2&lt;/h2&gt;
&lt;p&gt;Running all our tests shows we are all green, and all good to go. The first test on the list looks easy -- set the number of players in the game. Let's do that one.&lt;/p&gt;

&lt;pre&gt;//From GameSpec.cs
[Fact]
public void Should_be_able_to_create_2_player_game() {
 var twoPlayerGame = new Game(10, 2);
 Assert.Equal(2, twoPlayerGame.NumberOfPlayers);
}
//From Game.cs
public int NumberOfPlayers { get { return numberOfPlayers; } }
public Game(int boardSize) {
 this.boardSize = boardSize;
}
public Game(int boardSize, int numberOfPlayers) {
 this.boardSize = boardSize;
 this.numberOfPlayers = numberOfPlayers;
}&lt;/pre&gt;
  
&lt;p&gt;What about the previous constructor that just takes the &lt;code&gt;boardSize&lt;/code&gt;? Well that should probably just start a new one player game I guess. Let's write a test for how we think it should work.&lt;/p&gt;

&lt;pre&gt;[Fact]
public void New_game_should_have_1_player_by_default() {
 var onePlayerGame = new Game(10);
 Assert.Equal(1, onePlayerGame.NumberOfPlayers);
}&lt;/pre&gt;

&lt;p&gt;This fails because the number of players initialises to zero.&lt;/p&gt;

&lt;pre&gt;
public Game(int boardSize) {
 this.boardSize = boardSize;
 this.numberOfPlayers = 1;
}&lt;/pre&gt;

&lt;p&gt;Fixed. Now let's look at test 2, checking the position of each player for a new game.&lt;/p&gt;

&lt;pre&gt;//From GameSpec.cs:
[Fact]
public void New_game_should_start_all_players_off_the_board() {
 var newThreePlayerGame = new Game(10, 3);
 var players = new[] {1, 2, 3};
 foreach (var player in players) {
  Assert.Equal(0, newThreePlayerGame.GetSquareFor(player));   
 }            
}

//From Game.cs:
public int GetSquareFor(int player) {
 return 0;
}&lt;/pre&gt;

&lt;p&gt;An obviously deficient implementation like this &lt;code&gt;GetSquareFor()&lt;/code&gt; method suggests we need to writes some more tests to flesh out a better one.&lt;/p&gt;  
  
&lt;pre&gt;[Fact]
public void Positions_should_be_correct_after_first_two_players_roll() {
 var threePlayerGame = new Game(10, 3);
 const int firstRoll = 3;
 const int secondRoll = 5;
 
 threePlayerGame.Roll(firstRoll);
 threePlayerGame.Roll(secondRoll);
 
 Assert.Equal(firstRoll, threePlayerGame.GetSquareFor(1));
 Assert.Equal(secondRoll, threePlayerGame.GetSquareFor(2));
 Assert.Equal(0, threePlayerGame.GetSquareFor(3));
}&lt;/pre&gt; 

&lt;p&gt;Now we are potentially looking at a bigger step. We need &lt;code&gt;Roll()&lt;/code&gt; to affect only the position of the current player. We don't have the concept of a current player. We'll also probably need an array or similar structure to store each player's position. &lt;code&gt;Roll()&lt;/code&gt; will then store update the position of the current player, and change the current player to the next player. The &lt;code&gt;CurrentSquare&lt;/code&gt; implementation will probably need to change to refer to the current player too. And then we'll have to add code to change the position in the event the player lands on a feature square! Argh!&lt;/p&gt;

&lt;h2&gt;Stop worrying! Try baby steps...&lt;/h2&gt;

&lt;p&gt;Let's back up a bit. I'm fairly confident we can write up the code above, but it will only be covered by one test and we are touching a lot of the &lt;code&gt;Game&lt;/code&gt; class without direct guidance from the tests. We still have this test on our test list: "&lt;i&gt;After first player's roll, current player should be player 2&lt;/i&gt;". This deals with the concept of the current player without requiring addition position arrays. It should only affect the &lt;code&gt;Roll()&lt;/code&gt; implementation. Let's skip our last test by updating the attribute to &lt;code&gt;[Fact(Skip="Too big a step for now")]&lt;/code&gt; (I could delete the test and rewrite it if we need it, but it did illustrate our need to deal with the current player concept, so I'll leave it for now). I started off coding our new test with two separate assertions:&lt;/p&gt;

&lt;pre&gt;var newTwoPlayerGame = new Game(10, 2);
Assert.Equal(1, newTwoPlayerGame.CurrentPlayer);
newTwoPlayerGame.Roll(2);
Assert.Equal(2, newTwoPlayerGame.CurrentPlayer);&lt;/pre&gt;

&lt;p&gt;The split asserts are ugly, and we can split this into two more specific tests. Here's the passing code, which was written one step at a time (not shown is chaining the &lt;code&gt;Game(int)&lt;/code&gt; constructor to &lt;code&gt;Game(int, int)&lt;/code&gt;, so everything gets initialised properly in either case. Check the download at the end for the finished code):&lt;/p&gt;

&lt;pre&gt;//From GameSpec.cs:
[Fact]
public void Current_player_for_new_game_should_be_player_1() {
 var newTwoPlayerGame = new Game(10, 2);
 &lt;b&gt;Assert.Equal(1, newTwoPlayerGame.CurrentPlayer);&lt;/b&gt;
}
[Fact]
public void After_first_players_roll_it_should_be_the_second_players_turn() {
 var newTwoPlayerGame = new Game(10, 2);
 newTwoPlayerGame.Roll(2);
 &lt;b&gt;Assert.Equal(2, newTwoPlayerGame.CurrentPlayer);&lt;/b&gt;
}
//From Game.cs:
&lt;b&gt;public int CurrentPlayer { get; private set; }&lt;/b&gt;
public Game(int boardSize, int numberOfPlayers) {
 this.boardSize = boardSize;
 this.numberOfPlayers = numberOfPlayers;
 this.playerPositions = new int[numberOfPlayers];
 &lt;b&gt;this.CurrentPlayer = 1;&lt;/b&gt;
}
public void Roll(int dieValue) {
 CurrentSquare += dieValue;
 &lt;b&gt;CurrentPlayer++;&lt;/b&gt;
}&lt;/pre&gt;

&lt;p&gt;Before we go back to the test we skipped, I'd like to flesh out more of the &lt;code&gt;CurrentPlayer&lt;/code&gt; property. Fifth test on our list was &amp;quot;&lt;i&gt;First player rolls a 3, second player rolls a 2, then current player should be player 1 on square 3&lt;/i&gt;&amp;quot;. Let's do a simpler version and just verify that this scenario ends up with the correct &lt;code&gt;CurrentPlayer&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;//In GameSpec.cs:
[Fact]
public void After_all_players_have_had_a_turn_it_should_be_first_players_turn_again() {
 var newThreePlayerGame = new Game(10, 3);
 newThreePlayerGame.Roll(1);
 newThreePlayerGame.Roll(1);
 newThreePlayerGame.Roll(1);
 Assert.Equal(1, newThreePlayerGame.CurrentPlayer);
}
//In Game.cs:
public void Roll(int dieValue) {
 CurrentSquare += dieValue;
 CurrentPlayer++;
 &lt;b&gt;if (CurrentPlayer &gt; NumberOfPlayers) CurrentPlayer = 1;&lt;/b&gt;
}
&lt;/pre&gt;

&lt;h2&gt;A quick refactor from the green bar&lt;/h2&gt;
&lt;p&gt;We now have a green bar (well, yellow if you count the skipped test I guess). Time to take a look for potential refactoring opportunities. I've been a bit slack about this up to now as I haven't noticed anything obvious while coding and haven't explicitly stopped to think about refactoring. I have a bad habit of doing this -- I do design work while writing the code to pass the test, rather than deferring it to the refactoring stage. This can lead me to generalising to early or changing the design without getting clear direction from the tests and passing implementation. Note to self: premature generalisation is one of the many roots of all evil :)&lt;/p&gt;

&lt;p&gt;In this case we've done the Right Thing&lt;sup&gt;TM&lt;/sup&gt; and written simple code to pass the test, then looked at refactoring based on what the current implementation needs, rather than what we &lt;i&gt;think&lt;/i&gt; it will need. The code within &lt;code&gt;Roll()&lt;/code&gt; contains the logic for selecting the next player as well as for updating the current square. Let's &lt;a href="http://www.refactoring.com/catalog/extractMethod.html"&gt;Extract Method&lt;/a&gt; to make this more obvious.&lt;/p&gt;

&lt;pre&gt;public void Roll(int dieValue) {
 CurrentSquare += dieValue;
 &lt;b&gt;nextPlayer();&lt;/b&gt;
}
private void nextPlayer() {
 CurrentPlayer++;
 if (CurrentPlayer &gt; NumberOfPlayers) CurrentPlayer = 1;
}&lt;/pre&gt;

&lt;p&gt;This is purely a matter of taste. I find it reflects the intention more. If you don't, then leave it un-refactored. :-) Either way, key lesson here (for me, you probably know it already :)) is to defer design stuff until the production code shows a clear need, or until a test is too hard to write. Either way, design from the green bar whenever possible.&lt;/p&gt;

&lt;h2&gt;Time to face the music...&lt;/h2&gt;

&lt;p&gt;We probably shouldn't put it off any longer. Let's re-enable the test we skipped earlier:&lt;/p&gt;

&lt;pre&gt;//In GameSpec.cs:
[Fact]
public void Positions_should_be_correct_after_first_two_players_roll() {
 var threePlayerGame = new Game(10, 3);
 const int firstRoll = 3;
 const int secondRoll = 5;
 
 threePlayerGame.Roll(firstRoll);
 threePlayerGame.Roll(secondRoll);
 
 Assert.Equal(firstRoll, threePlayerGame.GetSquareFor(1));
 Assert.Equal(secondRoll, threePlayerGame.GetSquareFor(2));
 Assert.Equal(0, threePlayerGame.GetSquareFor(3));
}&lt;/pre&gt;

&lt;p&gt;This give the following assertion failure:&lt;/p&gt;
&lt;pre&gt;TestCase 'DaveSquared.GardenRace.Tests.GameSpec.Positions_should_be_correct_after_first_two_players_roll'
failed: Assert.Equal() Failure
Expected: 3
Actual:   0&lt;/pre&gt;

&lt;p&gt;This is failing because our implementation for &lt;code&gt;GetSquareFor(...)&lt;/code&gt; stinks -- it's just returning 0. My fault, not yours. Let's get back to the green bar as soon as possible, then we'll worry about getting the design right. My original guess for passing this test was that we would need an array of player positions, and &lt;code&gt;Roll()&lt;/code&gt; would just update the position for the current player. We have a current player concept in the code now, so let's chuck in an array and see how it goes:&lt;/p&gt;

&lt;pre&gt;//Bits and pieces from Game.cs:
public class Game {
    //...
 private readonly int[] playerPositions;
 //...
 public Game(int boardSize, int numberOfPlayers) {
  this.boardSize = boardSize;
  this.numberOfPlayers = numberOfPlayers;
  &lt;b&gt;this.playerPositions = new int[numberOfPlayers];&lt;/b&gt;
  this.CurrentPlayer = 1;
 }
 public void Roll(int dieValue) {
  CurrentSquare += dieValue;
  &lt;b&gt;playerPositions[CurrentPlayer - 1] = CurrentSquare;&lt;/b&gt;
  nextPlayer();
 }
 //...
 public int GetSquareFor(int player) {
  &lt;b&gt;return playerPositions[player - 1];&lt;/b&gt;
 }
}&lt;/pre&gt;

&lt;p&gt;Running this fails with a new message:&lt;/p&gt;

&lt