<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[Mike Murray]]></title>
  <link href="http://mkmurray.com/atom.xml" rel="self"/>
  <link href="http://mkmurray.com/"/>
  <updated>2012-12-15T15:41:41-07:00</updated>
  <id>http://mkmurray.com/</id>
  <author>
    <name><![CDATA[Mike Murray]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[The Value is the Boundary]]></title>
    <link href="http://mkmurray.com/blog/2012/12/15/the-value-is-the-boundary/"/>
    <updated>2012-12-15T15:31:00-07:00</updated>
    <id>http://mkmurray.com/blog/2012/12/15/the-value-is-the-boundary</id>
    <content type="html"><![CDATA[<p><em>Author&#8217;s Note: I do not take credit for the phrase used as the title of this
blog post. It comes from Gary&#8217;s Ruby Conf 12 video recording entitled
<u>Boundaries</u> mentioned below and in the previous blog post.</em></p>

<p>In the last blog post <a href="http://mkmurray.com/blog/2012/12/08/testing-trade-offs/">Testing
Trade-offs</a>, I talked about the
difficulties of verifying the decisions and dependencies of our classes with the
current mainstream testing methodologies. Based on a recorded conference talk by
<a href="https://twitter.com/garybernhardt">Gary Bernhardt</a>, the focus was on
effectively testing the logic a class contains and the dependent collobrators it
takes in for coordinating with other classes and objects to perform its
responsibilities. Mixing the two concerns in the same object definition requires
utilizing both isolated unit testing and integration/integrated testing in order
to adequately test cover the class. However, code designed this way seems to
play to the weaknesses of each testing strategy just as much as it plays to
their strengths (please see the previous blog post if you would like more
details on that discussion).</p>

<p>Today let&#8217;s go one step further and talk about ways that we could more cleanly
separate the concerns of decisions and dependencies, with the hope that we can
create objects that better lend themselves to one type of testing over the
other. Gary proposes that a such a codebase could have better modularity,
scalability, and even concurrency. I assert that your code will also be more
maintainable and extensible as well. Most of today&#8217;s content will take a lesson
from the functional programming paradigm, including practices they have espoused
for decades.</p>

<h2>Frictionless Isolated Unit Testing</h2>

<p>If you wanted to test the mathematical addition operator (i.e., the plus sign
<code>+</code>), what frameworks, tools, and/or coding tricks do you have to employ to
sufficiently isolate it from all other concerns and objects? Absolutely nothing!
There are no dependencies to mock or stub; it isolates for free. Why is that?
Gary cautions against assuming it is because the addition operator is simple and
lacks complexity. He digs deeper in order to identify two properities the
implementation of plus sign exhibits that allows it to be naturally isolated.</p>

<p>The first property is that the operator takes values as arguments and returns
new values as output without any mutation. The second property is that the
operator requires no dependencies in order to perform its computation and logic.
Thus there is nothing to mock or stub when testing it, which was the major
weakness of isolated unit testing. Also because of the lack of dependencies, no
integrated tests are required in order to better test how the operator will
behave in a production environment where there are no mocks and stubs. To test
the addition operator we merely need to write simple pass-values-in,
assert-value-out tests with no extra setup required.</p>

<p>As Gary applies these concepts to existing code, we notice a few changes. Pieces
of domain logic and pieces of code that coordinate dependencies are separated
from each other, broken out into new objects created for a single purpose and
responsibility. The nature of the communication between objects also changed,
with values (inputs and outputs) becoming the boundary between objects instead
of the emphasis being on several synchronous method calls. Value objects focused
on data (and not behavior) become the new contract between collaborating
classes.</p>

<h2>To Be Continued&#8230;</h2>

<p>You may notice that many of these concepts have a functional programming
influence. The properties of immutability and focus on data at the boundaries
allow us to write code that isolates very easily and lends itself very well to
isolated unit testing that is simple and not brittle. It is very good at
verifying the domain logic and decision paths of our objects. Of course, we
can&#8217;t write the entirety of our codebase in this manner with no dependencies
ever. Next time I will discuss a code architecture that Gary proposes which can
utilize this style of code married with some more imperative glue code that
coordinates the dependencies in the system. We will also discuss testing those
portions of code as well.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Testing Trade-offs]]></title>
    <link href="http://mkmurray.com/blog/2012/12/08/testing-trade-offs/"/>
    <updated>2012-12-08T21:11:00-07:00</updated>
    <id>http://mkmurray.com/blog/2012/12/08/testing-trade-offs</id>
    <content type="html"><![CDATA[<p>Last week our dev team at Extend Health watched a <a href="http://www.youtube.com/watch?v=yTkzNHF6rMs">RubyConf 2012 video of a talk
entitled Boundaries</a> by <a href="https://twitter.com/garybernhardt">Gary
Bernhardt</a> of <a href="https://www.destroyallsoftware.com/screencasts">Destroy All
Software</a> (or perhaps even
better known for the infamous <a href="https://www.destroyallsoftware.com/talks/wat">WAT lightning talk at CodeMash
2012</a>). Gary proposes a very
interesting code architecture that marries the individual benefits of
immutability &amp; mutability, functional programming &amp; imperative object-oriented
programming, isolated unit testing &amp; integration testing. He discusses the pros
&amp; cons of each code design &amp; testing decision and the trade-offs that we end up
dealing with. He suggests a potential solution that makes virtually no trade-off
and attempts to harness the advantages of each of these methodologies that
appear to be at odds with one another. I feel the idea has a lot of merit and I
highly encourage everyone to watch his presentation to get the full context and
a better logical progression of his proposal than what I can provide.</p>

<h2>Isolated Unit Testing vs. Integration Testing</h2>

<p>A common practice in unit testing classes and objects is to isolate the targeted
class from its dependencies so that you can focus solely on its responsibilities
and domain logic independent of any implementation details of the dependencies.
This is typically accomplished by the use of stubs and mocks, which attempt to
control and monitor the interactions with and data return from dependencies.
There are a ton of gains afforded by this style of testing as Gary points out,
but one very large criticism of this testing methodology is that it doesn&#8217;t
exercise the code in the same way it would run in production. It is not exactly
rare to have these isolated unit tests successfully pass and yet still have
problems in production.</p>

<p>Integration testing tends to better emulate production because it maintains the
interaction relationships between objects in addition to acquiring and passing
the data around the system in the same way. The criticism Gary puts forth of an
integrated testing strategy is that it is very slow as you begin to attempt to
cover all the code paths through the system. Consider trying to cover all
logical branches through the system, including all branches of
try/catch/finally, conditional, and looping structures. Gary suggests the growth
in code to cover these scenarios is 2<sup>n<sup>,</sup></sup> where <code>n</code> is the number of branches.</p>

<p>Many try to get the benefits of both types of testing in order to compensate for
each strategy&#8217;s shortcomings. However, they still write code that doesn&#8217;t play
to each testing methodolgy&#8217;s strengths. The strength of isolated unit testing is
verifying that given certain inputs the expected output is always returned. The
strength of integration testing is coordinating dependencies, making sure they
utilize and interact with the API of other objects correctly. If you design your
classes to be a mix of dependencies and logic, it becomes difficult to
effectively test cover them without writing both sets of tests for all classes
in your codebase.</p>

<h2>So What?</h2>

<p>OK, so you are probably wondering what the point is then. This sounds like a
good plan to just be more disciplined in your test coverage, right? Well, let&#8217;s
explore a way to better segregate dependency orchestration from actual logic and
behavior. This could allow us to use the right testing methodology depending on
which type of responsibility the object is meant to encapsulate: dependencies or
decisions? Gary also asserts that it will lead us down a path that could yield a
codebase with better modularity, scalability, and potentially even concurrency.
I believe you can also add better maintainability and extensibility to that
list.</p>

<p>Next week I will dive into how Gary suggests we can better seperate these
concerns of dependencies and decisions. Stay tuned (or go watch the video and
spoil the surprise).</p>

<p>Next post: <a href="http://mkmurray.com/blog/2012/12/15/the-value-is-the-boundary/">The Value is the Boundary</a></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Async lambda expressions and anonymous delegates]]></title>
    <link href="http://mkmurray.com/blog/2012/12/01/async-lambda-expressions-and-anonymous-delegates/"/>
    <updated>2012-12-01T22:34:00-07:00</updated>
    <id>http://mkmurray.com/blog/2012/12/01/async-lambda-expressions-and-anonymous-delegates</id>
    <content type="html"><![CDATA[<p>I&#8217;ve known about the new <code>async</code> and <code>await</code> keywords in C# 5 for a while now,
but I saw a use of it I hadn&#8217;t anticipated. I saw Jon Skeet create an
asyncronous lambda expression and was caught a bit off guard. After thinking
about it, it really isn&#8217;t that amazing, but I thought I would spread the word
anyway because I think it could be a really handy feature.</p>

<p>Anonymous functions are declared without a method name and can be passed around
and invoked at will. Lambda expression syntax creates anonymous functions that
can be used as delegates or expression trees. In C# 5, you can adorn functions
with the <code>async</code> keyword which signifies that the function will return a <code>Task</code>
object from the Task Parallel Library as a return value. You will also find
somewhere in the method body the keyword <code>await</code> next to a statement that could
take a while to process and be a blocking operation. Now your method can resume
operation after the asyncronous operation has completed and has its result.</p>

<p>Here is a simple example:</p>

<pre class="brush: csharp">
    public void ButtonClick()
    {
        ProcessFiles();
    }

    private async void ProcessFiles()
    {
        var files = new string[] { "file1.txt", "file2.txt", "file3.txt" };

        foreach (var file in files)
        {
            var fileContents = await ReadTextAsync(file);
            // likely do something with file contents
        }
    }

    private async Task&lt;string&gt; ReadTextAsync(string filePath)
    {
        // Some text reading implementation that supports the TPL
    }
</pre>


<p>The button click handler method would return at the first sign of a blocking
operation and callback delegates are set up under the covers by the compiler to
finish executing the rest of the code after the blocking process finishes.</p>

<p>Here is the same example but using an async lambda expression:</p>

<pre class="brush: csharp">
    public void ButtonClick()
    {
        var files = new string[] { "file1.txt", "file2.txt", "file3.txt" };

        files.ForEach(async file => await ReadTextAsync(file));
    }

    private async Task&lt;string&gt; ReadTextAsync(string filePath)
    {
        // Some text reading implementation that supports the TPL
    }
</pre>


<p>Please overlook my disregard of single responsibility and encapsulation, and so
on so forth. This is an overly simplified example intended solely to show what
the syntax looks like. Either way, I could see this lighter weight syntax coming
in handy in the future.</p>

<p>In the same example where I saw async lambda syntax used, I also saw Jon Skeet
show off a really clever extension method that took an enumerable collection of
<code>Task</code> objects and reordered them so they could be enumerated and handled in the
order that they complete their asynchronous operations. Perhaps I will show that
piece of code next time.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Well-Rounded Developers]]></title>
    <link href="http://mkmurray.com/blog/2012/11/17/well-rounded-developers/"/>
    <updated>2012-11-17T19:32:00-07:00</updated>
    <id>http://mkmurray.com/blog/2012/11/17/well-rounded-developers</id>
    <content type="html"><![CDATA[<p>I had the opportunity this week to talk with some terrific Computer Science
students nearing graduation and who were beginning to look for employment. It
provided me the chance to put into words the amazing culture and environment
that exists at my workplace. The software development team at <a href="https://www.extendhealth.com/">Extend
Health</a> is second to none in both talent and
passion for creating clean, modular code that is maintainable because of its
extensibility. Everyone on the team contributes and has a trusted voice. It
truly is an environment I&#8217;ve never seen before and am certainly proud to be
apart of.</p>

<p>One of the main things that hit me while talking to these graduating students
was how well-rounded our developers have come. No, I&#8217;m not talking about the
amount of soda and treats we consume. I&#8217;m referring to the varying skills each
one of us have developed. From front-end to back-end or web sites to desktop
apps, every single member of the team is capable of jumping into any of our
codebases and tackling new features or bugs with a excellent degree of
competentcy. I find this fascinating because it is not the norm at many medium
to large size companies. It is typical for a developer to be hired to a
position or team where he or she works on a single project and codebase for a
few years until they get bored enough to change positions within the company or
go somewhere else completely. This has not been the case for all of the
developers at Extend Health.</p>

<p>We are currently divided into four teams of about four or five devs each. While
each team may have past experience with a certain project or codebase, they are
not automatically the chosen team to work on it again the next time. Because of
this, there is shared knowledge across teams and team members, instead of all
the knowledge residing in only one person&#8217;s head. This avoids the &#8220;what if
someone gets hit by a bus&#8221; problem <a href="http://rhauert.wordpress.com/2012/11/17/the-bus-factor/">my coworker Ryan just blogged
about</a>. The other side
effect is that our developers have all become well-rounded in varying languages
and platforms, solving both front-end and back-end problems. Contrast this with
how I used to classify my dev skill set four or five years ago before working
at Extend Health. I used to consider myself a back-end systems developer,
feeling it was important to have specialization in order to differentiate myself
and provide a chance to develop focused and in-depth experience. I also fooled
myself into thinking that I preferred this designation because web development
was trivial and only the hardest and most worthwhile problems were in the
back-end systems. Instead, I merely lacked some meaningful experience with
front-end web development, which is harder to come by in the typical work
enivronment I described above. However in my current employment, I&#8217;ve become a
much more well-rounded software developer.</p>

<p>I&#8217;m not entirely positive if our environment and team dynamic were
intentionally setup to ensure we were all well-rounded developers (though every
other good aspect of our dev culture seems to have been carefully pieced
together by <a href="http://coreykaylor.com/">Corey</a>). Regardless, I am appreciatevly
taking note of the advantageous results of such a configuration. This is one
very important aspect of true job satisfaction and also in avoiding high
turnover and attrition in workforce.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Refactoring Legacy Code Starts with Test Coverage]]></title>
    <link href="http://mkmurray.com/blog/2012/11/10/refactoring-legacy-code-starts-with-test-coverage/"/>
    <updated>2012-11-10T15:37:00-07:00</updated>
    <id>http://mkmurray.com/blog/2012/11/10/refactoring-legacy-code-starts-with-test-coverage</id>
    <content type="html"><![CDATA[<p>As a dev team, we have been watching and discussing various training videos and
conference talks every morning for a few months now. This week we watched a
recorded conference talk by Ruby developer <a href="http://kytrinyx.com/">Katrina Owen</a>
entitled <a href="http://www.youtube.com/watch?v=J4dlF0kcThQ">Therapeutic Refactoring</a>.
I was especially impressed with her strategy for refactoring legacy code.</p>

<p>I&#8217;m sure everyone can agree that the safest way to refactor code and be 100%
positive that the functionality hasn&#8217;t regressed is to have a good suite of
tests. And if you don&#8217;t have sufficient test coverage (or any at all), then now
is the right time to add it before refactoring.</p>

<p>However, I have found myself skipping this step in the past, feeling justified
because the quality of the code was so poor or the deadline was so short. It is
irresponsible of me to assume that I have not changed the functionality of the
code without proof in the form of passing tests that sufficiently cover all
scenarios and use cases.  Nonetheless, watching Katrina&#8217;s presentation has
given me renewed commitment and a sound plan of attack against legacy code that
may be ugly and very unfamiliar to me.</p>

<p>Here is the example method that Katrina uses during her presentation (which is
later revealed as a piece of code that she vaguely remembers coding herself and
now abhors):</p>

<pre class="brush: ruby">
    module XYZService

      def self.xyz_filename(target)
        # File format:
        # [day of month zero-padded][three-letter prefix] \
        # _[kind]_[age_if_kind_personal]_[target.id] \
        # _[8 random chars]_[10 first chars of title].jpg
        filename = "#{target.publish_on.strftime("%d")}"
        filename << "#{target.xyz_category_prefix}"
        filename << "#{target.kind.gsub("_", "")}"
        filename << "_%03d" % (target.age || 0) if target.personal?
        filename << "_#{target.id.to_s}"
        filename << "_#{Digest::SHA1.hexdigest(rand(10000).to_s)[0,8]}"
        truncated_title = target.title.gsub(/[^\[a-z\]]/i, '').downcase
        truncate_to = truncated_title.length > 9 ? 9 : truncated_title.length
        filename << "_#{truncated_title[0..(truncate_to)]}"
        filename << ".jpg"
        return filename
      end

    end
</pre>


<p>It certainly isn&#8217;t the worst lines of code ever written and it is getting the
job done, but it is definitely not very readable and quite difficult to
understand its purpose and logic. About the only thing that can be discerned is
that it is intended to generate a filename in a specific format.</p>

<p>Katrina starts by writing a very simple and seemingly useless test (which she
calls a &#8220;Mickey Mouse test&#8221; in her GitHub commit message) in order to begin test
coverage of this method:</p>

<pre class="brush: ruby">
    require_relative './xyz_service'

    describe XYZService do

      let(:target) do
        stub(:target)
      end

      subject { XYZService.xyz_filename(target) }

      it 'works' do
        subject.should eq('something')
      end

    end
</pre>


<p>Without much knowledge of what this method&#8217;s purpose or inputs are, we can only
pass in an empty stub object as input and then assert something rediculous for
the result. We expect this test to not only fail to pass, but it is also likely
to error during runtime (or even at compile time if in a statically typed
language like C#). The idea is to create a quick feedback loop that aids us in
finding the context and inputs required to make the code execute without runtime
error. Then we can finally see the actual return value and modify our dummy
assertion to begin expecting that output.</p>

<p>After iterating in this fashion, Katrina arrives at the following test which is
a bit more useful:</p>

<pre class="brush: ruby">
    require_relative './xyz_service'
    require 'date'

    describe XYZService do

      let(:target) do
        messages = {
          :publish_on => Date.new(2012, 3, 14),
          :xyz_category_prefix => 'abc',
          :kind => 'unicorn',
          :personal? => false,
          :id => 1337,
          :title => 'magic & superglue'
        }
        stub(:target, messages)
      end

      subject { XYZService.xyz_filename(target) }

      it 'works' do
        subject.should eq('14abcunicorn_1337_cb6c53bc_magicsuper.jpg')
      end

    end
</pre>


<p>However, this test doesn&#8217;t pass because the <code>cb6c53bc</code> portion of the resultant
filename is different every execution of the test. A simple regex allows the
test to pass all of the time:</p>

<pre class="brush: ruby">
    subject.should match(/14abcunicorn_1337_[0-9a-f]{8}_magicsuper\.jpg/)
</pre>


<p>Even though we now have a passing test, we have not yet exercised the different
input values and all code paths and branches through the method. This must be
done in order to fully understand, document, and test cover the logic and
purpose of the method. This would be done in the normal unit testing fashion
that is shown in just about every testing demo by adding more test scenarios and
assertions that excercise the varying use cases.</p>

<p>One interesting development that occurred while Katrina was using this process
was that she actually found a bug in the implementation of the original
<code>xyz_filename</code> method, specifically an extra set of braces in the regex on line
14.</p>

<p>Now that we are fully covered with tests (and a bug fixed), we are free to
refactor the code into smaller, more readable chunks of code logic that are more
cohesive and more reusable as well. This is what Katrina does for the remainder
of her presentation, and it is just as instructive as this first part. However,
today I wanted to focus on her strategy for writing test coverage against a
legacy codebase.</p>

<p>I like how what Katrina is demonstrating seems to utilize a black box testing
approach at first, and then progresses to a more white box approach as we begin
to explore the different parts of the implementation. Perhaps such a strategy
should have been obvious to me, but Katrina&#8217;s conference talk really struck a
chord with me and encouraged me to commit to doing better with test coverage in
legacy codebases before I begin making modifications or additions.</p>

<p>I highly recommend viewing the entire video, as it is only 30 minutes long and
an entertaining watch.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Using SQL PIVOT and UNPIVOT]]></title>
    <link href="http://mkmurray.com/blog/2012/11/03/using-sql-pivot-and-unpivot/"/>
    <updated>2012-11-03T23:22:00-06:00</updated>
    <id>http://mkmurray.com/blog/2012/11/03/using-sql-pivot-and-unpivot</id>
    <content type="html"><![CDATA[<p>I learned about a pair of SQL keywords I didn&#8217;t know existed before. I suppose I shouldn&#8217;t have been so surprised
this ability existed in SQL since I knew it existed within Excel spreadsheets, but it really saved the day this
last week. I&#8217;m speaking of the <code>PIVOT</code> and <code>UNPIVOT</code> SQL keywords.</p>

<p>This last week I needed to track down some data inconsistencies in our database by joining a few view model tables.
These tables are populated by event handlers that denormalize the relevant data from events into a view model
table that serves the needs of a specific part of the UI. In one particular view model table, it made sense to
arrange the data points specific to each US state as columns on a single row. This allowed for a grid-based UI that
enables batch operations on many rows at one time. A second view model table was intended for a different use case
and was designed so that the state-specific data points became a one-to-many relationship across multiple rows and
only two columns for the key-value pair of the US state and its associated data point value. These were two of the
tables I needed to join together during my database inquisition.</p>

<p>At this point I figured I was stuck, as I couldn&#8217;t see a sensible way to join two tables designed so contrary to
each other for the purposes of joining. I tried to think of any ways to dynamically join tables on a column name
in one table specified by the value in the other table&#8217;s row. I knew I was heading nowhere fast, so I asked our
DBA for some ideas. He informed me of the <code>PIVOT</code> and <code>UNPIVOT</code> keywords in SQL as one option to solve the problem.
We reasoned that even though it may not be the most efficient feature, the likelihood of it proving to be a
performance bottleneck would be essentially non-existent (given that the entire size of the data set was relatively
small, on the magnitude of hundreds or thousands of rows instead of millions of rows). And so I gave it a go.</p>

<p>I will now describe an example scenario in order to illustrate how I used the <code>UNPIVOT</code> feature to join two tables
that didn&#8217;t seem at all compatible. The goal will be to join a table representing what US states each product is
available for sale within to a table representing how many of each product are being sold in each state. We will
call the first table <code>ProductAvailability</code> and give it an integer identity column named <code>Id</code>, an integer column
named <code>ProductId</code>, and then 52 <code>bit</code> columns indicating the availability status of the product in each of the 50 US
states, the District of Columbia, and Puerto Rico. These columns will be named by their two letter abbreviations of
<code>AK</code> through <code>WY</code>. The second table we will call <code>ProductSales</code> and it will also have an integer identity column
named <code>Id</code> and an integer column named <code>ProductId</code>. In addition it will have a string column (specifically
<code>char(2)</code>) named <code>StateCode</code> and an integer column named <code>TotalSales</code>.</p>

<p>The unpivoting of the <code>ProductAvailability</code> table to prepare it for joining can be done like so:</p>

<pre class="brush: sql">
    SELECT
      Unpivoted.ProductId,
      Unpivoted.StateCode,
      Unpivoted.IsAvailable
    FROM ProductAvailability
    UNPIVOT
    (
      IsAvailable FOR StateCode
      IN (AK,AL,AR,AZ,CA,CO,CT,
          DC,DE,FL,GA,HI,IA,ID,
          IL,IN,KS,KY,LA,MA,MD,
          ME,MI,MN,MO,MS,MT,NC,
          ND,NE,NH,NJ,NM,NV,NY,
          OH,OK,OR,PA,PR,RI,SC,
          SD,TN,TX,UT,VA,VT,WA,
          WI,WV,WY)
    ) AS Unpivoted
</pre>


<p>The interesting part is obviously the <code>UNPIVOT</code> clause. Here we are declaring a list of column names to unpivot and
also naming two new columns in which to place the old column&#8217;s name and value (<code>StateCode</code> and <code>IsAvailable</code>
respectively). The result is that instead of having one row of 54 columns for each product, we now have 52 rows of
three columns to describe the exact same availability of the product. But with this second schema, we can more
easily join with the <code>ProductSales</code> table.</p>

<p>Here is an example of such a query where we are trying to find the products which have no sales in a state for
which it is marked as available for sale:</p>

<pre class="brush: sql">
    SELECT
      ProductStateAvailability.ProductId,
      ProductStateAvailability.StateCode
    FROM
    (
      SELECT
        Unpivoted.ProductId,
        Unpivoted.StateCode,
        Unpivoted.IsAvailable
      FROM ProductAvailability
      UNPIVOT
      (
        IsAvailable FOR StateCode
        IN (AK,AL,AR,AZ,CA,CO,CT,
            DC,DE,FL,GA,HI,IA,ID,
            IL,IN,KS,KY,LA,MA,MD,
            ME,MI,MN,MO,MS,MT,NC,
            ND,NE,NH,NJ,NM,NV,NY,
            OH,OK,OR,PA,PR,RI,SC,
            SD,TN,TX,UT,VA,VT,WA,
            WI,WV,WY)
      ) AS Unpivoted
      WHERE Unpivoted.IsAvailable = 1
    ) AS ProductStateAvailability
    INNER JOIN ProductSales
      ON ProductSales.StateCode = ProductStateAvailability.StateCode
      AND ProductSales.ProductId = ProductStateAvailability.ProductId
    WHERE ProductSales.TotalSales = 0
</pre>


<p>I hope you find the <code>PIVOT</code> and <code>UNPIVOT</code> SQL keywords just as helpful as I did if you ever find yourself in a bind
with two tables that are seemingly impossible to join.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[FubuMVC Webinar - Compositional and Convention-based Web Development]]></title>
    <link href="http://mkmurray.com/blog/2011/07/21/fubumvc-webinar-compositional-and-convention-based-web-development/"/>
    <updated>2011-07-21T12:44:00-06:00</updated>
    <id>http://mkmurray.com/blog/2011/07/21/fubumvc-webinar-compositional-and-convention-based-web-development</id>
    <content type="html"><![CDATA[<div class='post'>
<p>I just gave a webinar yesterday for <a href="http://www.jpboodhoo.com/">JP Boodhoo’s</a> <a href="http://webinars.developwithpassion.com/">Develop With Passion® webinar series</a> on Compositional and Convention-based Web Development with <a href="http://fubumvc.com/">FubuMVC</a>. The recorded session is now posted online with a slew of referenced and related links. I apologize for the sound quality and will make corrections if I get another chance to do another webinar/screencast. Here is the link to the recording:</p>  <p><a href="http://webinars.developwithpassion.com/webinars/3">http://webinars.developwithpassion.com/webinars/3</a></p>  <p>I didn’t mention this in the screencast but before we began switching our company’s production website to FubuMVC, we first devised a way to get the benefit of <a href="http://murrayon.net/2011/06/fubumvc-behavior-chains-bmvc-pattern.html">FubuMVC Behavior Chains</a> while still on the ASP.NET MVC framework. Please feel free to read more about that successful venture at <a href="http://paceyourself.net/">Bob Pace’s</a> <a href="http://paceyourself.net/2011/06/11/mvctofubu---transition-your-website-from-aspnet-mvc-to-fubumvc-part-1/">blog post on the MvcToFubu project</a>.</p>  </div>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[FubuMVC Behavior Chains - The BMVC Pattern]]></title>
    <link href="http://mkmurray.com/blog/2011/06/13/fubumvc-behavior-chains-the-bmvc-pattern/"/>
    <updated>2011-06-13T16:01:00-06:00</updated>
    <id>http://mkmurray.com/blog/2011/06/13/fubumvc-behavior-chains-the-bmvc-pattern</id>
    <content type="html"><![CDATA[<div class='post'>
<p>For the last several months at work, we have been gradually migrating our production website to use the .NET open source <a href="http://fubumvc.com/" target="_blank">FubuMVC web framework</a>. Before committing to a whole new infrastructure for our site, some brilliant talent on our team decided to improve our experience on the ASP.NET MVC framework by integrating in one of FubuMVC’s most compelling features, behavior chains. <a href="https://twitter.com/#!/bob_pace" target="_blank">Bob Pace</a> originally blogged about the process in a two part blog post series (<a href="http://paceyourself.net/2010/08/06/integrating-fubumvc-with-aspnet-mvc-part-1/" target="_blank">part 1</a> and <a href="http://paceyourself.net/2010/08/13/integrating-fubumvc-with-aspnet-mvc-part-2/" target="_blank">part 2</a>); since then, he has <a href="https://github.com/bobpace/MvcToFubu" target="_blank">created a packaged solution called MvcToFubu</a> which he <a href="http://paceyourself.net/2011/06/11/mvctofubu---transition-your-website-from-aspnet-mvc-to-fubumvc-part-1/" target="_blank">just recently started another blog post series about</a>.</p>  <p>Behavior chains are by far my favorite feature of FubuMVC. I believe they single-handedly revolutionized our use of the MVC pattern in a web environment. In fact, I like to think of it as a whole new pattern, the <strong>BMVC Pattern</strong> (I was told by a coworker that the ‘B’ should stand for “Better”, and while that’s true, I’ll stick with “Behaviors”). No, I’m not sincerely trying to coin yet another design or architectural pattern buzzword. However, I am most sincerely not joking when I say behavior chains add a whole new dimension to how I design web architectures. I find myself creating composable pipelines of cohesive, testable components in lieu of monolithic controllers and actions.</p> <span class="fullpost">   <h3>What are Behavior Chains?</h3>    <p>Have you ever looked at your controller actions and thought “Man, there’s a lot going on here!” (validation, authorization, transactions, ORM setup, logging, caching, etc.)? If you haven’t, I urge you to take a conscious look at your controller actions and try to identify code that doesn’t <u>directly</u> relate to the purpose of the page (or sub-view of the page). Shouldn’t there be a way to move some of this secondary infrastructure code out of our controller actions and have it be applied conventionally to the correct actions/routes? Yes, and this is exactly what Behavior Chains are meant to accomplish, the ability to create composable pipelines of reusable behavior nodes for each route in your site.</p>    <p>Behavior chains can be built up in any order you want for each route via Conventions and Policies, which are extension points that allow you to inspect and modify the entire Behavior Graph that was built by FubuMVC during startup bootstrapping. The behavior graph is the modifiable collection of all behavior chains in the site, initially built with just a few default behavior nodes for each route. A typical behavior chain by default usually has an ActionCall node (representing the call to a controller action) and an Output node (often a tie-in to a view rendering engine, but can also be JSON or anything else). Other behavior nodes can be sprinkled into the pipeline in any order in front of or in between the ActionCall and the Output nodes. As mentioned before via the use of Conventions and Policies, it is common practice to filter your list of behavior chains using LINQ extension methods and then add a specific behavior node into the matching chains at a specific location in the chain. This truly elevates coding to conventions to a new level; some of the filtering criteria regarding controller actions that you may come up with could be as follows:</p>    <ul>     <li>Action method names that contain a certain word. </li>      <li>Actions methods that are located in a particular controller or namespace. </li>      <li>Action method signatures that contain an input/output model that implements a specific interface. </li>      <li>Action method signatures that contain an input/output model that contains a property of a certain type or have a particular C# attribute applied to it. </li>      <li>So on, so forth…whatever you can dream up! </li>   </ul>    <p>One more aspect of behavior chains that is important to point out is the logistics in how behavior nodes are chained together. The chains are not merely a linked-list of behavior nodes that are traversed linearly. Instead the makeup of the chains is better conceptualized to be an outer behavior node wrapping around an inner behavior node, which is then itself an outer node wrapped around another inner node, and so on. In fact, the FubuMVC developers like to refer to this chaining architecture as the Onion Layer Model or the Russian Doll Model (conjuring up a mental image of the <a href="http://en.wikipedia.org/wiki/Matryoshka_doll">nesting Russian doll toy called a matryoshka doll or a babushka doll</a>). When an outer behavior node has finished executing it’s logic, it can then optionally execute it’s inner behavior node logic (or stop the behavior chain entirely in order to return early with a response, an error, or even transfer to a different route and behavior chain). One of the key advantages that this wrapping architecture can afford is the ability for an outer behavior to run additional logic or clean up code after all inner behavior nodes have completed (i.e., transactions can be committed, connections can be closed, sessions can be disposed, etc.).</p>    <h3>How does this change the way I code my controllers?</h3>    <p>I find that my controller actions are much thinner and more focused on the base case and the successful code path. All the exceptional code paths and edge cases have been identified and deal with by the other behavior nodes in the chain, prior to my action call being invoked. My action call can now focus on the essential logic that differentiate this route from others. That essential logic doesn’t get lost anymore in the necessary infrastructure code that should be a secondary concern. And all of this logic can be broken up into cohesive, reusable components within a flexible request/response pipeline that can be built up automatically by coding to whatever conventions you deem beneficial. Behavior chains really do add a whole new first-class citizen to the MVC design pattern. Do yourself a favor and check out the MvcToFubu solution mentioned at the top of this post, and bring some FubuMVC behavior chain goodness to your ASP.NET MVC website. I think you might be as impressed as we were and yearn for <a href="http://lostechies.com/chadmyers/2011/05/30/cool-stuff-in-fubucore-and-fubumvc-series/">the other killer features of FubuMVC</a> as well.</p> </span>  </div>
<h2>Comments</h2>
<div class='comments'>
<div class='comment'>
<div class='author'>Mike Murray</div>
<div class='content'>
Thanks for thought! Perhaps I&#39;ll post on the mailing list and see what others think about it being involved in the FubuMVC documentation somewhere.</div>
</div>
<div class='comment'>
<div class='author'>Rex</div>
<div class='content'>
Great post, I didn&#39;t see this one when I was writing my post about authentication behavior. This is a great explanation of behavior chains in FubuMVC.<br /><br />This would also be a great intro to behaviors for the fubumvc guides.</div>
</div>
</div>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[.NET Needs More Apprenticeships]]></title>
    <link href="http://mkmurray.com/blog/2011/06/03/-net-needs-more-apprenticeships/"/>
    <updated>2011-06-03T15:50:00-06:00</updated>
    <id>http://mkmurray.com/blog/2011/06/03/-net-needs-more-apprenticeships</id>
    <content type="html"><![CDATA[<div class='post'>
<p>It came to my attention recently that there are a few companies in other dev circles with all-star developers who give back to their communities by doing apprenticeship programs or open door programs at their workplaces. Basically the idea is to let people come into your workplace and pair program with them, sharing knowledge and best practices. I believe we need more of this sense of community going on in the .NET space. I’m sure I’ve probably overlooked something (or perhaps I’m about to spout off craziness and heresies), but it just seems like we should be able to work out the logistics to make this a reality.</p> <span class="fullpost">   <p>The interesting thing is that this really isn’t a new concept in other professions. For example, the culinary world has had the idea of <a href="http://en.wikipedia.org/wiki/Stage_(cooking)">staging</a> for quite a while. Sometimes it’s a final part of an interview process and other times it’s just to swap techniques and recipes. As mentioned above, I was recently informed of a few dev companies that have taken this idea to our profession. In the Rails community, <a href="http://hashrocket.com/people/work-at-hashrocket/apprentice">Hashrocket has an apprenticeship program</a> where you can apply to be a part of their team for a week and soak in some of the awesome skills and techniques they possess. It appears they vet their candidates a bit to ensure they get the right kind of people coming in who are motivated and ready to learn, and also because the code being worked on is for real Hashrocket projects for their clients. In the Node.js space, <a href="http://joyeur.com/2011/04/05/events-ssjs-office-hours-and-codeconf/">Joyent has a program called Office Hours</a> where devs can register for free in advance to bring in something to work on with a Joyent employee at end of work day and get their feedback &amp; expert advice. They provide snacks, drinks, and a comfortable work environment.</p>    <p>I think these ideas are brilliant and foster real community among developers. Although this idea alone can improve the interview and hiring process, I think it can go further than that to help our profession mature in the sharing of best practices and proven techniques. For most .NET companies out there, I’m willing to bet there are few legitimate roadblocks that would prevent instituting programs like these. Being completely honest with yourself, how much of what you work on each day is top secret intellectual property that is core to the success of your company and absolutely cannot be seen by outsiders? Even if there are parts of your code that should not be seen by strangers, I’m sure there are projects and tasks to be done on the other parts of code that will still prove instructive for your invited guests. I encourage our dev community to do whatever it takes to make this happen: have the visitors sign non-disclosure agreements, interview and re-interview potential candidates to meet satisfactory requirements, don’t allow them to hook up thumb drives to your machine and steal your secrets, whatever! It doesn’t matter if it’s a week-long thing or a few hours; let’s realize we’re all in this together and build this community up to have a higher standard of software craftsmanship.</p> </span>  </div>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Develop with Passion bootcamp course - Denver 2011]]></title>
    <link href="http://mkmurray.com/blog/2011/05/31/develop-with-passion-bootcamp-course-denver-2011/"/>
    <updated>2011-05-31T09:27:00-06:00</updated>
    <id>http://mkmurray.com/blog/2011/05/31/develop-with-passion-bootcamp-course-denver-2011</id>
    <content type="html"><![CDATA[<div class='post'>
<p><a href="http://paceyourself.net/" target="_blank">A very talented coworker</a> and I recently went to JP Boodhoo’s <a href="http://www.jpboodhoo.com/training.oo" target="_blank">Develop with Passion bootcamp training course</a> (previously known as Nothin but .NET). I had originally heard of the course from <a href="http://www.davesquared.net/" target="_blank">Dave Tchepak</a> who <a href="http://www.davesquared.net/2009/08/nothin-but-net-sydney-2009-day-1.html" target="_blank">attended the course nearly two years ago</a>. This blog post is a wrap-up of my thoughts and feelings about the course itself, <a href="http://www.jpboodhoo.com/" target="_blank">JP Boodhoo</a> as the instructor &amp; experienced craftsman, and the .NET development community in general.</p> <span class="fullpost">   <p>My prior impressions of the course from what I had read was that I would be in awe of JP&#8217;s coding and design skills and very overwhelmed with the feeling that I didn&#8217;t really know how to code; also that I would get no sleep at all that week, going from early morning to past midnight every day. I had also heard from a previous course member (off the record) that JP’s organization and direction with course material was a bit disorganized back then (luckily this has changed significantly since he had taken the course). I was really excited to see some good BDD in action, get my TDD passion ignited again (I had actually mentioned on twitter recently that my motivation for test was waning as of late), and see JP&#8217;s mad Vim skills (since I have gotten into that the last few months).</p>    <p>Overall, I was pleasantly surprised with the fulfillment of most of my positive expectations and initial impressions going into the course. JP&#8217;s personality and passion are infectious, and his teaching skills are pretty top-notch. The course material was well-structured and there was a clear direction for what we hoped to cover throughout the week (and yet, he was still flexible enough to be able to briefly entertain an off-topic direction the students wanted to take the course). He stayed true to the advertised 9am-9pm every day no matter what. He said that when he did the late nighters with previous courses, people came back the next day with little sleep and trashed as far as coding &amp; learning capabilities go.</p>    <p>Watching him code so efficiently is quite a treat. He automates anything he does more than once so that a particular task doesn’t ever get in his way and hold him back the next time. His <a href="http://www.autohotkey.com/" target="_blank">AutoHotkey</a> scripts and automation tools that he has put together are absolutely incredible. He briefly touched the mouse two times the entire week, and it only for when one of his programs or Windows VM was wigging out. Screens and dialogs flew by so fast, you could tell he wasn&#8217;t going to let any UI (even Visual Studio) get in the way of his productivity to code. He mentioned he will be open sourcing some of his scripts that he uses to keep his development environment consistent across OS platforms. Definitely cool stuff.</p>    <p>As far as JP&#8217;s actual coding/design skills, I am absolutely floored. He certainly understands C# and .NET well. But it&#8217;s his Object-Oriented design skills that blew us away. I&#8217;ve realized I don&#8217;t really know OO design. I think too mechanically about the implementation of the solution instead of focusing on breaking down the problem into smaller manageable chunks. His TDD skills (both Top Down Design and Test Driven Development) are amazing. I&#8217;ve never been a fan of the TDD samples and intros I&#8217;ve seen (where the instructors do the absolute dumbest thing to make the test pass; JP admitted that style didn’t jive with him either). I&#8217;ve always thought that Behavior Driven Development and Top-Down Design were the way to go if I were to have tests drive my designs (or have tests at all for that matter; I&#8217;m still having trouble finding enthusiasm for tests written after development for modules and units). So it was great to see a master at that particular craft. It made me excited to use tests as a tool to guide my OO design, behavior discovery, and problem solving.</p>    <p>Some of you may recall that I had <a href="http://murrayon.net/2009/11/anagram-code-kata-bdd-mspec.html" target="_blank">previously investigated BDD, Machine.Specifications, and Top-Down Design a year and a half ago doing the Anagram Code Kata</a>. I think I can recognize better design and responsibility break-up and assignment nowadays. I likely will blog on these subjects again this year with new &amp; improved passion and knowledge.</p>    <p>There was one sad takeaway for me personally from the course, which was a sense of disappointment in the .NET development community in general. Giving myself some time since the course to really think it through, I’m realizing I’m probably being too tough on our community, as I know each Dev community out there suffers from it’s own set of problems. But I don’t want to excuse our shortcomings either; rather, I would like to point them out so that we can focus on them and root those weaknesses out. I think our community in specific is unique in that there is a big shot company that dictates the direction our community should take, sometimes taking credit for all the innovation. Things are improving lately no doubt; it appears Microsoft is listening more and more and trying to let outsiders get involved and contribute.</p>    <p>But we as .NET devs need to step up and take matters into our own hands, we need to take better control of the code we write and encourage best practices within the realms of our responsibilities and influence. I believe many .NET shops rely on the tools sent down from above so heavily that we don’t really solve problems anymore. JP’s focus on problem solving and code katas from the course attack this deficiency at its core. I do somewhat blame our university Computer Science programs for not teaching real OO (a great discussion on formalism versus hermeneutics in a book I highly recommend, <a href="http://www.amazon.com/Object-Thinking-DV-Microsoft-Professional-David/dp/0735619654" target="_blank">Object Thinking</a>), but at some point we have to take what we were given and no matter our current standing, focus on sharpening our skills through practice and continuous learning. It boils down to individual responsibility for our current skill set and progression as a software craftsman. JP’s course does a terrific job of waking you up to that realization and inspiring you to be a better professional at your craft.</p>    <p>I have a few takeaways from the course that I’ll publicly spell out now. First, I (and hopefully our whole team) need to better understand design patterns and have them become integral to our code discussions. JP was all about efficiency in keystrokes and related dev tasks, and it seems natural that our language and code discussions could benefit from more efficient communication using design pattern terminology to convey a lot about a specific design concept in only a few words. Second, I hope that I (and our team again) can really put our tests to work for us, helping us recognize the problem to be solved or the behavior that needs to be captured, and then guiding us toward a simple solution. The third takeaway is related to that last part, and that is to have simple solutions that are distributed across simple object implementations (focusing on behaviors) that adhere to SOLID principles. It appears the key is to not focus on implementation specifics until the very last responsible moment; if done right, the implementations to create should be so clear cut and trivial, almost spelled right out in the tests themselves. It’s hard to put into words, but it seems crucial to focus first on the collaborators needed while designing code at the higher levels, finding ways to offload as much responsibility as possible (at least that’s what it felt like) onto dependencies that have yet to be designed and implemented. Designing Top-Down in this way gave such simple and elegant solutions that were totally extensible and adhered to the <a href="http://en.wikipedia.org/wiki/Open/closed_principle" target="_blank">Open/Closed Principle</a> better than any other code I have ever seen before. Perhaps as I blog more about this, I’ll be able to better put this style of coding into words (especially as I try to better understand it myself; it all seems so magical still!).</p>    <p>Overall, a great course that I highly recommend to all. JP has mentioned doing a similar course in Ruby, which I personally find especially interesting, given the same design/coding techniques would seem to run against a lot less friction compared to the heavy reliance on interfaces and mocking that C# require.</p>    <p>Stay tuned as I try to put some of this stuff into practice!</p> </span>  </div>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[LINQ Query Syntax and Type Argument Inference]]></title>
    <link href="http://mkmurray.com/blog/2010/12/03/linq-query-syntax-and-type-argument-inference/"/>
    <updated>2010-12-03T15:29:00-07:00</updated>
    <id>http://mkmurray.com/blog/2010/12/03/linq-query-syntax-and-type-argument-inference</id>
    <content type="html"><![CDATA[<div class='post'>
<p>In LINQ, you can query in-memory data collections using <a href="http://msdn.microsoft.com/en-us/library/bb397947.aspx">Method Syntax (the <font face="Courier New">IEnumerable</font> extension methods) or Query Syntax (the SQL-like, declarative syntactic sugar on top of the underlying method calls)</a>.&#160; I was using the query syntax to join a few in-memory collections and then project (like a SQL <font face="Courier New">SELECT</font>) the denormalized data into a new object that only contained a few pieces of information from each of the separate data collections.&#160; The code could look similar to this (we&#8217;ll go with a shopping example in honor of the upcoming holiday season):</p>  <pre class="brush: csharp">var shoppingLists =
    from person in people
    join wishlist in wishlists on person.Id equals wishlist.personId
    join store in stores on store.Id equals wishlist.storeId
    select new
    {
        PersonName = person.Name,
        StoreName = store.Name,
        NumItems = wishlist.Items.Count
    };</pre>

<p>However, I ran into the following intellisense red squiggly error in the Visual Studio C# code editor on the second <font face="Courier New">join</font> statement:</p>

<blockquote>
  <p><font face="Courier New">The type arguments for method &#8216;IEnumerable&lt;TResult&gt; System.Linq.Enumerable.Join&lt;TOuter,TInner,TKey,TResult&gt;(this IEnumerable&lt;TOuter&gt;, IEnumerable&lt;TInner&gt;, Func&lt;TOuter,TKey&gt;, Func&lt;TInner,TKey&gt;, Func&lt;TOuter,TInner,TResult&gt;)&#8217; cannot be inferred from the query.</font></p>
</blockquote>

<p>The error might also end with a statement that says &quot;<font face="Courier New">Try specifiying the type arguments explicitly</font>.&quot;</p>
<span class="fullpost">
  <h3>Let’s Take a Closer Look…</h3>

  <p>The underlying problem is best understood by examining the method signature of the <a href="http://msdn.microsoft.com/en-us/library/bb534675.aspx">LINQ <font face="Courier New">Join</font> extension method</a> and how the LINQ query syntax for the keyword <font face="Courier New">join</font> maps to that method call in the compiler.&#160; The type signature for the extension method is as follows:</p>

  <pre class="brush: csharp">public static IEnumerable&lt;TResult&gt; Join&lt;TOuter,TInner,TKey,TResult&gt;(
    this IEnumerable&lt;TOuter&gt; outer,
    IEnumerable&lt;TInner&gt; inner,
    Func&lt;TOuter,TKey&gt; outerKeySelector,
    Func&lt;TInner,TKey&gt; innerKeySelector,
    Func&lt;TOuter,TInner,TResult&gt; resultSelector)</pre>

  <p>Consistent with all <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension methods</a>, it is <font face="Courier New">public static</font> and has a <font face="Courier New">this</font> keyword in front of the first method parameter, allowing you to call the <font face="Courier New">Join</font> method as if it had been declared in the original definition of the <font face="Courier New">IEnumerable&lt;&gt;</font> class or one of its inheriting children classes.</p>

  <p>The first two parameters are the two data collections being joined, and in the case of my LINQ query above, they would be the joined collection of <font face="Courier New">people</font> &amp; <font face="Courier New">wishlists</font> and then the <font face="Courier New">stores</font> collection, respectively.</p>

  <p>The next two method parameters take delegates or lambda expressions that select the key value from each collection participating in the join, <font face="Courier New">outer</font> collection key selector first and then the <font face="Courier New">inner</font> key selector second.&#160; The key values of each item in each collection will compared to each other for equality.&#160; It will use the normal definition of the <font face="Courier New">Equals</font> method for your object type (or if you specified a custom one in your class definition), or there is another <font face="Courier New">Join</font> extension method signature that takes in another method parameter that an object that conforms to the <font face="Courier New"><a href="http://msdn.microsoft.com/en-us/library/ms132151.aspx">IEqualityComparer&lt;TKey&gt; <font face="Arial">interface</font></a></font>.&#160; The key selectors from our LINQ query sample would be the two member access expressions in the &quot;<font face="Courier New">on store.Id equals wishlist.storeId</font><font face="Arial">&quot; statement.</font></p>

  <p>The last parameter is a delegate or lambda expression that takes in a item from each participating data collection and projects the items into a new form (like the <font face="Courier New">Select</font> LINQ query method and its SQL equivalent).&#160; The two items being passed into the <font face="Courier New">Func</font> have passed the equality comparison of each item’s key value, exactly the same as how rows from two tables match up in an <font face="Courier New">inner join</font> statement in SQL.</p>

  <p>As for the <a href="http://msdn.microsoft.com/en-us/library/0zk36dx2.aspx">generic type parameters</a> in this extension method definition, <font face="Courier New">TOuter</font> and <font face="Courier New">TInner</font> are the types from the two collections participating in the join.&#160; <font face="Courier New">TKey</font> is the type returned by the key selectors; notice that in order to compare the equality of each key selected, they need to be of the same type.&#160; In our example, <font face="Courier New">TKey</font> is likely <font face="Courier New">int</font> or <font face="Courier New">long</font> (or maybe <font face="Courier New">Guid</font>) since we’re dealing with <font face="Courier New">Id</font> properties of all of our objects.&#160; <font face="Courier New">TResult</font> is the type returned by the projection <font face="Courier New">Func&lt;TOuter,TInner,TResult&gt; resultSelector</font>; in our case, we returned an <a href="http://msdn.microsoft.com/en-us/library/bb397696.aspx">anonymous type</a> consisting of three properties (<font face="Courier New">PersonName</font>, <font face="Courier New">StoreName</font>, and <font face="Courier New">NumItems</font>).</p>

  <h3>Ok, So Where Did I Screw Up Then?</h3>

  <p>To answer this, let’s take a look one more time at my LINQ query syntax, how it would map to LINQ method syntax, and the <font face="Courier New">Join</font> method signature again all side-by-side:</p>

  <pre class="brush: csharp; highlight: [4,19,20]">var shoppingLists =
    from person in people
    join wishlist in wishlists on person.Id equals wishlist.personId
    join store in stores on store.Id equals wishlist.storeId
    select new
    {
        PersonName = person.Name,
        StoreName = store.Name,
        NumItems = wishlist.Items.Count
    };

// Equivalent LINQ method syntax
var shoppingLists2 = people
    .Join(wishlists,
        person =&gt; person.Id,
        wishlist =&gt; wishlist.personId,
        (person, wishlist) =&gt; new { person, wishlist })
    .Join(stores,
        store =&gt; store.Id,
        something =&gt; something.wishlist.storeId,
        (obj, store) =&gt; new
        {
            PersonName = obj.person.Name,
            StoreName = store.Name,
            NumItems = obj.wishlist.Items.Count
        });

public static IEnumerable&lt;TResult&gt; Join&lt;TOuter,TInner,TKey,TResult&gt;(
    this IEnumerable&lt;TOuter&gt; outer,
    IEnumerable&lt;TInner&gt; inner,
    Func&lt;TOuter,TKey&gt; outerKeySelector,
    Func&lt;TInner,TKey&gt; innerKeySelector,
    Func&lt;TOuter,TInner,TResult&gt; resultSelector)</pre>

  <p>The issue is lines 19 and 20 above; they need to be switched.&#160; The compiler can’t properly infer the generic type parameters because we have our key selectors out of order in the argument list when invoking the <font face="Courier New">Join</font> method.&#160; If you wanted to be explicit about your generic type parameters assignments, then <font face="Courier New">Join&lt;TOuter, TInner, TKey, TResult&gt;</font> would be <font face="Courier New">Join&lt;Temp1, Store, int, Temp2&gt;</font>, where <font face="Courier New">Temp1</font> and <font face="Courier New">Temp2</font> represent the magical type definitions that the compiler creates underneath the covers when you use anonymous types in your C# code.&#160; Notice the <font face="Courier New">outerKeySelector</font> needs to come before the <font face="Courier New">innerKeySelector</font>.&#160; It appears the &quot;<font face="Courier New">on store.Id equals wishlist.storeId</font><font face="Arial">&quot; syntax is not a </font><a href="http://en.wikipedia.org/wiki/Commutativity">commutative operation</a>.</p>

  <p>One last thing, I just realized that the error(s) given in Visual Studio when you actually compile the code are different than the intellisense red squiggly error message.&#160; It appears an actual build of the code is able to be a little more omniscient than the quick compile that intellisense does as you type.&#160; The error (and intelligent suggestion) the compiler offers says something like this:</p>

  <blockquote>
    <p><font face="Courier New">The name &#8216;store&#8217; is not in scope on the left side of &#8216;equals&#8217;.&#160; Consider swapping the expressions on either side of &#8216;equals&#8217;.</font></p>
  </blockquote>

  <h3>Additional Info</h3>

  <p>While reading the <a href="http://msdn.microsoft.com/en-us/library/bb534675.aspx">MSDN article on the LINQ <font face="Courier New">Join</font> method</a>, I thought the &quot;<font face="Courier New">Remarks</font><font face="Arial">&quot;</font> section has some really great stuff about deferred execution, default equality comparison, differences from <font face="Courier New">SelectMany</font>, sort order perseverance, and so on:</p>

  <blockquote>
    <p>This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its <strong>GetEnumerator</strong> method directly or by using foreach in Visual C# or For Each in Visual Basic.</p>

    <p>The default equality comparer, <a href="http://msdn.microsoft.com/en-us/library/ms224763.aspx">Default</a>, is used to hash and compare keys.</p>

    <p>A join refers to the operation of correlating the elements of two sources of information based on a common key. <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.join.aspx">Join</a> brings the two information sources and the keys by which they are matched together in one method call. This differs from the use of <strong>SelectMany</strong>, which requires more than one method call to perform the same operation.</p>

    <p><a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.join.aspx">Join</a> preserves the order of the elements of outer, and for each of these elements, the order of the matching elements of inner.</p>

    <p>In query expression syntax, a join (Visual C#) or Join (Visual Basic) clause translates to an invocation of <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.join.aspx">Join</a>.</p>

    <p>In relational database terms, the <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.join.aspx">Join</a> method implements an inner equijoin. &#8216;Inner&#8217; means that only elements that have a match in the other sequence are included in the results. An &#8216;equijoin&#8217; is a join in which the keys are compared for equality. A left outer join operation has no dedicated standard query operator, but can be performed by using the <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.groupjoin.aspx">GroupJoin</a> method. See <a href="http://msdn.microsoft.com/en-us/library/bb397908.aspx">Join Operations</a>.</p>
  </blockquote>

  <p>Thanks, I hope this proves helpful to someone, as it was certainly eye-opening to me.</p>
</span></div>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Maybe Monad Extensions]]></title>
    <link href="http://mkmurray.com/blog/2010/09/30/maybe-monad-extensions/"/>
    <updated>2010-09-30T17:35:00-06:00</updated>
    <id>http://mkmurray.com/blog/2010/09/30/maybe-monad-extensions</id>
    <content type="html"><![CDATA[<div class='post'>
<p>I learned a lot from <a href="http://murrayon.net/2010/09/maybe-from-murray-monads.html" target="_blank">my last foray into implementing my own Maybe Monad</a>.&#160; Apparently, it got noticed by and was actually useful to <a href="http://www.lostechies.com/members/derick.bailey/default.aspx" target="_blank">Derick Bailey</a>, as it was one of the resources he used in <a href="http://www.lostechies.com/blogs/derickbailey/archive/2010/09/29/monads-in-c-which-part-is-the-monad.aspx" target="_blank">his own personal exploration into Monads</a>.&#160; Of course, Derick did the topic a bit more justice, as he has a propensity to do.</p>  <p>Nonetheless, I have done as I said I would and reworked my Murray Monads into a cleaner, more concise implementation using extension methods, much like the implementation I introduced from Dmitri Nesteruk in the last post.&#160; So without further ado, I’d like to introduce you to the MaybeMonadExtensions.</p> <span class="fullpost">   <h4>Monads 2.0 - <a href="http://www.youtube.com/watch?v=ll7rWiY5obI&amp;t=1m19s" target="_blank">“These Go To Eleven”</a></h4>    <p>If you want to get an introduction to what Monads are and how I got to where I am today with this little library, then you really should check out <a href="http://murrayon.net/2010/09/maybe-from-murray-monads.html" target="_blank">the previous post on this topic</a>.&#160; I will however give a few brief code samples to show you what it can do to tidy up all those null checks using the Maybe Monad.</p>    <p>Here is code we tend to write all the time:</p>    <pre class="brush: csharp">string postCode;
if (person != null)
{
  if (HasMedicalRecord(person) &amp;&amp; person.Address != null)
  {
    CheckAddress(person.Address);
    if (person.Address.PostCode != null)
      postCode = person.Address.PostCode.ToString();
    else
      postCode = &quot;UNKNOWN&quot;;
  }
}</pre>

  <p>It can look like this with some Maybe Monad love:</p>

  <pre class="brush: csharp">string postalCode = person.If(HasMedicalRecord)
  .Access(p =&gt; p.Address)
  .Apply(CheckAddress)
  .Access(a =&gt; a.PostCode)
  .Convert(pc =&gt; pc.ToString(), &quot;UNKNOWN&quot;);</pre>

  <p>I know!&#160; Groovy, huh?!</p>

  <p>The source can be found here:&#160; <a href="http://bitbucket.org/murrayondotnet/maybemonadextensions/">http://bitbucket.org/murrayondotnet/maybemonadextensions/</a></p>

  <p>Let me know if you put this to good use!</p>
</span>  </div>
<h2>Comments</h2>
<div class='comments'>
<div class='comment'>
<div class='author'>Omer Mor</div>
<div class='content'>
I see your point.<br />However, even Rx is sharing many LINQ operators with its IObservable &amp; IQbservable monads.<br />So we already have 4 different monads (IEnumerable, IQueryable, IObservable, IQbservable) using those operators. I don&#39;t think any more would hurt :-)</div>
</div>
<div class='comment'>
<div class='author'>Mike Murray</div>
<div class='content'>
Great question. I suppose I could have used those names and it would likely be a familiar vernacular for .NET developers. I guess my only hesitation would be that I wouldn&#39;t necessarily want to confuse others who read the code into thinking that they are LINQ extension methods. My first thought when I saw your code was that somehow person was an IQueryable or IEnumerable, just because of those familiar method names.<br /><br />Great point though, and it does make me second guess my chosen names a bit. I did like Derick&#39;s method names too (especially just plain old &quot;Get&quot;). Thanks for posting!</div>
</div>
<div class='comment'>
<div class='author'>Omer Mor</div>
<div class='content'>
Nice.<br /><br />Why didn&#39;t you choose the Linq terminology here?<br />I&#39;d write your example as this (Linq + Rx&#39;s Do operator):<br /><br /><br />string postalCode = person.Where(HasMedicalRecord)<br />  .Select(p =&gt; p.Address)<br />  .Do(CheckAddress)<br />  .Select(a =&gt; a.PostCode)<br />  .Select(pc =&gt; pc.ToString(), &quot;UNKNOWN&quot;);</div>
</div>
</div>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Maybe from Murray Monads]]></title>
    <link href="http://mkmurray.com/blog/2010/09/21/maybe-from-murray-monads/"/>
    <updated>2010-09-21T18:33:00-06:00</updated>
    <id>http://mkmurray.com/blog/2010/09/21/maybe-from-murray-monads</id>
    <content type="html"><![CDATA[<div class='post'>
<p>Off and on for the last six months, I have probably seen and read at least a half dozen introductions and tutorials on <a href="http://en.wikipedia.org/wiki/Monad_(functional_programming)">monads</a>, a functional programming construct based on the mathematical monads from category theory.&#160; Monads are known for their headache-inducing explanations, and I’ve had my fair share.&#160; Every tutorial I’ve committed time to mentions the endless possibilities of using such constructs to improve your code, but I’ve had a hard time finding real-world examples of using this stuff out in the wild (<a href="http://stackoverflow.com/questions/866912/what-is-the-compelling-scenario-for-using-monads-in-c">much like this Stack Overflow poster</a>, whose link I only found just now).&#160; It has recently become a quest of mine to find some C# code we all write that could be improved by a monad.</p>  <p>I am now going to attempt to introduce a Maybe monad that I cooked up, but I warn you that I have no idea what I’m doing or if I’m staying within the rules for what makes a monad by definition a monad.&#160; Don’t worry though, you have nothing to lose; I’m the only one taking a risk at looking foolish, and it’s all at the expense of my reputation and not yours.&#160; Should be fun!</p> <span class="fullpost">   <h3>“It is not the spoon that bends, it is only yourself”</h3>    <p>From the <a href="http://en.wikipedia.org/wiki/Monad_(functional_programming)">Wikipedia article linked to above</a>:</p>    <blockquote>     <p>“In functional programming, a monad is a kind of abstract data type constructor used to represent computations (instead of data in the domain model). Monads allow the programmer to chain actions together to build a pipeline, in which each action is decorated with additional processing rules provided by the monad. Programs written in functional style can make use of monads to structure procedures that include sequenced operations, or to define arbitrary control flows (like handling concurrency, continuations, or exceptions).</p>      <p>…</p>      <p>“A programmer will compose monadic functions to define a data-processing pipeline. The monad acts as a framework, as it&#8217;s a reusable behavior that decides the order in which the specific monadic functions in the pipeline are called, and manages all the undercover work required by the computation.”</p>   </blockquote>    <p>The promised tenets of monads are increased code readability and algorithm composability, an example of preferring declarative code over imperative, procedural code.&#160; In the case of the Maybe monad, it is a wrapper around types that might have an invalid state like <font face="Courier New">null</font> or <font face="Courier New">nothing</font>.&#160; The lure of the Maybe monad is the ability to deal with values that might be in this invalid state without having to explicitly check for null before continuing or exceptions being thrown in your algorithms.</p>    <p>I first found <a href="http://abdullin.com/journal/2009/10/6/zen-development-practices-c-maybe-monad.html">a post by Rinat Abdullin</a> where he introduced his version of a C# Maybe monad.&#160; I downloaded the library and attempted to figure out how to use it in code I could possibly write any given day.&#160; I tried mimicking the <font face="Courier New">HttpContext.Request.Params</font> collection commonly used in ASP.NET pages and HTTP handlers to retrieve the passed in query string or post values on the <font face="Courier New">Request</font> object.&#160; If you ask that collection for a parameter that was not passed in on the request, it returns a null instead of the string value.&#160; Common practice is to then use a bunch of <font face="Courier New">if</font> statements and key off the fact that certain query string or post parameters may or may not exist.</p>    <p>The problem I ran into with Rinat’s implemenation is that I wrote the code using the monad how I thought it should help me, and then ran into compiler errors and runtime exceptions because of the expectation that Maybe objects couldn’t be constructed around null values.&#160; Here is the twitter conversation I had with Rinat in regard to this misconception that I had:</p>   <span style="widows: 2; text-transform: none; text-indent: 0px; border-collapse: separate; font: medium &#39;Times New Roman&#39;; white-space: normal; orphans: 2; letter-spacing: normal; color: rgb(0,0,0); word-spacing: 0px; -webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px" class="Apple-style-span"><span style="font-family: verdana, tahoma, arial, &#39;Trebuchet MS&#39;, sans-serif, georgia, courier, &#39;Times New Roman&#39;, serif; color: rgb(0,58,126); font-size: 12px; font-weight: bold" class="Apple-style-span">       <div style="padding-bottom: 15px; background-color: rgb(234,242,249); margin: 0px; padding-left: 15px; width: 550px; padding-right: 15px; padding-top: 15px; background-origin: initial; background-clip: initial" class="post1">         <div style="padding-bottom: 0px; margin: 0px 15px 0px 0px; padding-left: 0px; width: 80px; padding-right: 0px; display: block; float: left; height: 80px; padding-top: 0px" class="avatar"><a style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; color: rgb(0,58,126); text-decoration: none; padding-top: 0px" title="View murrayondotnet&#39;s Twitter Page" href="http://www.twitter.com/murrayondotnet" target="_blank"><img style="border-bottom: rgb(204,204,204) 1px solid; border-left: rgb(204,204,204) 1px solid; padding-bottom: 3px; margin: 0px; padding-left: 3px; padding-right: 3px; border-top: rgb(204,204,204) 1px solid; border-right: rgb(204,204,204) 1px solid; padding-top: 3px" alt="murrayondotnet&#39;s avatar" src="http://a1.twimg.com/profile_images/547516901/profilepic_bigger.PNG" width="73" height="73" /></a></div>          <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; float: left; padding-top: 0px" class="post">           <h5 style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; font: bold 16px verdana, tahoma, arial, &#39;Trebuchet MS&#39;, sans-serif, georgia, courier, &#39;Times New Roman&#39;, serif; color: rgb(98,98,98); padding-top: 0px"><a style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; color: rgb(0,58,126); text-decoration: none; padding-top: 0px" title="View murrayondotnet&#39;s Twitter Page" href="http://www.twitter.com/murrayondotnet" target="_blank">murrayondotnet</a><span class="Apple-converted-space">&#160;</span>says:</h5>            <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; width: 450px; padding-right: 0px; font: 14px/19px tahoma, arial; color: rgb(98,98,98); padding-top: 0px" class="mainpost">@abdullin Can you make your MaybeMonad in Lokad lib accept null at construct or explicit/implicit cast? Maybe&lt;SomeType&gt; monad = varThatsNull</div>         </div>          <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; clear: both; padding-top: 0px" class="clear"></div>       </div>        <div style="padding-bottom: 15px; background-color: rgb(255,255,255); margin: 0px; padding-left: 15px; width: 550px; padding-right: 15px; padding-top: 15px; background-origin: initial; background-clip: initial" class="post2">         <div style="padding-bottom: 0px; margin: 0px 15px 0px 0px; padding-left: 0px; width: 80px; padding-right: 0px; display: block; float: left; height: 80px; padding-top: 0px" class="avatar"><a style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; color: rgb(0,58,126); text-decoration: none; padding-top: 0px" title="View abdullin&#39;s Twitter Page" href="http://www.twitter.com/abdullin" target="_blank"><img style="border-bottom: rgb(204,204,204) 1px solid; border-left: rgb(204,204,204) 1px solid; padding-bottom: 3px; margin: 0px; padding-left: 3px; padding-right: 3px; border-top: rgb(204,204,204) 1px solid; border-right: rgb(204,204,204) 1px solid; padding-top: 3px" alt="abdullin&#39;s avatar" src="http://a3.twimg.com/profile_images/755788123/0_1f297_e07be068_orig_bigger.jpg" width="73" height="73" /></a></div>          <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; float: left; padding-top: 0px" class="post">           <h5 style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; font: bold 16px verdana, tahoma, arial, &#39;Trebuchet MS&#39;, sans-serif, georgia, courier, &#39;Times New Roman&#39;, serif; color: rgb(98,98,98); padding-top: 0px"><a style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; color: rgb(0,58,126); text-decoration: none; padding-top: 0px" title="View abdullin&#39;s Twitter Page" href="http://www.twitter.com/abdullin" target="_blank">abdullin</a><span class="Apple-converted-space">&#160;</span>says:</h5>            <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; width: 450px; padding-right: 0px; font: 14px/19px tahoma, arial; color: rgb(98,98,98); padding-top: 0px" class="mainpost">@murrayondotnet No, this would violate the idea of MaybeMonad (as in Lokad libs). But you can copy code and tweak it to your needs locally.</div>         </div>          <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; clear: both; padding-top: 0px" class="clear"></div>       </div>        <div style="padding-bottom: 15px; background-color: rgb(234,242,249); margin: 0px; padding-left: 15px; width: 550px; padding-right: 15px; padding-top: 15px; background-origin: initial; background-clip: initial" class="post1">         <div style="padding-bottom: 0px; margin: 0px 15px 0px 0px; padding-left: 0px; width: 80px; padding-right: 0px; display: block; float: left; height: 80px; padding-top: 0px" class="avatar"><a style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; color: rgb(0,58,126); text-decoration: none; padding-top: 0px" title="View murrayondotnet&#39;s Twitter Page" href="http://www.twitter.com/murrayondotnet" target="_blank"><img style="border-bottom: rgb(204,204,204) 1px solid; border-left: rgb(204,204,204) 1px solid; padding-bottom: 3px; margin: 0px; padding-left: 3px; padding-right: 3px; border-top: rgb(204,204,204) 1px solid; border-right: rgb(204,204,204) 1px solid; padding-top: 3px" alt="murrayondotnet&#39;s avatar" src="http://a1.twimg.com/profile_images/547516901/profilepic_bigger.PNG" width="73" height="73" /></a></div>          <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; float: left; padding-top: 0px" class="post">           <h5 style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; font: bold 16px verdana, tahoma, arial, &#39;Trebuchet MS&#39;, sans-serif, georgia, courier, &#39;Times New Roman&#39;, serif; color: rgb(98,98,98); padding-top: 0px"><a style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; color: rgb(0,58,126); text-decoration: none; padding-top: 0px" title="View murrayondotnet&#39;s Twitter Page" href="http://www.twitter.com/murrayondotnet" target="_blank">murrayondotnet</a><span class="Apple-converted-space">&#160;</span>says:</h5>            <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; width: 450px; padding-right: 0px; font: 14px/19px tahoma, arial; color: rgb(98,98,98); padding-top: 0px" class="mainpost">@abdullin Figured this was case; what does it violate? I&#8217;m still new to monads. Thought one would be able construct monad around maybe null</div>         </div>          <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; clear: both; padding-top: 0px" class="clear"></div>       </div>        <div style="padding-bottom: 15px; background-color: rgb(255,255,255); margin: 0px; padding-left: 15px; width: 550px; padding-right: 15px; padding-top: 15px; background-origin: initial; background-clip: initial" class="post2">         <div style="padding-bottom: 0px; margin: 0px 15px 0px 0px; padding-left: 0px; width: 80px; padding-right: 0px; display: block; float: left; height: 80px; padding-top: 0px" class="avatar"><a style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; color: rgb(0,58,126); text-decoration: none; padding-top: 0px" title="View abdullin&#39;s Twitter Page" href="http://www.twitter.com/abdullin" target="_blank"><img style="border-bottom: rgb(204,204,204) 1px solid; border-left: rgb(204,204,204) 1px solid; padding-bottom: 3px; margin: 0px; padding-left: 3px; padding-right: 3px; border-top: rgb(204,204,204) 1px solid; border-right: rgb(204,204,204) 1px solid; padding-top: 3px" alt="abdullin&#39;s avatar" src="http://a3.twimg.com/profile_images/755788123/0_1f297_e07be068_orig_bigger.jpg" width="73" height="73" /></a></div>          <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; float: left; padding-top: 0px" class="post">           <h5 style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; font: bold 16px verdana, tahoma, arial, &#39;Trebuchet MS&#39;, sans-serif, georgia, courier, &#39;Times New Roman&#39;, serif; color: rgb(98,98,98); padding-top: 0px"><a style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; color: rgb(0,58,126); text-decoration: none; padding-top: 0px" title="View abdullin&#39;s Twitter Page" href="http://www.twitter.com/abdullin" target="_blank">abdullin</a><span class="Apple-converted-space">&#160;</span>says:</h5>            <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; width: 450px; padding-right: 0px; font: 14px/19px tahoma, arial; color: rgb(98,98,98); padding-top: 0px" class="mainpost">@murrayondotnet check out the article on Maybe monads in Lokad libs: http://bit.ly/1GJlNN</div>         </div>          <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; clear: both; padding-top: 0px" class="clear"></div>       </div>        <div style="padding-bottom: 15px; background-color: rgb(234,242,249); margin: 0px; padding-left: 15px; width: 550px; padding-right: 15px; padding-top: 15px; background-origin: initial; background-clip: initial" class="post1">         <div style="padding-bottom: 0px; margin: 0px 15px 0px 0px; padding-left: 0px; width: 80px; padding-right: 0px; display: block; float: left; height: 80px; padding-top: 0px" class="avatar"><a style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; color: rgb(0,58,126); text-decoration: none; padding-top: 0px" title="View murrayondotnet&#39;s Twitter Page" href="http://www.twitter.com/murrayondotnet" target="_blank"><img style="border-bottom: rgb(204,204,204) 1px solid; border-left: rgb(204,204,204) 1px solid; padding-bottom: 3px; margin: 0px; padding-left: 3px; padding-right: 3px; border-top: rgb(204,204,204) 1px solid; border-right: rgb(204,204,204) 1px solid; padding-top: 3px" alt="murrayondotnet&#39;s avatar" src="http://a1.twimg.com/profile_images/547516901/profilepic_bigger.PNG" width="73" height="73" /></a></div>          <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; float: left; padding-top: 0px" class="post">           <h5 style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; font: bold 16px verdana, tahoma, arial, &#39;Trebuchet MS&#39;, sans-serif, georgia, courier, &#39;Times New Roman&#39;, serif; color: rgb(98,98,98); padding-top: 0px"><a style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; color: rgb(0,58,126); text-decoration: none; padding-top: 0px" title="View murrayondotnet&#39;s Twitter Page" href="http://www.twitter.com/murrayondotnet" target="_blank">murrayondotnet</a><span class="Apple-converted-space">&#160;</span>says:</h5>            <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; width: 450px; padding-right: 0px; font: 14px/19px tahoma, arial; color: rgb(98,98,98); padding-top: 0px" class="mainpost">@abdullin Thanks for the link, thats actually how I found your lib. I didnt see where you say why cant construct maybe monad on null. Help?</div>         </div>          <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; clear: both; padding-top: 0px" class="clear"></div>       </div>        <div style="padding-bottom: 15px; background-color: rgb(255,255,255); margin: 0px; padding-left: 15px; width: 550px; padding-right: 15px; padding-top: 15px; background-origin: initial; background-clip: initial" class="post2">         <div style="padding-bottom: 0px; margin: 0px 15px 0px 0px; padding-left: 0px; width: 80px; padding-right: 0px; display: block; float: left; height: 80px; padding-top: 0px" class="avatar"><a style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; color: rgb(0,58,126); text-decoration: none; padding-top: 0px" title="View abdullin&#39;s Twitter Page" href="http://www.twitter.com/abdullin" target="_blank"><img style="border-bottom: rgb(204,204,204) 1px solid; border-left: rgb(204,204,204) 1px solid; padding-bottom: 3px; margin: 0px; padding-left: 3px; padding-right: 3px; border-top: rgb(204,204,204) 1px solid; border-right: rgb(204,204,204) 1px solid; padding-top: 3px" alt="abdullin&#39;s avatar" src="http://a3.twimg.com/profile_images/755788123/0_1f297_e07be068_orig_bigger.jpg" width="73" height="73" /></a></div>          <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; float: left; padding-top: 0px" class="post">           <h5 style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; font: bold 16px verdana, tahoma, arial, &#39;Trebuchet MS&#39;, sans-serif, georgia, courier, &#39;Times New Roman&#39;, serif; color: rgb(98,98,98); padding-top: 0px"><a style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; color: rgb(0,58,126); text-decoration: none; padding-top: 0px" title="View abdullin&#39;s Twitter Page" href="http://www.twitter.com/abdullin" target="_blank">abdullin</a><span class="Apple-converted-space">&#160;</span>says:</h5>            <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; width: 450px; padding-right: 0px; font: 14px/19px tahoma, arial; color: rgb(98,98,98); padding-top: 0px" class="mainpost">@murrayondotnet in essence monad in Lokad guarantees: there will be no nulls around (hence no need to check for them), it replaces null.</div>         </div>          <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; clear: both; padding-top: 0px" class="clear"></div>       </div>        <div style="padding-bottom: 15px; background-color: rgb(234,242,249); margin: 0px; padding-left: 15px; width: 550px; padding-right: 15px; padding-top: 15px; background-origin: initial; background-clip: initial" class="post1">         <div style="padding-bottom: 0px; margin: 0px 15px 0px 0px; padding-left: 0px; width: 80px; padding-right: 0px; display: block; float: left; height: 80px; padding-top: 0px" class="avatar"><a style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; color: rgb(0,58,126); text-decoration: none; padding-top: 0px" title="View murrayondotnet&#39;s Twitter Page" href="http://www.twitter.com/murrayondotnet" target="_blank"><img style="border-bottom: rgb(204,204,204) 1px solid; border-left: rgb(204,204,204) 1px solid; padding-bottom: 3px; margin: 0px; padding-left: 3px; padding-right: 3px; border-top: rgb(204,204,204) 1px solid; border-right: rgb(204,204,204) 1px solid; padding-top: 3px" alt="murrayondotnet&#39;s avatar" src="http://a1.twimg.com/profile_images/547516901/profilepic_bigger.PNG" width="73" height="73" /></a></div>          <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; float: left; padding-top: 0px" class="post">           <h5 style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; font: bold 16px verdana, tahoma, arial, &#39;Trebuchet MS&#39;, sans-serif, georgia, courier, &#39;Times New Roman&#39;, serif; color: rgb(98,98,98); padding-top: 0px"><a style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; color: rgb(0,58,126); text-decoration: none; padding-top: 0px" title="View murrayondotnet&#39;s Twitter Page" href="http://www.twitter.com/murrayondotnet" target="_blank">murrayondotnet</a><span class="Apple-converted-space">&#160;</span>says:</h5>            <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; width: 450px; padding-right: 0px; font: 14px/19px tahoma, arial; color: rgb(98,98,98); padding-top: 0px" class="mainpost">@abdullin I may try to create my own implementation that hides whether null or not. If so probably base mine off of the nice things in yours</div>         </div>          <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; clear: both; padding-top: 0px" class="clear"></div>       </div>     </span></span>    <p>And so I did.</p>    <h3>Introducing MurrayMonads</h3>    <p>I don’t even like the name.&#160; I’m also not sure this code will ever be used again…by anyone, let alone me (especially since I like some other guy’s implementation better; read on to watch me embarrass myself).&#160; But whatever, Visual Studio asks for a project/solution name and so there it is.&#160; I need some cool theme like Rhino, as used by <a href="http://ayende.com/blog/default.aspx">Ayende</a>.</p>    <p>Speaking of Oren (I will use his proper name instead so that he doesn’t <a href="http://ayende.com/Blog/archive/2010/08/13/how-to-pay-3-times-for-the-same-flight-ticket.aspx">get stuck at the airport unable to board his flight</a>), he posted a link on Twitter to <a href="http://devtalk.net/csharp/chained-null-checks-and-the-maybe-monad/">an article where Dmitri Nesteruk created his own version of the Maybe monad</a>, just as I was starting my experiment.&#160; He used extension methods instead of an explicit monad object wrapper in order to enable the pipelining composability that you can also do with Rinat’s implementation.&#160; Really clever, but there was one small thing that bothered me a bit, and that is how the monad chaining begins with Dmitri’s API.&#160; (Actually, I’ll prove I’m wrong by the end of the post; this is the cause of upcoming embarrassment mentioned above, hooray!)&#160; Because of this, I decided to use his example problem as the basis for my sample that I will show, in order to increase comparability.</p>    <p>So I set off to try and merge the good points of both Rinat’s and Dmitri’s implementations.&#160; I have put my source code up for viewing at Bitbucket.org:&#160; <a href="http://bitbucket.org/murrayondotnet/murraymonads">http://bitbucket.org/murrayondotnet/murraymonads</a></p>    <h3>Are We There Yet?!</h3>    <p>Yes, we are.&#160; Let’s see some code finally.</p>    <p>Here is the code we don’t like writing all the time:</p>    <pre class="brush: csharp">string postCode;
if (person != null)
{
  if (HasMedicalRecord(person) &amp;&amp; person.Address != null)
  {
    CheckAddress(person.Address);
    if (person.Address.PostCode != null)
      postCode = person.Address.PostCode.ToString();
    else
      postCode = &quot;UNKNOWN&quot;;
  }
}</pre>

  <p>This is actually code that you wrote; I took it just yesterday from your current project at work.&#160; I know you’re feeling a bit defensive because of this, but I’m here to help so put down the attitude please.&#160; We’re gonna make your life easier…I hope…</p>

  <p>All in all, it’s code you see every day and there’s not much really wrong with it per se.&#160; I just think it could be cleaner I suppose.&#160; So using Dmitri’s extension methods, you can get that logic down to this:</p>

  <pre class="brush: csharp">string postCode = this.With(x =&gt; person)
  .If(x =&gt; HasMedicalRecord(x))
  .With(x =&gt; x.Address)
  .Do(x =&gt; CheckAddress(x))
  .With(x =&gt; x.PostCode)
  .Return(x =&gt; x.ToString(), &quot;UNKNOWN&quot;);</pre>

  <p>As long as that last <font face="Courier New">ToString</font> method call doesn’t return a null (which one of my use cases does in the <font face="Courier New">TestConsoleApp</font> included in my source code), you will either get the value or <font face="Courier New">“UNKNOWN”</font>.&#160; Looking good!</p>

  <p>So my version of the Maybe monad comes out pretty close to this last one:</p>

  <pre class="brush: csharp">string postCode = person.If(p =&gt; HasMedicalRecord(p))
  .Access(p =&gt; p.Address)
  .Apply(a =&gt; CheckAddress(a))
  .Access(a =&gt; a.PostCode)
  .Convert(pc =&gt; pc.ToString(), &quot;UNKNOWN&quot;);

// or even
string postalCode = person.If(HasMedicalRecord)
  .Access(p =&gt; p.Address)
  .Apply(CheckAddress)
  .Access(a =&gt; a.PostCode)
  .Convert(pc =&gt; pc.ToString(), &quot;UNKNOWN&quot;);</pre>

  <p>The difference between Dmitri’s and mine being how the chain is first started, on the Maybe <font face="Courier New">person</font> object instead of Dmitri’s use of the <font face="Courier New">this</font> keyword.</p>

  <p>Here’s what you’ve been really waiting for where I eat my own words.&#160; Dmitri’s code can also be written like this:</p>

  <pre class="brush: csharp">string postCode = person.If(HasMedicalRecord)
  .With(x =&gt; x.Address)
  .Do(CheckAddress)
  .With(x =&gt; x.PostCode)
  .Return(x =&gt; x.ToString(), &quot;UNKNOWN&quot;);</pre>

  <p>…which appears to take away any advantage of my library.&#160; I officially like his solution better, I just don’t like some of the method names.&#160; So perhaps <a href="http://murrayon.net/2010/09/maybe-monad-extensions.html" target="_blank">I will create another blog post</a> and <a href="http://bitbucket.org/murrayondotnet/maybemonadextensions/" target="_blank">Bitbucket repo with a new library of extension methods</a> instead.&#160; I will leave up this mess-of-a-post public (as well as the source code) so that perhaps others can see the process I went through and learn from my mistakes.</p>

  <h3>Your Turn to Criticize Now</h3>

  <p>Let me have it.&#160; Let me know how crazy I am or if this is even useful.&#160; Let me know if I’m completely misusing the monad principles.&#160; Or, by some weird miracle, let me know if I’m on to something.&#160; Actually, if Dmitri is on to something.&#160; Either way, I want to hear from you.&#160; Thanks.</p>

  <h3>Additional Monad Learning Resources</h3>

  <ul>
    <li><a href="http://blogs.msdn.com/b/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx">http://blogs.msdn.com/b/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx</a> </li>

    <li><a href="http://www.infoq.com/presentations/Demystifying-Monads">http://www.infoq.com/presentations/Demystifying-Monads</a> </li>

    <li><a href="http://importantshock.wordpress.com/2009/01/18/jquery-is-a-monad/">http://importantshock.wordpress.com/2009/01/18/jquery-is-a-monad/</a> </li>

    <li>Also, LINQ is based on monadic principles. </li>
  </ul>
</span>  </div>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[F# Pipeline Operator in C#?]]></title>
    <link href="http://mkmurray.com/blog/2010/09/06/f-pipeline-operator-in-c/"/>
    <updated>2010-09-06T20:22:00-06:00</updated>
    <id>http://mkmurray.com/blog/2010/09/06/f-pipeline-operator-in-c</id>
    <content type="html"><![CDATA[<div class='post'>
<p>I am currently reading the <a href="http://www.manning.com/petricek/" target="_blank">Real-World Functional Programming</a> book from <a href="http://www.manning.com/" target="_blank">Manning Publications</a>. It’s mostly an exercise in learning F#, but also to improve my C# code as well. I finally learned what the F# pipelining operator (<font face="Courier New">|&gt;</font>) is all about, and I was so impressed I thought I would try to figure out how to bring it into C# if possible.</p> <span class="fullpost">   <h3>Introducing the F# Pipeline Operator</h3>    <p>Here is some F# code that defines a list of integers and a pair of functions.&#160; They are then used in a few “higher-order” functions (functions that utilize other functions as parameters or return values, according to my book).&#160; <font face="courier new">List.filter</font> is equivalent to the LINQ <font face="Courier New">IEnumerable.Where()</font> extension method, and <font face="Courier New">List.map</font> is equivalent to <font face="Courier New">IEnumerable.Select()</font>.</p>    <pre class="brush: csharp">let numbers = [ 1 .. 10 ]
let isOdd(n) = n % 2 = 1
let square(n) = n * n

List.filter isOdd numbers
List.map square (List.filter isOdd numbers)</pre>

  <p>The interesting part is the last line of code, where it is argued that you lose a little bit of code readability because the function that is actually executed first (<font face="Courier New">List.filter</font>) is found second in the expression statement.&#160; Enter the F# pipelining operator:</p>

  <pre class="brush: csharp">let squared =
  numbers
  |&gt; List.filter isOdd
  |&gt; List.map square</pre>

  <p>Even though we’re no longer a compact, one-liner expression, I think we’ve gained some code readability.&#160; It says to take the list <font face="Courier New">numbers</font> and perform the following manipulations in the exact order listed.&#160; Cool stuff, if I say so myself.</p>

  <h3>“There is No Charge for Awesomeness…or Attractiveness”</h3>

  <p>(Sorry, I’ve been watching the movie <a href="http://www.imdb.com/title/tt0441773/" target="_blank">Kung Fu Panda</a> a lot with my kids lately.&#160; Funny stuff.)&#160; So can this awesomeness be brought over into C#?&#160; I opened up Visual Studio and tried to see if I could figure out how to define my own operator or reuse one of the existing ones.</p>

  <p>I realize C# is a pretty tough language to flip keywords and operators around and invent new syntax with (ok, it’s impossible), but I tried anyway.&#160; The type of code readability issue I wanted to remedy is the same as with the F# code snippet above.&#160; I thought it would be nice to make C# code like the following statement more readable and digestible (especially the execution order):</p>

  <pre class="brush: csharp">Convert.ToInt32(Context.Request[“requestParam”].Trim());</pre>

  <p>As I started to (unsuccessfully) beat out some pretty rough code, I ran into problems with trying to make extension methods that are operator definition overloads and errors saying “<font face="Courier New">One of the parameters of a binary operator must be the containing type.</font>”&#160; It just wasn’t working and then I began to realize that C# already has a pipelining syntax, even if only in one small subset of the .NET API.&#160; You can find a decent pipelining syntax with the <a href="http://en.wikipedia.org/wiki/Fluent_interface" target="_blank">Fluent Interface</a> used for the LINQ extension methods.&#160; Its power is in the fact that the functions return the object type that was passed in and acted upon, so that more functions can be chained on afterward in a composable manner.&#160; The ability to do things like <font face="Courier New">collection.Where().Select().OrderBy()</font> is a much more declarative and functional solution to imperative <font face="Courier New">for</font> loops (and it makes it more readable and intention revealing in my opinion).&#160; It’s a difference in describing more <u><em>what</em></u> you want to be accomplished rather than <em><u>how</u></em> it is to be accomplished (especially when the <u><em>how</em></u> in programming languages is more readable to a computer than it is a human).</p>

  <p>So the good news is that you indeed can have a nice pipelining syntax in C#, especially for APIs that are designed with Fluent Interfaces like LINQ.&#160; However, it doesn’t solve code readability issues with code snippets like the C# fragment I showed above.&#160; For those regular, non-fluent method calls in the rest of the .NET API, you must use old-fashioned Object-Oriented Programming practices of breaking code up into meaningful, atomic units of statements and naming and encapsulating functions cohesively in order to get more readable code.</p>
</span>  </div>
<h2>Comments</h2>
<div class='comments'>
<div class='comment'>
<div class='author'>Jonas Elfström</div>
<div class='content'>
This looks a whole lot like the Thrush Combinator.<br /><a href="http://alicebobandmallory.com/articles/2009/10/06/the-thrush-combinator-in-c" rel="nofollow">I implemented</a> that one in C# a while ago</div>
</div>
<div class='comment'>
<div class='author'>Richard Beauchamp</div>
<div class='content'>
This comment has been removed by the author.</div>
</div>
<div class='comment'>
<div class='author'>Mike Murray</div>
<div class='content'>
Funny you should mention the Maybe Monad, as I&#39;ve been looking into Monads off and on for several months trying to figure out how I could use them in everyday code.  I likely will be posting something on this in the somewhat near future.</div>
</div>
<div class='comment'>
<div class='author'>Anonymous</div>
<div class='content'>
Just a small hint from someone who uses something like this in productive code on a day-to-day basis:<br /><br />Take your time and extend the static methods a bit. It won&#39;t hurt to build something like a maybe-monad in there.<br /><br />You know - check if the input is null and return null if so.<br /><br />For this you need either:<br />- &quot;where U : class&quot;<br />- use Equals<br /><br />For the same reason I give somethink like a &quot;DefaultValue&quot; Funktion that checks the input for null and responses with the default-value if so, if not it will give the original value.</div>
</div>
<div class='comment'>
<div class='author'>Mike Murray</div>
<div class='content'>
Very intriguing! Man I wish I had thought about that.  I suppose I&#39;m still new to designing APIs that pass around Funcs.<br /><br />I was able to make the following code work with the type inference (and without having to specify the types to the Then method):<br /><br />var blah = &quot;576 &quot;<br />.Then(x =&gt; x.Trim())<br />.Then(x =&gt; Convert.ToInt32(x));<br /><br />Not too bad really.  A little too much C# syntax though, but I&#39;d argue it might be more readable than what we started with, the code everyone writes.  It appears my code snippet doesn&#39;t even need the second extension method.<br /><br />Thanks for sharing!</div>
</div>
<div class='comment'>
<div class='author'>Yusuf Motara</div>
<div class='content'>
You could try this:<br /><br />static class Extn {<br />    public static U Then&lt;T,U&gt;(this T o, Func&lt;T, U&gt; f) { return f(o); }<br />    public static U Then&lt;T, U&gt;(this T o, Func&lt;T, Func&lt;U&gt;&gt; fe) { return fe(o)(); }<br />}<br /><br />&#8230; which lets you write the more-readable:<br /><br />var blah = &quot;576  &quot;<br />   .Then&lt;string,string&gt;(x =&gt; x.Trim)<br />   .Then(Convert.ToInt32);<br /><br />Unfortunately, it seems that you need to make the generic parameters explicit; C#&#39;s type inference is nowhere near as good as F#&#39;s.</div>
</div>
</div>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Reactive Framework Finally Explained]]></title>
    <link href="http://mkmurray.com/blog/2010/07/14/reactive-framework-finally-explained/"/>
    <updated>2010-07-14T17:59:00-06:00</updated>
    <id>http://mkmurray.com/blog/2010/07/14/reactive-framework-finally-explained</id>
    <content type="html"><![CDATA[<div class='post'>
<p>I have been intrigued by the <a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx">Reactive Extensions for .NET (Rx Framework)</a> for quite a while now, especially the fundamental shift from a “push” data model as opposed to the “pull” model most familiar to us.&#160; I have thought to myself that this must be a game changer in how data and events are consumed in every-day software.&#160; I didn’t quite understand how it all works or how to use it from the few samples I had seen, but I knew if I gave myself a little time to really sit down and look at it, my life would be changed forever.</p>  <p>However, after reading some articles, watching some recorded presentations, and even <a href="http://live.visitmix.com/MIX10/Sessions/FTL01">attending a MIX ‘10 session in-person</a> on the Reactive Extensions, I felt increasingly lost and confused by what this framework could offer me.&#160; I wasn’t understanding some fundamental ideology of the framework and it was jading my learning experience when watching/reading sample code.&#160; Well, I think I have finally figured out what the mental roadblock was and will attempt to explain the framework here as I best as I understand it, in hopes that it can be of help to others not getting what the fuss is all about.&#160; I can sense that I’m not the only one who has been turned off by the unsuccessful attempts by Microsoft to explain this revolutionary framework to the average developer.&#160; Apparently those who had a hand in designing the framework are just so incredibly intelligent that they are having a hard time discerning that the common man is not immediately getting it.</p> <span class="fullpost">   <h3><font face="Courier New">IEnumerable&lt;T&gt;</font>, Meet <font face="Courier New">IObservable&lt;T&gt;</font></h3>    <p>Essentially what Microsoft did is create a <a href="http://en.wikipedia.org/wiki/Duality_(mathematics)">mathematical dual</a> of the <font face="Courier New">IEnumerable</font> and <font face="Courier New">IEnumerator</font> interfaces using <a href="http://en.wikipedia.org/wiki/Category_theory">Category Theory</a>, and named them <font face="Courier New">IObservable</font> and <font face="Courier New">IObserver</font> respectively.&#160; In its bare simplicity, this is done by merely reversing the direction of your arrows in your mathematical functions and compositions.&#160; The following images of a few slides from <a href="http://live.visitmix.com/MIX10/Sessions/FTL01">Erik Meijer’s MIX ‘10 Session</a> that were the best visual explanation I have seen:</p>    <p>Duality Example with De Morgan’s Laws</p>    <p><a href="http://lh6.ggpht.com/_rps657FzHZ0/TD5QDKjrqpI/AAAAAAAAADo/_LP_XWkDId4/s1600-h/rxSlide23.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="rxSlide2" border="0" alt="rxSlide2" src="http://lh5.ggpht.com/_rps657FzHZ0/TD5QDjfchiI/AAAAAAAAADs/etW1caiUFHA/rxSlide2_thumb1.png?imgmax=800" width="441" height="334" /></a></p>    <p>Creating a Dual of <font face="Courier New">IEnumerable</font></p>    <p><a href="http://lh4.ggpht.com/_rps657FzHZ0/TD5QD9tyhyI/AAAAAAAAADw/CG9FYEFDB4Y/s1600-h/rxSlide33.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="rxSlide3" border="0" alt="rxSlide3" src="http://lh4.ggpht.com/_rps657FzHZ0/TD5QEm7T9hI/AAAAAAAAAD0/t_pfOknuY3o/rxSlide3_thumb1.png?imgmax=800" width="441" height="334" /></a></p>    <p>Creating a Dual of <font face="Courier New">IEnumerator</font></p>    <p><a href="http://lh4.ggpht.com/_rps657FzHZ0/TD5QE7KuUwI/AAAAAAAAAD4/tpV314oMx5g/s1600-h/rxSlide43.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="rxSlide4" border="0" alt="rxSlide4" src="http://lh3.ggpht.com/_rps657FzHZ0/TD5QFZd3VjI/AAAAAAAAAD8/9jaGTsA76jQ/rxSlide4_thumb1.png?imgmax=800" width="441" height="333" /></a>&#160;</p>    <p>The reason the mathematical proof part is significant is because we can guarantee that LINQ syntax and operators will work on these new collection and data subscriber interfaces, just like they did with <font face="Courier New">IEnumerable</font> collections in LINQ-to-Objects.&#160; This new LINQ provider is commonly called “LINQ over Events.”</p>    <h3>Reacting to Data is Asynchronous</h3>    <p>This is actually where I think some of the confusion came in for me.&#160; Mostly what I didn’t understand is how you can write LINQ queries into pushed data (already sent and also yet to be sent), when essentially that task is indeterminate by nature.&#160; What I have figured out is that the LINQ syntax is not entirely for the data being pushed, but also used for molding the subscriptions themselves.&#160; What the LINQ syntax provides you is a way to compose, filter, project, aggregate, and throttle data and event subscriptions in a powerful, declarative way.</p>    <p>A common workflow seems to be to create one or more observable collections (and there are <a title="16 Ways to Create IObservables Without Implementing IObservable" href="http://weblogs.asp.net/sweinstein/archive/2010/01/10/16-ways-to-create-iobservables-without-implementing-iobservable.aspx">many ways to do so</a>) and then customize and compose a subscription based on the subscription(s) using LINQ syntax.&#160; All that’s left then is to set the subscription in motion, giving it some sort of callback or lambda expression to be called as data is asynchronously pushed in and processed.</p>    <p>Here is a very simple code example that illustrates this process quite plainly:</p>    <pre class="brush: csharp">using System;
using System.Linq;

namespace TestRX
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var oneNumberPerSecond = Observable.Interval(TimeSpan.FromSeconds(1));

            var numbersTimesTwo = from n in oneNumberPerSecond
                                  select n * 2;

            Console.WriteLine(&quot;Numbers * 2:&quot;);

            numbersTimesTwo.Subscribe(num =&gt;
            {
                Console.WriteLine(num);
            });

            Console.ReadKey();
        }
    }
}</pre>

  <p>It is interesting to watch the code run and think about what it’s actually doing.&#160; It sits on the <font face="Courier New">Console.ReadKey()</font> line while the observable collection is asynchronously pushing data to the lambda expression containing the <font face="Courier New">Console.WriteLine()</font> statement.</p>

  <p>It looks like the Reactive Framework is not just a better way to handle events and pushed data, but it also appears from what I’ve read that it could be used as a nicer API for sending off asynchronous process threads.</p>

  <h3>Additional Reading</h3>

  <p><a href="http://msdn.microsoft.com/en-us/devlabs/default.aspx">Microsoft DevLabs</a> has created the <a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx">Reactive Extensions for .NET</a> (and it’s associated languages), but it has also came up with the Reactive Extensions for Silverlight and JavaScript (<a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx">can be found on same webpage</a>).&#160; This proves very interesting as JavaScript (and Silverlight) tends to be quite event driven because of its close interactions to UI elements in HTML (or XAML).&#160; In fact, one of the most encouraging example use cases that I’ve heard was that of having some HTML text field that you wanted to auto-search as the user types, but not until the user pauses for a second; they can also hit Enter.&#160; What the Reactive Framework could provide you is a way to aggregate more than one event source (alphabetic and Enter key strokes and the timer) into a single event handler using clear, declarative framework statements.</p>

  <p>Here are other links I would recommend for additional examples and explanation:</p>

  <ul>
    <li><a href="http://rxwiki.wikidot.com/101samples">(not yet) 101 Rx Samples – Reactive Framework (Rx) Wiki</a> </li>

    <li><a href="http://www.codeproject.com/KB/Parallel_Programming/RxByExample.aspx">The Reactive Framework by Example – The Code Project</a> </li>

    <li><a href="http://live.visitmix.com/MIX10/Sessions/FTL01">Reactive Extensions for JavaScript – Erik Meijer’s MIX ‘10 Session</a> </li>

    <li><a href="http://www.virtualaltnet.com/Recordings/Show/99">Making the Most of the Reactive Extensions for .NET – Virtual Alt.NET recording with Scott Weinstein</a></li>

    <li><a href="http://channel9.msdn.com/shows/Going+Deep/Expert-to-Expert-Brian-Beckman-and-Erik-Meijer-Inside-the-NET-Reactive-Framework-Rx/">Channel 9 Video with Brian Beckman and Erik Meijer</a></li>
  </ul>

  <p>Enjoy!&#160; Let me know via comments if you start using it for something real cool and useful.</p>
</span>  </div>
<h2>Comments</h2>
<div class='comments'>
<div class='comment'>
<div class='author'>Michael</div>
<div class='content'>
Nice post on a complex topic.  You are indeed correct that there has been confusion around explaining the why and how of Reactive Extensions.  Thanks Mike.</div>
</div>
<div class='comment'>
<div class='author'>Paul</div>
<div class='content'>
Great post on getting started with Rx!  One of the things I&#39;ve been working on is a MVVM framework for Silverlight / WPF that uses the Reactive Extensions - I&#39;ve written about it quite a bit in my blog at http://blog.paulbetts.org/index.php/category/programming/reactive-extensions/ and the code is at github.com/xpaulbettsx/ReactiveXaml ; it&#39;s got some great examples of doing more than just handling events together, I&#39;d love to hear any feedback you&#39;ve got on the project</div>
</div>
</div>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Parallel.For Loops in .NET 4]]></title>
    <link href="http://mkmurray.com/blog/2010/06/12/parallel-for-loops-in-net-4/"/>
    <updated>2010-06-12T12:19:00-06:00</updated>
    <id>http://mkmurray.com/blog/2010/06/12/parallel-for-loops-in-net-4</id>
    <content type="html"><![CDATA[<div class='post'>
<p>I was having fun working on the <a href="http://toughestdeveloperpuzzleever.com/tdpe2/">Toughest Developer Puzzle Ever 2</a> when I came across a problem that asked for the coordinates into a grid of numbers of the upper left corner for a 4x4 sub-grid with a magic sum of 34, meaning all rows, columns, and the 2 diagonals all sum up to 34.&#160; Instead of trying to figure it out manually, I probably did what many programmers would do and wrote a quick and dirty program to accomplish the task for me.</p>  <p>I didn’t try to use any optimized search algorithm or anything, as I knew that the problem space was very small and specific and that computers are really fast.&#160; So I figured I would just write a brute-force iterate through every row and column type of an algorithm (in Big O notation being <font face="Courier New">O(mn)</font> or just <font face="Courier New">O(n<span style="font-size:xx-small; vertical-align:top;">2</span>)</font> if the original grid is square), knowing it would return in milliseconds.</p>  <p>I quickly realized that each iteration was not dependent any previous iteration for its calculations, so I decided it might be a good time to try out the new <font face="Courier New">Parallel.For</font> loops in the .NET 4 Framework that would multi-thread the iterations of the loops.&#160; Here’s the implementation I threw together:</p> <span class="fullpost">   <pre class="brush: csharp">using System;
using System.Linq;
using System.Threading.Tasks;

namespace Find34Grid
{
    public class Program
    {
        private static readonly int[][] Grid = new []
        {
            new [] {16,3,2,13,15,10,3,6,41,15,14,4,12,8,7,1,12},
            new [] {5,10,22,8,4,5,16,7,9,7,6,12,5,11,10,8,5},
            new [] {9,6,7,12,14,11,2,13,16,3,2,13,15,10,3,6,5},
            new [] {41,15,14,4,12,8,7,2,5,10,11,8,4,5,16,9,15},
            new [] {16,3,2,13,15,10,3,6,15,10,16,2,3,13,16,2,3},
            new [] {5,10,11,8,4,5,16,9,4,5,5,11,10,8,5,11,10},
            new [] {9,6,7,12,14,11,2,13,14,11,9,7,6,12,9,7,6},
            new [] {41,15,14,4,12,8,7,1,12,8,4,14,15,1,14,15,1},
            new [] {9,7,6,12,5,11,10,8,5,11,10,3,6,41,15,14,4},
            new [] {4,14,15,1,9,7,6,12,9,7,5,16,9,9,7,6,12},
            new [] {12,8,13,13,4,14,15,1,4,14,11,2,13,16,3,2,13}
        };

        private const int MagicSum = 34;

        public static void Main(string[] args)
        {
            Parallel.For(0, Grid.Length - 3, i =&gt;
            {
                Parallel.For(0, Grid[i].Length - 3, j =&gt;
                {
                    int[] sums = new []
                    {
                        Grid[i].Skip(j).Take(4).Sum(), // Row 1
                        Grid[i+1].Skip(j).Take(4).Sum(), // Row 2
                        Grid[i+2].Skip(j).Take(4).Sum(), // Row 3
                        Grid[i+3].Skip(j).Take(4).Sum(), // Row 4
                        new [] { Grid[i][j], Grid[i+1][j], Grid[i+2][j], Grid[i+3][j]}.Sum(), // Column 1
                        new [] { Grid[i][j+1], Grid[i+1][j+1], Grid[i+2][j+1], Grid[i+3][j+1]}.Sum(), // Column 2
                        new [] { Grid[i][j+2], Grid[i+1][j+2], Grid[i+2][j+2], Grid[i+3][j+2]}.Sum(), // Column 3
                        new [] { Grid[i][j+3], Grid[i+1][j+3], Grid[i+2][j+3], Grid[i+3][j+3]}.Sum(), // Column 4
                        new [] { Grid[i][j], Grid[i+1][j+1], Grid[i+2][j+2], Grid[i+3][j+3]}.Sum(), // Diagonal 1
                        new [] { Grid[i][j+3], Grid[i+1][j+2], Grid[i+2][j+1], Grid[i+3][j]}.Sum() // Diagonal 2
                    };

                    if (sums.All(x =&gt; x == MagicSum))
                    {
                        Console.WriteLine(&quot;y (row): {0}\nx (column): {1}&quot;, i, j);
                    }
                });
            });

            Console.ReadLine();
        }
    }
}</pre>
<p>Nothing special and certainly did the job.&#160; I didn’t really notice a performance improvement in anyway, but that was expected for such a small problem.&#160; I don’t really expect a whole lot of feedback on such straightforward code, but if there is a cleaner or more efficient way to utilize <font face="Courier New">Parallel.For</font> or <font face="Courier New">Parallel.ForEach</font>, please don’t hesitate to let me know via commenting to this post.&#160; Thanks!</p>
</span></div>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Anagram Code Kata Part 5 – Domain Objects Over Language Primitives]]></title>
    <link href="http://mkmurray.com/blog/2010/02/20/anagram-code-kata-part-5-domain-objects-over-language-primitives/"/>
    <updated>2010-02-20T17:55:00-07:00</updated>
    <id>http://mkmurray.com/blog/2010/02/20/anagram-code-kata-part-5-domain-objects-over-language-primitives</id>
    <content type="html"><![CDATA[<div class='post'>
<p>This post is part of a <a href="http://murrayon.net/2009/11/anagram-code-kata-bdd-mspec.html">series on coding Kata, BDD, MSpec, and SOLID principles</a>.&#160; Feel free to visit the above link which points to the introductory post, also containing an index of all posts in the series.</p>  <p>In this post, we will discuss some reasons why you might want to avoid using language primitives directly in place of domain objects.&#160; Specifically, I have been using <font face="Courier New">String</font> variables and objects to represent words up to this point.&#160; <a href="http://adotnetdude.blogspot.com/">Esteban</a> suggested I create a <font face="Courier New">Word</font> class for a few good reasons which I’ll layout for you.&#160; Out of sheer luck and good timing, <a href="http://codebetter.com/blogs/dru.sellers/default.aspx">Dru Sellers</a> of <a href="http://codebetter.com/">CodeBetter.com</a> also wrote on this subject shortly afterward and confirmed Esteban’s reasoning.</p> <span class="fullpost">   <h3>Use <font face="Courier New">String</font> Class or Create <font face="Courier New">Word</font> Domain Object?</h3>    <p>I mentioned in the previous post that Esteban had suggested creating a <font face="Courier New">Word</font> class instead of just passing around strings everywhere through my application.&#160; One good reason is that we don’t own the <font face="Courier New">String</font> class and so further modification to our string-based implementation is difficult because the logic is scattered throughout the application, instead of centralized under the responsibility and definition of one domain class.&#160; It is much more difficult to refactor the word-specific logic with its behaviors and attributes spread throughout the code.&#160; Even if your <font face="Courier New">Word</font> class doesn’t grow any more beyond a seemingly unnecessary wrapper of the <font face="Courier New">String</font> class, the code is more cohesive and ready for change should the need arise.</p>    <p>But more importantly, you designed the code thinking in a true object-oriented mindset.&#160; You have to keep in mind that the <font face="Courier New">String</font> class is someone else’s implementation, and is hardly ever sufficient in and of itself as a domain object within your solution.&#160; Think about it, the behaviors that a string object performs are so generic and multipurpose that you likely don’t need two-thirds of the class as defined (and there’s likely a few behaviors you really need that aren’t there).&#160; Of course nearly every application on earth makes use of the <font face="Courier New">String</font> class; but because of this fact, it has no meaning in and of itself within any given application.&#160; You would have to look at how the stings are actually used within the code in order to understand its unique application within the app’s context.&#160; Of course that task of research is much easier for everyone (including the original author of the code) if it’s all encapsulated within a dedicated domain object class.&#160; True object-orientation means describing in code form the properties, behaviors, and interactions/relationships of real world objects within your problem domain.</p>    <p>Esteban gave me a great example to illustrate these points.&#160; He said that you can always represent money as a decimal (and even when you use a domain object, it’s got to have a decimal language primitive underneath the covers).&#160; However, what happens when you need to attach metadata to the amount (like currency denomination), or if you need to change decimal precision?&#160; You would have to go through all of the code and make sure your use of decimal language primitives is modified uniformly in order to retain consistency.&#160; Also, mathematic operations involving money are hardly ever the same as their counterparts involving standard decimals, because currency deals with discrete values to a certain decimal precision.&#160; Typically when the behaviors and properties within our system begin to get complex, we are cognizant enough to create domain objects in order to bring it all under one class.&#160; We definitely don’t want to over-architect features and interactions before we need them, but I think there is power in this principle of abstracting away language primitives and instead encapsulating their use within domain objects located in just one place in your codebase.&#160; I believe it is one thing we can keep in mind to help guide us to better object-oriented thinking, and avoid language-oriented coding.</p>    <p>As mentioned above, Esteban’s thoughts were confirmed nearly verbatim by <a href="http://codebetter.com/blogs/dru.sellers/default.aspx">Dru Sellers</a> of <a href="http://codebetter.com/">CodeBetter.com</a> in his blog post that he wrote just a few days after I had the conversation with Esteban.&#160; A great coincidence no doubt, and worth a read; here’s the link:</p>    <p><a href="http://codebetter.com/blogs/dru.sellers/archive/2010/01/27/business-primitives-1-2.aspx">Business Primitives (1/2)</a>&#160;</p>    <h3><font face="Courier New">Word</font> Class Implementation</h3>    <p>So basically I created the following class implementation and then replaced string with a reference to this new class, <font face="Courier new">Word</font>:</p>    <pre class="brush: csharp">public class Word
{
    private string wordStr = string.Empty;

    public Word(string wordStr)
    {
        this.wordStr = wordStr;
    }

    public override string ToString()
    {
        return wordStr;
    }

    public override bool Equals(object obj)
    {
        return wordStr == ((Word)obj).ToString();
    }

    public override int GetHashCode()
    {
        return base.GetHashCode();
    }

    public int GetCanonicalHashCode()
    {
        char[] letters = wordStr.ToCharArray();
        Array.Sort&lt;char&gt;(letters);
        return new string(letters).GetHashCode();
    }
}</pre>

  <p>I have defined an overridden implementation for <font face="Courier New">Equals(object)</font> (so that the test assertions and other <font face="Courier New">IEnumerable.Contains()</font> queries work) and <font face="Courier New">GetHashCode()</font> (solely to satisfy a compiler warning).&#160; I also moved the <font face="Courier New">GetCanoncialHashCode()</font> method from <font face="Courier New">AnagramGrouper</font>, in order to better encapsulate it as a behavior a Word knows how to do innately.</p>

  <p>One other change I had to make was to convert strings into <font face="Courier New">Word</font> objects in our <font face="Courier New">NewlineFileParser</font>, which I accomplished by using an <font face="Courier New">IEnumberable.Select()</font> call as shown below:</p>

  <pre class="brush: csharp">return File.ReadAllLines(filePath).Select&lt;string, Word&gt;(x =&gt; new Word(x));</pre>

  <p></p>

  <h3>Let’s Revisit <font face="Courier New">AssertWasCalled</font> One More Time</h3>

  <p>Trust me, I am groaning with you, even as I wrote that heading text.&#160; The last thing we need is for me to rehash the topic again and flip flop my stance yet another time.&#160; Yes, that’s right I’ve changed my mind again.&#160; First I couldn’t understand what utility asserting methods were called would have under normal test scenarios.&#160; Then I changed my mind that perhaps using it would help my test specifications have clearer intent of what I am asserting.&#160; After an email conversation with <a href="http://www.davesquared.net/">David Tchepak</a>, I think I’m now back to my original stance.&#160; Here is what Dave said that had me reconsidering, and I think it’s pretty sound reasoning (emphasis added by me):</p>

  <blockquote>
    <p>…</p>

    <p>“But seeing as you asked for it, here goes. :)</p>

    <p>“I try and avoid <font face="Courier New">AssertWasCalled</font> like the plague. Generally I don&#8217;t care that some method was called, I care that my class does the work it needs to. If that involves calling a dependency then great, but that is not my class&#8217; reason for existence.</p>

    <p>“I prefer your original approach of stubbing out everything in the setup and having that tested indirectly. One reason I prefer this is I find it makes it easier to refactor: the assertions in my test don&#8217;t change, the class still does the same thing. However I can add or change dependencies by changing some wiring in the setup, and then make sure I haven&#8217;t stuffed anything up as my assertions still pass. <strong>I prefer that my tests specify what I want, not how it does it.</strong> To me, <font face="Courier New">AssertWasCalled</font> reeks of over-specification. The one exception is where I hit the external boundaries of my code, so where I want to send an email or something without side effects that I can test. Then the core of the behaviour is the call itself, so I&#8217;m happy to assert on that then.”</p>
  </blockquote>

  <p>And with that I’ll promise to never bring this up again…unless of course I get swayed by someone else. :)&#160; In all seriousness, I think this is an interesting discussion and so if you have insight, please share via comment below.</p>

  <h3>Summary</h3>

  <p>Please leave your thoughts in the comments below in regard to creating domain objects over using language primitives (or heaven forbid, the <font face="Courier New">AssertWasCalled</font> debate).&#160; As far as this coding kata exercise, I need to take a high-level look at where this should go next.&#160; Perhaps the next post will tie up loose ends and see how our code performs on large text files as input.&#160; It may be that we will need to refactor our architecture to achieve better runtimes.&#160; If not, maybe we can still discuss where would could have headed if it had been necessary.</p>
</span>  </div>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Anagram Code Kata Part 4 – Will it Write My Code for Me?]]></title>
    <link href="http://mkmurray.com/blog/2010/01/26/anagram-code-kata-part-4-will-it-write-my-code-for-me/"/>
    <updated>2010-01-26T22:27:00-07:00</updated>
    <id>http://mkmurray.com/blog/2010/01/26/anagram-code-kata-part-4-will-it-write-my-code-for-me</id>
    <content type="html"><![CDATA[<div class='post'>
<p>This post is part of a <a href="http://murrayon.net/2009/11/anagram-code-kata-bdd-mspec.html">series on coding Kata, BDD, MSpec, and SOLID principles</a>.&#160; Feel free to visit the above link which points to the introductory post, also containing an index of all posts in the series.</p>  <p>In this post, we work on implementing the other main dependency, <font face="Courier New">IAnagramsFinder</font>.&#160; In doing so, you will discover that I have been a little naïve with this BDD methodology. Apparently I expected a different experience than what I ran into doing the exercise.&#160; In gathering feedback, I had a very interesting discussion about Object-Oriented Programming with <a href="http://adotnetdude.blogspot.com/">Esteban</a> that I will summarize and ask for further discussion from all of you.&#160; I’ll also show you one way to debug your code when running the MSpec tests via the console test runner.</p> <span class="fullpost">   <h3>New Thoughts on Mocks vs. Stubs</h3>    <p>During <a href="http://murrayon.net/2009/11/anagram-code-kata-part-2-mocking-and.html">Part 2 of this series</a>, <a href="http://papamufflon.blogspot.com/">Tobias</a> left <a href="http://murrayon.net/2009/11/anagram-code-kata-part-2-mocking-and.html#comments">a comment about using mocks and <font face="Courier New">AssertWasCalled</font></a>, rather than stubs and defining fake responses.&#160; I didn’t understand how it would help, as it appeared they would accomplish roughly the same thing.&#160; With stubs and fake responses, if you don’t get back the return you are looking for, then you can infer that the dependencies weren’t called since you had previously hard-coded their return values when called.&#160; With mocks and asserting methods were called, you directly assert that the manager class did in fact call it’s dependencies.</p>    <p>When I looked more closely into using the <font face="Courier New">AssertWasCalled</font> method in Rhino.Mocks, I noticed that my strategy of using stubs and faked return values wasn’t very explicit in signifying that the ultimate responsibility of the manager class was to delegate to its dependencies.&#160; I mean the test context does rigorously stub out the dependencies, but the actual assertions weren’t clear what we were testing.&#160; Therefore, I decided to pop in a pair of <font face="Courier New">AssertWasCalled</font> statements (as found below), leaving <a href="http://murrayon.net/2009/11/anagram-code-kata-part-2-mocking-and.html#firstSpec">the rest of the test the same as it was back in Part 2</a>.</p>    <pre class="brush: csharp">It should_result_in_list_of_anagram_sets_and_both_dependencies_should_have_been_called = () =&gt;
{
    fileParser.AssertWasCalled(x =&gt; x.ExtractWordListFromFile(filePath));
    anagramGrouper.AssertWasCalled(x =&gt; x.FindAnagramSets(wordListFromFile));

    result.ShouldEqual(expected);
};</pre>

  <p>However, when I thought to simplify the test code by removing most of stubbing setup, it appeared I had to leave most of the stub logic in tact in order to test if <font face="Courier New">anagramGrouper.FindAnagramSets()</font> was called with parameter <font face="Courier New">wordListFromFile</font>, which was one of the stubbed fake responses.&#160; The one dependency (the file parser) needed to pass it’s return value to the next dependency (the anagrams finder).&#160; I could not think of a way to accomplish testing that the manager class facilitated that without the stubbing logic (fake responses) that I created.</p>

  <p>It would be great if someone could enlighten me since I’m such a newbie to mocking and stubbing.&#160; Otherwise, I feel the intent of the test is now more clear with the <font face="Courier New">AssertWasCalled</font> checks that I added, even if that I means I’m needlessly mixing stubbing and mocking.&#160; But one last question:&#160; should I try to stick more closely to the rule of thumb guiding me to stick to one all-encompassing assertion per test if possible?&#160; Let me know your thoughts.</p>

  <h3>Implementing the <font face="Courier New">AnagramGrouper</font> Dependency</h3>

  <p>So let’s continue onward with some more actual design and code.&#160; We are tackling the <font face="Courier New">AnagramGrouper</font> dependency, whose sole responsibility is to take in the parsed collection of words and find anagram sets.&#160; Here is the test spec (one thing to note is that in some of my earlier tests for the <font face="Courier New">AnagramsFinder</font> manager class and <font face="Courier New">IFileParser</font>, I had used string arrays liberally; I decided to go with <font face="Courier New">IList&lt;string&gt;</font> collections instead):</p>

  <pre class="brush: csharp">public class AnagramGrouperSpecs
{
    [Subject(typeof(AnagramGrouperSpecs))]
    public class when_given_word_list_collection
    {
        static AnagramGrouper sut;
        static IEnumerable&lt;IList&lt;string&gt;&gt; result;
        static IEnumerable&lt;string&gt; wordList = new[] { &quot;wordA&quot;, &quot;wordB&quot;, &quot;Aword&quot;, &quot;wordC&quot; };

        Establish context = () =&gt;
        {
            sut = new AnagramGrouper();
        };

        Because of = () =&gt;
        {
            result = sut.FindAnagramSets(wordList);
        };

        It should_result_in_anagram_sets_collection_of_length_1 = () =&gt;
        {
            result.Count().ShouldEqual(1);
        };

        It should_contain_2_specific_words_in_the_anagram_set = () =&gt;
        {
            result.First().ShouldContain(&quot;wordA&quot;, &quot;Aword&quot;);
        };
    }
}</pre>

  <p>Here too I have basically two assertions (but split it up differently than last time); should I also try harder to avoid this as well?</p>

  <p>When contemplating how to further breakdown this responsibility of finding anagram sets into subtasks, I figure we would need one piece of code that would compare two words and answer whether they are anagrams of each other, and another piece of code that would keep track of the various anagram sets (perhaps a collection or dictionary of string arrays).&#160; With what BDD has revealed to me thus far, I figure this means we are going to see two more dependencies (and interfaces, and spec tests) added to the codebase.</p>

  <p>So I start with the word comparison task, thinking I could perhaps leverage the <font face="Courier New">String.GetHashCode()</font> method for assigning meaningful value to the list of characters in the string.&#160; However, string hash codes give importance to letter casing and order of characters, so a modified strategy would have to be utilized, even though <font face="Courier New">GetHashCode()</font> seems quite close to filling our need.</p>

  <p>Now I probably should have come up with this ingenious algorithm all by myself, but…it is what it is and this is the best, most concise solution that I can put together to solve the problem.&#160; With that said, I ended up doing some internet searching in order to proof-of-concept my <font face="Courier New">GetHashCode()</font> idea.&#160; I came across pure genius in the form of <a href="http://www.formatexception.com/">Brian Mullen’s</a> blog post entitled <a href="http://www.formatexception.com/2009/03/linq-group-by-and-groupby/">LINQ group by and GroupBy</a>, specifically the second-to-last code snippet.&#160; Just <font face="Courier New">String.ToCharArray()</font> the word and then <font face="Courier New">Array.Sort()</font> the resultant array; now turn it back into a string and do <font face="Courier New">GetHashCode()</font> now.&#160; (As a side note, we can worry about case-insensitivity later if desired by simply doing a <font face="Courier New">String.ToLower()</font> on the word before getting the hash code.)&#160; Now anagrams will have the same hash code (Brian uses the term “canonical”, which I think is very fitting); it’s literally perfect in every way!</p>

  <p>So now for the other dependency, I figure we could use a <font face="Courier New">Dictionary&lt;int, IList&lt;string&gt;&gt;</font>, where the key is the canonical hash code and the value is a string list collection representing an anagram set of words.&#160; These two dependency implementations are so simple and straight forward that I have a hard time seeing a reason to continue breaking out full-fledged object dependencies with interfaces and Dependency Injection.&#160; However, I will make a case for moving the canonical hash code logic outside this <font face="Courier New">AnagramsGrouper</font> class, but that will come later.</p>

  <p>So let’s write some code to pass our test/spec:</p>

  <pre class="brush: csharp">public class AnagramGrouper : IAnagramGrouper
{
    public IEnumerable&lt;IList&lt;string&gt;&gt; FindAnagramSets(IEnumerable&lt;string&gt; wordList)
    {
        Dictionary&lt;int, IList&lt;string&gt;&gt; results = new Dictionary&lt;int, IList&lt;string&gt;&gt;();

        foreach (string word in wordList)
        {
            int canonicalHashCode = GetCanonicalHashCode(word);

            if (results.ContainsKey(canonicalHashCode))
            {
                results[canonicalHashCode].Add(word);
            }
            else
            {
                results.Add(canonicalHashCode, new List&lt;string&gt;(new[] { word }));
            }
        }

        return results.Values;
    }

    public static int GetCanonicalHashCode(string word)
    {
        char[] letters = word.ToCharArray();
        Array.Sort&lt;char&gt;(letters);

        return new string(letters).GetHashCode();
    }
}</pre>

  <p>Maybe you noticed already, but there is a bug in my logic.&#160; At that time, I didn’t see it and needed to debug the code while running.&#160; Setting a debug break point in your code doesn’t work like you’re probably used to, and this is because we’re running the MSpec tests via its console test runner.&#160; I had to do some searching to figure this one out, and that’s what we’ll cover next.</p>

  <h3>How to Debug MSpec Specifications and the Code They Test</h3>

  <p>After a short ride on the Google super highway, I found a <a href="http://codebetter.com/blogs/aaron.jensen/archive/2008/09/02/mspec-v0-2.aspx#comments">blog post containing a November 2009 comment</a> from <a href="http://codebetter.com/blogs/aaron.jensen/default.aspx">Aaron Jensen</a>, author of MSpec, that gave a few possible solutions.&#160; I opted to go with the <font face="Courier new">Debugger.Break()</font> solution, which I put at the very top of my <font face="Courier new">FindAnagramSets</font> method.&#160; It is a tad awkward because it will show a Windows error dialog box that says the program encountered a problem and Windows is searching the web for a solution.&#160; If you wait through that, it will give you an option to debug the program via a Visual Studio dialog where you select the currently running instance of Visual Studio as your debugger instance.&#160; You just remove the statement when you’re done (and you’ll really want to remember to remove it from your production code).&#160; Does the trick, though it is a bit obtrusive to your code base.</p>

  <p>If you haven’t already figured it out, the bug is that my <font face="Courier New">FindAnagramSets</font> method is returning all anagram sets found in the dictionary.&#160; An anagram set of just one word is not really an anagram set, which is why our test specification which is based on that assumption failed.&#160; The fix is to filter out anagram word sets with less than two words before returning, like this:</p>

  <pre class="brush: csharp">// Return anagram sets with more than one word in it
return results.Values.Where(x =&gt; x.Count &gt; 1);</pre>

  <p>That will make the code pass the tests now.&#160; Remember to remove the debugger statement we added.</p>

  <h3>BDD, OOP…WTH?!</h3>

  <p>Just kidding.&#160; But I do want to discuss a reaction I had to BDD after implementing this anagram finding solution.&#160; After I completed the code and finished the tests, I was feeling pretty great.&#160; But then I started thinking about how I didn’t really go down the path that I felt BDD was originally trying to lead me down with <font face="Courier New">AnagramGrouper</font>, which was to create two more dependencies, just as I had done for the first managing class <font face="Courier New">AnagramsFinder</font>.&#160; I mean I felt pretty frustrated because I was digging BDD to this point.&#160; I’m not quite sure what my original expectations were, but I might have thought BDD was magically going to right my algorithms for me as well.</p>

  <p>I decided to discuss the whole thing with <a href="http://adotnetdude.blogspot.com/">Esteban</a> to get some perspective on the issue.&#160; He told me he didn’t know a thing about BDD and how it’s supposed to work, but he figured BDD would lead me to decoupled, cohesive code design, but he couldn’t see how it would aide with algorithmic solutions to the problems at hand.&#160; I’m not sure why I was so naïve, but it makes complete sense.&#160; I mean these methodologies are designed to keep you disciplined to some proven, guiding principles, but you still need to use your brain and creativity to actually solve the problem.&#160; I guess it would help to get some feedback and suggestions from you all in regard to knowing when it is time to switch from BDD architecture design mode to algorithm design mode within the broken down dependencies that handle the very specific sub-responsibilities.&#160; Please let me know if you have found some guiding concept or question you’ve come up with that you put to the test in order to lead you into the right coding mindset for that particular context (design or algorithm; or do I even have the right categories?).</p>

  <p>Perhaps it’s just that this design process feels so new to me.&#160; Maybe I have solely been in the coding, algorithm mindset this whole time throughout my career.&#160; Perhaps it will become more natural with practice and experience.&#160; I guess it just feels like I’m learning to drive a manual, stick-shift car or something, and I am a little rough with the clutch when transitioning between gears.</p>

  <p>To take this discussion further, <a href="http://adotnetdude.blogspot.com/">Esteban</a> made a comment in our conversation about his personal thoughts on these methodologies (like BDD) and Object-Oriented Programming.&#160; He has come to believe that we invent these methodologies like flavors of the week “because as programmers we don’t really get OOP.”&#160; Perhaps OOP just comes more naturally to his thought process that most people (or he admits it’s possible he could just be completely ignorant), but he feels that there’s really just a few simple rules and guidelines to keep in mind at all times in order to keep your objects behaving like real life objects and not acting like data constructs.&#160; I encouraged him to give his theory some additional thought and make it a little more formal by writing it down.&#160; He did this and the following is a link to the resultant blog post:</p>

  <p><a href="http://adotnetdude.blogspot.com/2010/01/3-simple-rules-to-good-object-oriented.html">3 Simple Rules to Good Object Oriented Code</a></p>

  <p>Please read through that post and comment on it.&#160; His idea needs to be criticized and/or validated.&#160; He admits he may have no clue what he’s talking about, but I said that’s why it needs to be put to the test by posting it in the open.&#160; We both think it’s an interesting theory, but we’re unsure if it even holds any water.&#160; Perhaps Esteban’s theory is too simplistic to be practical for many programmers.&#160; Provide feedback and lots of it.</p>

  <h3>Summary</h3>

  <p>So I think I need to wrap this post up about now.&#160; I think I have raised enough discussion points to write a book, but please do take the time to comment on what I’m doing wrong, what I’m doing right, or how to make the BDD mentality more flowing and natural.&#160; I promised to talk about having a Word class as opposed to using primitive strings everywhere, and that will definitely be in the next post.&#160; Also, I think our <font face="Courier New">AnagramGrouper</font> class may need some more testing and flushing out of how it should handle spaces, punctuation, casing, and so on.</p>

  <p>Thanks for sticking with me thus far.</p>
</span>  </div>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Anagram Code Kata Part 3 – Use Common Sense]]></title>
    <link href="http://mkmurray.com/blog/2009/12/18/anagram-code-kata-part-3-use-common-sense/"/>
    <updated>2009-12-18T18:10:00-07:00</updated>
    <id>http://mkmurray.com/blog/2009/12/18/anagram-code-kata-part-3-use-common-sense</id>
    <content type="html"><![CDATA[<div class='post'>
<p>This post is part of a <a href="http://murrayon.net/2009/11/anagram-code-kata-bdd-mspec.html">series on coding Kata, BDD, MSpec, and SOLID principles</a>.&#160; Feel free to visit the above link which points to the introductory post, also containing an index of all posts in the series.</p>  <p>In this post, we will discuss how far to take the idea of creating mockable contracts via interfaces for testing purposes and to keep responsibilities modular.&#160; As I solicited feedback from commenters, I was getting hung up on applying this concept to every object and dependency.&#160; We’ll talk about how I’m now thinking that overly strict adherence to the practice can drive you nuts and decrease productivity.&#160; It is meant to help guide your design process along rather than hinder it.&#160; We’ll finish this post off with one of our two dependencies implemented in an extremely simple manner.</p> <span class="fullpost">   <h3><font face="Courier New">IFileParser</font> Dependency</h3>    <p>When we left off last time, we had defined two separate responsibilities that <font face="Courier New">AnagramsFinder</font> was going to push down into its dependencies.&#160; As I started to write a specification test for the newly created <font face="Courier New">NewlineFileParser</font>, I realized it would be difficult to stub based on providing a file path to a text file as the only parameter.&#160; I began having thoughts that maybe I could break up another pair of dependencies for file parsing, namely obtaining a file stream (or file contents string) from a path and then parsing the file contents into a list of multiple lines.&#160; But then again, my first of the two dependencies is still dependent on the physical file system and I cannot get away from this unless I somehow mock up an in-memory file system.&#160; This began to feel silly to me as I was hoping I would just use the built-in .NET APIs for file systems and string parsing.</p>    <p>After emailing <a href="http://www.davesquared.net/" target="_blank">Dave</a> and <a href="http://adotnetdude.blogspot.com/" target="_blank">Esteban</a> asking for guidance, the revelation I received via these two fine gentlemen is that file parsing is not an essential purpose of this application nor exercise (at least not yet; we won’t be focusing on performance unless it appears to be grossly deficient as we go along).&#160; What we could do is write integration tests instead, where we have a set of simple test files sitting in a folder that we run our <font face="Courier New">NewlineFileParser</font> against to ensure it working as we expect.&#160; But I don’t think I’m even going to do this at this point.&#160; I really do want to get to the core of the application.&#160; Plus, I feel certain that I can trust the implementation of <font face="Courier New">File.ReadAllLines()</font> from the .NET Framework.</p>    <p>Unless it needs to be changed further down the road, the following code implementation will likely be sufficient for the remainder of this coding exercise:</p>    <pre class="brush: csharp">public class NewlineFileParser : IFileParser
{
    public IEnumerable&lt;string&gt; ExtractWordListFromFile(string filePath)
    {
        return File.ReadAllLines(filePath);
    }
}</pre>

  <p>I feel great about this because I haven’t gone insane trying to mock and test everything in sight, nor have I broken up every single responsibility in such small chunks that it becomes tedious.&#160; Instead, I have broken up the two core responsibilities of <font face="Courier New">AnagramsFinder</font> which means I can change and test the two dependencies independent of each other and from their manager class.&#160; Even though I haven’t written a ton of code yet, I feel the tests specs have driven my design into a cohesive, decoupled design that should prove flexible if requirements change or if I encounter friction later on and need to rethink my design.&#160; A flexible architecture for the application is being flushed out based on a “top-to-bottom” design view of the requirements.</p>

  <h3>Create Stubs or Assert Methods were Called</h3>

  <p><a href="http://papamufflon.blogspot.com/">Tobias Walter</a> left <a href="http://murrayon.net/2009/11/anagram-code-kata-part-2-mocking-and.html#comments">a comment on my last post</a> with some suggestions that I would like to get clarification on and discuss further with my growing audience of three now.&#160; He compared some of my implementation to <a href="http://www.davesquared.net/2009/11/favour-test-driving-logic-over-data.html">Dave’s implementation on his Favour test driving logic over data post</a>, but the comparison was lost on me.&#160; It seemed Tobias was saying that I had gone too far breaking up the responsibilities into such small dependencies.&#160; I am unsure what his argument was, but as far as I could tell both Dave and I broke up a managing class into two separate responsibilities so that the more crucial of the two could be tested independently.&#160; Also in doing so, we both created stubs that were given specific dummy responses to method calls using Rhino.Mocks.&#160; One more comment I would like to say is that I broke the file parsing responsibility away into its own dependency more because of the need to isolate the anagrams grouping than because file parsing is of itself a difficult task.&#160; If Tobias or anyone else could try to clarify his argument, that would really help me understand the merits of his suggestions.</p>

  <p>Another suggestion that Tobias brought up that I would like to petition feedback on is to use the mocking feature of testing whether a method was called instead of creating a stub programmed with a dummy response.&#160; I have to admit, I’m not sure when to use one method over another.&#160; I guess I’ve felt in the past that testing whether a method was called seems silly, since it seems odd to have your test know the implementation and inner method calls of the subject under test.&#160; But I am now realizing that my stubs appear to be doing the same thing, but with dummy input and output programmed in.&#160; If you have an opinion or experience on this subject, please leave some feedback in the comments of this post.</p>

  <h3>What’s Next?</h3>

  <p>In my next post I hope to summarize this mocking debate brought up above regarding two differing methods of verifying my manager class is correctly managing its dependencies.&#160; I also hope to begin driving out the design and implementation of the <font face="Courier New">AnagramGrouper</font> dependency via behavior specification tests.&#160; Thanks and any feedback is greatly appreciated.</p>
</span>  </div>
<h2>Comments</h2>
<div class='comments'>
<div class='comment'>
<div class='author'>David</div>
<div class='content'>
Hi Mike,<br /><br />In terms of the stubbing vs. asserting a method was called, the team I&#39;m on has found we rarely AssertWasCalled any more. Doing so explicitly couples our tests/specs to the implementation, whereas just stubbing calls in a SetUp seems easier to change without altering the fundamental assertions in our tests. <br /><br />The only time we use AssertWasCalled is for void methods to a service or similar where there is no observable side-effect from a unit perspective.<br /><br />YMMV. :)<br /><br />Regards,<br />David</div>
</div>
<div class='comment'>
<div class='author'>Tobias Walter</div>
<div class='content'>
Hi Mike,<br /><br />great you continued this series.<br /><br />I think I messed things up and wrote incorrect things. In the meantime I managed to do this kata again and now I agree with you. Just forget my advice to mock it - this was wrong.<br /><br />However, I and my coworkers question if it&#39;s worth to write 30 lines of code to test a 2-lines-method? I think for this kata it will be enough to do some acceptance tests here.</div>
</div>
</div>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Anagram Code Kata Part 2 – Mocking and SRP]]></title>
    <link href="http://mkmurray.com/blog/2009/11/17/anagram-code-kata-part-2-mocking-and-srp/"/>
    <updated>2009-11-17T00:59:00-07:00</updated>
    <id>http://mkmurray.com/blog/2009/11/17/anagram-code-kata-part-2-mocking-and-srp</id>
    <content type="html"><![CDATA[<div class='post'>
<p>This post is part of a <a href="http://murrayon.net/2009/11/anagram-code-kata-bdd-mspec.html">series on coding Kata, BDD, MSpec, and SOLID principles</a>.&#160; Feel free to visit the above link which points to the introductory post, also containing an index of all posts in the series.</p>  <p>In this post, we will rewrite our <a href="http://murrayon.net/2009/11/anagram-code-kata-part-1-getting.html" target="_blank">first specification/test from the previous post</a>, where we didn’t feel very confident about the direction we were heading.&#160; We got some great feedback and will now better <a href="http://www.davesquared.net/2009/11/favour-test-driving-logic-over-data.html" target="_blank">focus on test driving logic and not just data</a>; we will also be more careful in extracting the requirements from problem statement and in giving our classes a <a href="http://www.davesquared.net/2009/01/introduction-to-solid-principles-of-oo.html" target="_blank">Single Responsibility (the first of the SOLID principles of Object-Oriented Design)</a>.&#160; As we are test driving our design from a “top-down” perspective, we will encounter the need for dependencies not yet implemented while creating the higher level classes.&#160; Instead of halting our rhythm and progress, we will utilize a mocking framework to stub out non-existent implementations according to interfaces.&#160; This also encourages us to use <a href="http://www.davesquared.net/2009/01/introduction-to-solid-principles-of-oo.html" target="_blank">Dependency Inversion (last of the SOLID principles; same link as above)</a> and we can prove the validity of our modules by testing them in complete isolation from their dependencies.</p> <span class="fullpost">   <h3>Don’t Focus on Data (Yet) and SRP (Single Responsibility Principle)</h3>    <p>I had a feeling I was focusing too much on testing data, and I also knew it seemed to odd to be writing my very first test to be dependent on solving a specific instance of the problem (especially a test case with thousands of words in it), instead of working on solving the problem generally.&#160; After some terrific feedback from <a href="http://www.davesquared.net/" target="_blank">David Tchepak</a> in the <a href="http://murrayon.net/2009/11/anagram-code-kata-part-1-getting.html#comments" target="_blank">comments of my last post</a>, I now understand that wasn’t my only mistake.&#160; I was also trying to give my <font face="Courier New">AnagramsFinder</font> class too many responsibilities (especially with just one <font face="Courier New">ParseTextFile</font> method), namely extracting the words out of the text file and then grouping the anagrams together.&#160; Not only that, I also was returning a count of anagram sets when the <a href="http://codekata.pragprog.com/2007/01/kata_six_anagra.html" target="_blank">problem statement specifically asked for output of the anagram sets themselves</a>.&#160; Even though this is a simple problem scenario, it can be foolish to make assumptions or simplifications like I did that are not part of the requirements.</p>    <p>Let us first focus on the responsibilities required of our <font face="Courier New">AnagramsFinder</font> class.&#160; It needs to parse a list of words out of a text file given the file path and it also needs to group words together into sets that are anagrams of each other.&#160; However, we just named two responsibilities; implementing both in the same class would make it less cohesive and therefore less maintainable.&#160; This is because our class would have more than one responsibility that could change in the future, and because these responsibilities are in the same class, they could be considered coupled and one could be affected by modifications to the other.&#160; All of this train of thought falls under the Single Responsibility Principle from the SOLID principles (see links at the beginning of the post).</p>    <p>To solve this predicament, we will make <font face="Courier New">AnagramsFinder</font> a managing class of dependencies that individually solve these separate concerns.&#160; Each of these dependencies will adhere to the Single Responsibility principle, as does this higher abstraction manager class.&#160; Its responsibility can be summarized as managing the inputs, outputs, and execution order of its dependencies.&#160; We shall name the dependencies directly after each of their responsibilities, namely <font face="Courier New">FileParser</font> and <font face="Courier New">AnagramGrouper</font>.&#160; However, I don’t want to go implement these dependencies and throw off the flow of fleshing out the design and logic of my manager class.&#160; We are trying to design from a more “top-down” approach, instead of focusing on the lower level data concerns of the solution too early in the design process.&#160; To accomplish completing the design of our manager class without actually implementing the dependencies, we will code to interfaces (namely <font face="Courier New">IFileParser</font> and <font face="Courier New">IAnagramGrouper</font>).</p>    <h3>DIP (Dependency Inversion Principle)</h3>    <p>The advantages of using interfaces are that we abstract out the actual implementation of the dependencies, allowing us to be more modular and less coupled between dependencies.&#160; One class is not strongly tied to a specific implementation of its dependency, but rather the general contracts made available by the interface’s defined method signatures.&#160; What this really means is that we can swap out actual implementations of the dependency without the consuming class being modified in the least bit.&#160; This makes for truly maintainable code, especially when requirements change down the road after version one of the application is up and running.&#160; This is what the Dependency Inversion Principle (again, from SOLID) is all about.</p>    <p>We can take this a step further by passing the necessary dependencies into our consuming class at construction.&#160; This allows for us to “inject” into the object any implementation of the interface we see fit; this technique is aptly named Dependency Injection (DI).&#160; Our manager class doesn’t have to fret about any concrete details regarding its dependencies’ actual implementations, nor about any of the construction ceremony associated with “newing” up and initializing said dependencies.&#160; We won’t be using any DI containers (as our dependency needs are very light in this exercise), but the use of the Dependency Inversion Principle does set us up nicely to use a mocking framework so that we can finish fleshing out our tests without implementing any of the dependencies yet.</p>    <h3>Mocking Dependencies</h3>    <p>We would like to finish the design of our top level <font face="Courier New">AnagramsFinder</font> manager class, but not fully commit to how its dependencies will be implemented yet.&#160; We have a general idea of how we want our consuming class to interact with its dependencies via interfaces.&#160; Let’s go ahead and look at our interfaces we named earlier:</p>    <pre class="brush: csharp">public interface IFileParser
{
    IEnumerable&lt;string&gt; ExtractWordListFromFile(string filePath);
}

public interface IAnagramGrouper
{
    IEnumerable&lt;string[]&gt; FindAnagramSets(IEnumerable<string> wordList);
}</pre>

  <p>Now, we could create concrete implementations of the interfaces to be used in our tests that return simple dummy results.&#160; An example could look like this:</p>

  <pre class="brush: csharp">public class TestFileParser : IFileParser
{
    public IEnumerable&lt;string&gt; ExtractWordListFromFile(string filePath)
    {
        return new[] { &quot;wordA&quot;, &quot;wordB&quot;, &quot;Aword&quot;, &quot;wordC&quot; };;
    }
}</pre>

  <p>This is helpful because it keeps the one class we are interested in from being dependent on any real logic in its dependencies.&#160; We want to be able to test our modules in isolation from any dependencies, so that no secondary or outside influences skew the test results.&#160; We are basically providing dummy dependencies to our tests that have no logic that could cause side effects.</p>

  <p>However, the software development community has provided tools called mocking frameworks that can create these dependency stubs for you.&#160; This can save you from creating concrete interface implementations that have no use except for in testing.&#160; The mocking framework I will try out is <a href="http://www.ayende.com/projects/rhino-mocks.aspx" target="_blank">Rhino.Mocks from Ayende</a>.&#160; To get set up, you merely need to <a href="http://www.ayende.com/projects/rhino-mocks/downloads.aspx" target="_blank">download the latest build zip archive</a>, extract out the <font face="Courier New">Rhino.Mocks.dll</font> library to our <font face="Courier New">Libraries</font> folder created in the last blog post, and add a reference to the DLL in our Visual Studio solution.&#160; I will next show you how to use Rhino.Mocks as we rewrite our first specification test.</p>
  <a name="firstSpec"></a>

  <h3>Rewrite of Our First Specification/Test</h3>

  <p>Armed with SRP, DIP, mocking, a more strict adherence to the actual problem statement, and a renewed focus on “favoring test driving logic over just testing data,” we now rewrite our first specification as follows:</p>

  <pre class="brush: csharp">[Subject(typeof(AnagramsFinder), &quot;Finding Anagrams&quot;)]
public class when_given_text_file_with_word_on_each_line
{
    static AnagramsFinder sut;
    static IEnumerable&lt;string[]&gt; result;
    static string filePath = &quot;dummy_file_path.txt&quot;;
    static IEnumerable&lt;string&gt; wordListFromFile = new[] { &quot;wordA&quot;, &quot;wordB&quot;, &quot;Aword&quot;, &quot;wordC&quot; };
    static IEnumerable&lt;string[]&gt; expected = new[] { new[] { &quot;anagram&quot;, &quot;gramana&quot; } };

    Establish context = () =&gt;
    {
        var fileParser = MockRepository.GenerateStub&lt;IFileParser&gt;();
        fileParser.Stub(x =&gt; x.ExtractWordListFromFile(filePath)).Return(wordListFromFile);

        var anagramGrouper = MockRepository.GenerateStub&lt;IAnagramGrouper&gt;();
        anagramGrouper.Stub(x =&gt; x.FindAnagramSets(wordListFromFile)).Return(expected);

        sut = new AnagramsFinder(fileParser, anagramGrouper);
    };

    Because of = () =&gt;
    {
        result = sut.ExtractAnagramSets(filePath);
    };

    It should_result_in_list_of_anagram_sets = () =&gt;
    {
        result.ShouldEqual(expected);
    };
}</pre>

  <p>I should mention a few notes about the code.&#160; First, we need to add a using Rhino.Mocks statement at the top of our specification class file.&#160; Second, our <font face="Courier New">AnagramsFinder</font> instance variable named <font face="Courier New">sut</font> stands for the “Subject Under Test,” a mannerism I picked up from David Tchepak, whom I’ve mentioned several times throughout this post series.</p>

  <p>Our use of Rhino.Mocks is found when we call the <font face="Courier New">MockRepository.GenerateStub</font> method against an interface.&#160; We then proceed to tell the stubbed object how to behave by specifying dummy return values when given methods of the object are called with given parameters.&#160; The last line of our “context” setup is to then inject these two newly generated, stubbed dependencies into our manager class for testing.&#160; It’s also interesting to note that none of my parameters and expected outputs really make much sense.&#160; This is done on purpose to show that the data really doesn’t matter to this class, as we are not testing the logic of any data processing by the dependencies (remember, test in isolation).&#160; It is true that this test really isn’t testing any real logic at this point, and it may even never evolve into testing any real logic either.&#160; However, I think the important point is that it aided us in fleshing out the design, which we previously didn’t know how we were going to implement.&#160; Not all tests will created equal in regard to validating our logic, but they all will play a part in driving the design of our code.&#160; Hopefully these statements are true, and I would love to hear feedback on this topic in the comments.</p>

  <p>I also want to touch on the Specification pattern of Behavior Driven Design and testing.&#160; Specification tests are commonly set up into a workflow of context establishing, behavior performing, and results asserting.&#160; The MSpec framework is designed to encourage this test organization.</p>

  <h3>Red, Green, Refactor and MSpec Test Runner Output</h3>

  <p>To make our first test run, we need to create the basic outline of our <font face="Courier New">AnagramsFinder</font> class as outlined in our test.&#160; This includes a constructor that takes our two dependencies and an <font face="Courier New">ExtractAnagramSets</font> method:</p>

  <pre class="brush: csharp">public class AnagramsFinder
{
    private IFileParser fileParser;
    private IAnagramGrouper anagramGrouper;

    public AnagramsFinder(IFileParser fileParser, IAnagramGrouper anagramGrouper)
    {
        this.fileParser = fileParser;
        this.anagramGrouper = anagramGrouper;
    }

    public IEnumerable&lt;string[]&gt; ExtractAnagramSets(string filePath)
    {
        throw new NotImplementedException();
    }
}</pre>

  <p>I am using the ConsoleRunner according to the method described in Rob Conery’s introductory MSpec and BDD post, including output to an HTML report.&#160; After running our specifications, we get the following output:</p>

  <pre style="border-bottom: #cecece 1px solid; border-left: #cecece 1px solid; padding-bottom: 5px; background-color: #fbfbfb; min-height: 40px; padding-left: 5px; width: 567px; padding-right: 5px; height: 239px; border-top: #cecece 1px solid; border-right: #cecece 1px solid; padding-top: 5px"><pre style="background-color: #fbfbfb; margin: 0em; width: 100%; font-family: consolas,&#39;Courier New&#39;,courier,monospace; font-size: 12px">Specs in AnagramCodeKata:

AnagramsFinder Finding Anagrams, when given text file with word on each line
¯ should result in list of anagram sets (FAIL)
System.NotImplementedException: The method or operation is not implemented.
   ... Stack Trace here ...

Contexts: 1, Specifications: 1
  0 passed, 1 failed</pre></pre>

  <p>…and the HTML report:</p>

  <p></p>
  <a href="http://lh6.ggpht.com/_rps657FzHZ0/SwJYInxVVSI/AAAAAAAAADU/jcI2a8kADCA/s1600-h/htmlReportError%5B3%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="htmlReportError" border="0" alt="htmlReportError" src="http://lh3.ggpht.com/_rps657FzHZ0/SwJYJUz3eMI/AAAAAAAAADY/bBzyAsPXUsw/htmlReportError_thumb%5B1%5D.png?imgmax=800" width="564" height="445" /></a> </a>

  <p>A highly encouraged tenet of Test Driven Development is the practice of “Red, Green, Refactor.”&#160; It is meant to denote the evolution of the results and state of your tests.&#160; You are encouraged to write the test and then do the minimum work necessary to get the code base to compile and run.&#160; You are first running your test in a control state where you know it should fail.&#160; Most test runners will show the color Red in regard to failed tests, and thus the name of the first step.&#160; Your next stage is to implement the code to make the test pass and turn the output color to Green, commonly indicating passing tests.&#160; The Refactor stage is a time to pause and see if any code can be reorganized or simplified.&#160; Then “rinse and repeat as necessary”, an applicable instruction from shampoo bottles.</p>

  <p>To make our test pass, we implement real logic to coordinate the calls into our dependencies, like so:</p>

  <pre class="brush: csharp">public IEnumerable&lt;string[]&gt; ExtractAnagramSets(string filePath)
{
    var wordList = fileParser.ExtractWordListFromFile(filePath);
    return anagramGrouper.FindAnagramSets(wordList);
}</pre>

  <p>…and the successful outputs of our test runner:</p>

  <pre style="border-bottom: #cecece 1px solid; border-left: #cecece 1px solid; padding-bottom: 5px; background-color: #fbfbfb; min-height: 40px; padding-left: 5px; width: 579px; padding-right: 5px; height: 156px; border-top: #cecece 1px solid; border-right: #cecece 1px solid; padding-top: 5px"><pre style="background-color: #fbfbfb; margin: 0em; width: 100%; font-family: consolas,&#39;Courier New&#39;,courier,monospace; font-size: 12px">Specs in AnagramCodeKata:

AnagramsFinder Finding Anagrams, when given text file with word on each line
¯ should result in list of anagram sets

Contexts: 1, Specifications: 1</pre></pre>

  <p>&#160;</p>

  <p><a href="http://lh5.ggpht.com/_rps657FzHZ0/SwJYJpq8OfI/AAAAAAAAADc/noptZ4ChfGo/s1600-h/htmlReportSuccess%5B3%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="htmlReportSuccess" border="0" alt="htmlReportSuccess" src="http://lh5.ggpht.com/_rps657FzHZ0/SwJYKGw-YWI/AAAAAAAAADg/0aPU7UnGVno/htmlReportSuccess_thumb%5B1%5D.png?imgmax=800" width="583" height="436" /></a> </p>

  <h3>Final Thoughts and Questions</h3>

  <p>So what do you think of the new test?&#160; Are we better able to see the Single Responsibility of the <font face="Courier New">AnagramsFinder</font> manager class?&#160; Are we more inline with solving the actual problem statement?&#160; Your feedback would be much appreciated.</p>

  <p>In the next post, we will begin work on test driving the design and implementation of the dependencies…unless of course I get feedback that I should be focusing on a different area first or that this last rewrite still needs more help.</p>
</span>  </div>
<h2>Comments</h2>
<div class='comments'>
<div class='comment'>
<div class='author'>Tobias Walter</div>
<div class='content'>
Yes, this is a good start for a great idea (code kata done slowly).<br /><br />Right now, I&#39;m struggling with the same kata and I have a problem looking at your AnagramsFinder and IAnagramGrouper. The result of both is the same and the tests (apart from setting up a not needed IFileParser for the AnagramsFinder) will be the same too.<br /><br />I think this is because you&#39;re using the pipes and filters-pattern (opposite to David, who combines his both results in &quot;focus on test driving logic&quot;). Testing just the filters should be sufficient here?<br /><br />What you maybe can do is a behavioural test. So, instead of testing with stubs, use mock-objects testing weather the methods were called.<br /><br />What do you think about that?<br /><br />p.s. it&#39;s hard to post a comment here because the word verification-textbox is only accessible when selecting text with the mouse and scrolling down :(</div>
</div>
<div class='comment'>
<div class='author'>David</div>
<div class='content'>
Looks good Mike!<br /><br />I wouldn&#39;t call the previous spec a mistake or &quot;foolish&quot; though. I seen working on simple cases like Count advocated lots of places for doing TDD, I&#39;ve just always struggled with getting from those cases to the main responsibilities of the class.<br /><br />Looking forward to the rest of the series.</div>
</div>
</div>
]]></content>
  </entry>
  
</feed>
