<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>Dr. Random - IoC</title>
    <link>http://www.drrandom.org/</link>
    <description>Random Thoughts for Random People</description>
    <language>en-us</language>
    <copyright>Casey Kramer</copyright>
    <lastBuildDate>Tue, 02 Oct 2007 20:53:13 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.3.9074.18820</generator>
    <managingEditor>casey.kramer@gmail.com</managingEditor>
    <webMaster>casey.kramer@gmail.com</webMaster>
    <item>
      <trackback:ping>http://www.drrandom.org/Trackback.aspx?guid=4ec5e15f-86a5-49b2-bdde-569311078d63</trackback:ping>
      <pingback:server>http://www.drrandom.org/pingback.aspx</pingback:server>
      <pingback:target>http://www.drrandom.org/PermaLink,guid,4ec5e15f-86a5-49b2-bdde-569311078d63.aspx</pingback:target>
      <dc:creator>Casey Kramer</dc:creator>
      <wfw:comment>http://www.drrandom.org/CommentView,guid,4ec5e15f-86a5-49b2-bdde-569311078d63.aspx</wfw:comment>
      <wfw:commentRss>http://www.drrandom.org/SyndicationService.asmx/GetEntryCommentsRss?guid=4ec5e15f-86a5-49b2-bdde-569311078d63</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I'm currently finding myself in the midst of an evolutionary change.  And I'm
not talking about my super-human mutant powers, I'm talking about the way I'm thinking
about solving a specific set of problems. 
</p>
        <p>
Let's start with a sample....Lets take something like processing credit-cards as a
benign and IP free place to start.  As a subject that I really have no practical
experience with, it seems like an appropriate choice.  I'm going to assume that
there are different rules for doing checksum validation on credit card numbers, depending
on what the card is (Mastercard/Visa/Discover/etc). Now, here is evolutionary step
1: Use a basic case statement to process the various cards.  Here is what something
like that would look like:<br /></p>
        <pre class="brush: csharp">switch(CardType)
{
    case CardType.MasterCard:
        CardValidators.MasterCardValidator(card.CardNumber);
        break;
    case CardType.Visa:
        CardValidators.VisaValidator(card.CardNumber);
        break;
    case CardType.Discover:
        CardValidators.DiscoverValidator(card.CardNumber);
        break;
}</pre>
        <p>
 
</p>
        <p>
This looks pretty straight-forward, and as it stands it isn't too bad from a maintainability
stand point.  But what happens when there are many different types of cards? 
An then what happens when you find a large amount of duplication between the validation
functions?
</p>
        <p>
Well, any student of GoF should be able to tell you that a Chain Of Responsibility
pattern looks like a perfect fit for this sort of scenario.  So, evolutionary
step 2: Create separate classes to handle the different types of validation, and configure
them in a Chain of Responsibility pattern where each instance decides for itself whether
it can process the input.
</p>
        <p>
Here is a quick and dirty look at what something like that would look like:<br /><img style="border-width: 0px;" alt="ClassDiagram1" src="http://www.drrandom.org/content/binary/ClassDiagram1.png" border="0" height="421" width="571" /></p>
        <p>
 
</p>
        <p>
The two most interesting things here are the GetValidator() method in the AbstractCardValidator,
and the individual CanValidate() methods in the concrete implementations.  What
this does is it allows each class to decide for itself how it is going to determine
whether or not it can be used as a validator for a specific card (thats the CanValidate()
part), and also provides a single point which the consumer of the API can use to get <em>the</em> validator
for the card instance they have.  You would probably want to build and Abstract
Factory around this, which would instantiate all of the ICardValidator classes, and
then run the GetValidator() method to get the correct one.
</p>
        <p>
Now we are at a point where things are looking pretty good; we've got the ability
to do some fairly complex logic to make the decision about which validator to use,
and we have a way to simply ask for one, and the correct one appears.  Pretty
cool.
</p>
        <p>
This is actually the place where I have found myself in the not to distant past. 
I have previously been perfectly content with this arrangement, and been fairly happy
with the separation of concerns among the classes...I mean, after all, who better
to decide whether or not a specific class should be used to validate a card than the
class itself.  So what is the issue?  Well, recently I have become aware
of two problems with this arrangement: Tight Coupling, and a violation of the Single
Responsibility Principle.  Let's start with the first:
</p>
        <p>
          <strong>Tight Coupling<br /></strong>The credit card example may be a bit contrived when it comes to this issue,
but bear with me.  Overall, the issue is that specific instances of ICardValidtor
objects are being created and handed around.  The use of an interface and an
Abstract Factory pattern would actually help the situation out some, but effectively
all it does is move the coupling from the consuming class to the Factory (okay, it
also consolidates coupling to a single class, which makes maintenance a lot easier). 
As I said, contained, but still there.  It would be nice if the factory didn't
need any knowledge of what concrete instances of ICardValidator were out there. 
Before we tackle that, though, lets also look at the second issue:
</p>
        <p>
          <strong>Violation of the "Single Responsibility Principle"<br /></strong>The SRP states that a class should have one, and only one, thing it is responsible
for.  Sounds pretty easy doesn't it?  The problem is that this can be difficult
to obtain without a fair amount of discipline.  The violation of SRP which
I'm seeing is that the ICardValidator is responsible for both validating a credit
card <em>and</em> determining which validator is appropriate.  But wait! 
Didn't I just say that moving this check into the ICardValidator instance was a "Good
Thing"?  Well, lets go as far as saying it is <em>better</em> than the previous
method, but still not perfect.  Applying the SRP would move the task of selecting
a validator from the ICardValidator instance, and put it on it's own somewhere. 
So, thusly we come to our:
</p>
        <p>
          <strong>Inversion Of Control Container</strong>.<br />
That's right, we are now going to get crazy and move the responsibility of creating
these instances to another component all together.  The nice thing about this
is that it allows us to move all of the knowledge about dependencies off somewhere
else.  How does this apply to this example?  Well, lets assume we have an
object of type <em>Card</em> which requires as a dependency an instance of an <em>ICardValidator.  </em>We'll
also assume that <em>Card</em> is subclassed based on the type of credit card. 
It now becomes trivial to configure our IoC container to supply a <em>specific implementation</em> (read
sub-type) of <em>ICardValidator</em> for each implementation (again, read sub-type)
of <em>Card</em>.  Now, when you want a <em>Card</em> instance, you ask the IoC
container for one, and depending on what type of card it is, you will get the appropriate <em>ICardValidator</em> as
well.
</p>
        <p>
What's the catch?  Well there is some additional complexity which will show up
somewhere in the application due to the IoC, but typically IoC configuration can be
delegated down to the configuration file level, so even then the ugliness is pushed
away to it's own dark corner.
</p>
        <p>
But wait!  Why should we have different instances of <em>Card</em>?  What
if the Card class is just a container for the card data?  Well, our Ioc still
gives us some advantages.  If we look back at our first example with the switch
statement, we've got a nice <em>CardType</em> enum, which could be a property of our <em>Card</em> class. 
Using an IoC container like the one provided by the Castle project, you have the ability
to configure a key string for your instances.  This would make it trivial to
map the enum choices to specific keys within the container, which the <em>Card</em> class
would use to get an ICardValidator instance.  This would also make it possible
to make the validators slightly more advanced by adding something like a Decorator
pattern, in which specific aspects of the validation could be factored into separate
classes, and then "stacked" to produce the final validation logic (This is the same
concept used by the Stream classes in .Net and Java.  You can modify the behavior
of a stream by passing it to the constructor of a stream with different behavior).
</p>
        <p>
It is definatly worth mentioning that there is a sudden appearance
of tight coupling to the IoC container itself from our consuming classes.  You
probably want to try to abstract away the fact that the IoC container exists from
the majority of the application.  Factory classes go a fair ways in making this
happen, but another good idea is to introduce a single service to do type resolution. 
The Factory classes can then ask this service for the object they want, and they never
need to know the IoC container is there.  This approach also gives you the ability
to create some objects using IoC and others in another (more traditional) way.
</p>
        <p>
So is this it?  Have I finally found the answer I've been looking for? 
It's hard to say right now.  For the time being this is a decent way to handle
things, provided the complexity of the underlying system, and the need for loose-coupling
are both high enough to justify the additional complexity of the IoC.  But who
knows, in another couple months I may find something new, or even something old, which
seems better, cleaner, simpler.  That, after all, is my final goal....And I need
to remind myself of that regularly, lest I become complacent.
</p>
        <img width="0" height="0" src="http://www.drrandom.org/aggbug.ashx?id=4ec5e15f-86a5-49b2-bdde-569311078d63" />
      </body>
      <title>The evolution of design, and the continued search for &amp;quot;The Way&amp;quot;</title>
      <guid isPermaLink="false">http://www.drrandom.org/PermaLink,guid,4ec5e15f-86a5-49b2-bdde-569311078d63.aspx</guid>
      <link>http://www.drrandom.org/2007/10/02/TheEvolutionOfDesignAndTheContinuedSearchForQuotTheWayquot.aspx</link>
      <pubDate>Tue, 02 Oct 2007 20:53:13 GMT</pubDate>
      <description>&lt;p&gt;
I'm currently finding myself in the midst of an evolutionary change.&amp;nbsp; And I'm
not talking about my super-human mutant powers, I'm talking about the way I'm thinking
about solving a specific set of problems. 
&lt;/p&gt;
&lt;p&gt;
Let's start with a sample....Lets take something like processing credit-cards as a
benign and IP free place to start.&amp;nbsp; As a subject that I really have no practical
experience with, it seems like an appropriate choice.&amp;nbsp; I'm going to assume that
there are different rules for doing checksum validation on credit card numbers, depending
on what the card is (Mastercard/Visa/Discover/etc). Now, here is evolutionary step
1: Use a basic case statement to process the various cards.&amp;nbsp; Here is what something
like that would look like:&lt;br&gt;
&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;switch(CardType)
{
    case CardType.MasterCard:
        CardValidators.MasterCardValidator(card.CardNumber);
        break;
    case CardType.Visa:
        CardValidators.VisaValidator(card.CardNumber);
        break;
    case CardType.Discover:
        CardValidators.DiscoverValidator(card.CardNumber);
        break;
}&lt;/pre&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
This looks pretty straight-forward, and as it stands it isn't too bad from a maintainability
stand point.&amp;nbsp; But what happens when there are many different types of cards?&amp;nbsp;
An then what happens when you find a large amount of duplication between the validation
functions?
&lt;/p&gt;
&lt;p&gt;
Well, any student of GoF should be able to tell you that a Chain Of Responsibility
pattern looks like a perfect fit for this sort of scenario.&amp;nbsp; So, evolutionary
step 2: Create separate classes to handle the different types of validation, and configure
them in a Chain of Responsibility pattern where each instance decides for itself whether
it can process the input.
&lt;/p&gt;
&lt;p&gt;
Here is a quick and dirty look at what something like that would look like:&lt;br&gt;
&lt;img style="border-width: 0px;" alt="ClassDiagram1" src="http://www.drrandom.org/content/binary/ClassDiagram1.png" border="0" height="421" width="571"&gt; 
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
The two most interesting things here are the GetValidator() method in the AbstractCardValidator,
and the individual CanValidate() methods in the concrete implementations.&amp;nbsp; What
this does is it allows each class to decide for itself how it is going to determine
whether or not it can be used as a validator for a specific card (thats the CanValidate()
part), and also provides a single point which the consumer of the API can use to get &lt;em&gt;the&lt;/em&gt; validator
for the card instance they have.&amp;nbsp; You would probably want to build and Abstract
Factory around this, which would instantiate all of the ICardValidator classes, and
then run the GetValidator() method to get the correct one.
&lt;/p&gt;
&lt;p&gt;
Now we are at a point where things are looking pretty good; we've got the ability
to do some fairly complex logic to make the decision about which validator to use,
and we have a way to simply ask for one, and the correct one appears.&amp;nbsp; Pretty
cool.
&lt;/p&gt;
&lt;p&gt;
This is actually the place where I have found myself in the not to distant past.&amp;nbsp;
I have previously been perfectly content with this arrangement, and been fairly happy
with the separation of concerns among the classes...I mean, after all, who better
to decide whether or not a specific class should be used to validate a card than the
class itself.&amp;nbsp; So what is the issue?&amp;nbsp; Well, recently I have become aware
of two problems with this arrangement: Tight Coupling, and a violation of the Single
Responsibility Principle.&amp;nbsp; Let's start with the first:
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Tight Coupling&lt;br&gt;
&lt;/strong&gt;The credit card example may be a bit contrived when it comes to this issue,
but bear with me.&amp;nbsp; Overall, the issue is that specific instances of ICardValidtor
objects are being created and handed around.&amp;nbsp; The use of an interface and an
Abstract Factory pattern would actually help the situation out&amp;nbsp;some, but effectively
all it does is move the coupling from the consuming class to the Factory (okay, it
also consolidates coupling to a single class, which makes maintenance a lot easier).&amp;nbsp;
As I said, contained, but still there.&amp;nbsp; It would be nice if the factory didn't
need any knowledge of what concrete instances of ICardValidator were out there.&amp;nbsp;
Before we tackle that, though, lets also look at the second issue:
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Violation of the "Single Responsibility Principle"&lt;br&gt;
&lt;/strong&gt;The SRP states that a class should have one, and only one, thing it is responsible
for.&amp;nbsp; Sounds pretty easy doesn't it?&amp;nbsp; The problem is that this can be difficult
to obtain without a fair&amp;nbsp;amount of discipline.&amp;nbsp; The violation of SRP which
I'm seeing is that the ICardValidator is responsible for both validating a credit
card &lt;em&gt;and&lt;/em&gt; determining which validator is appropriate.&amp;nbsp; But wait!&amp;nbsp;
Didn't I just say that moving this check into the ICardValidator instance was a "Good
Thing"?&amp;nbsp; Well, lets go as far as saying it is &lt;em&gt;better&lt;/em&gt; than the previous
method, but still not perfect.&amp;nbsp; Applying the SRP would move the task of selecting
a validator from the ICardValidator instance, and put it on it's own somewhere.&amp;nbsp;
So, thusly we come to our:
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Inversion Of Control Container&lt;/strong&gt;.&lt;br&gt;
That's right, we are now going to get crazy and move the responsibility of creating
these instances to another component all together.&amp;nbsp; The nice thing about this
is that it allows us to move all of the knowledge about dependencies off somewhere
else.&amp;nbsp; How does this apply to this example?&amp;nbsp; Well, lets assume we have an
object of type &lt;em&gt;Card&lt;/em&gt; which requires as a dependency an instance of an &lt;em&gt;ICardValidator.&amp;nbsp; &lt;/em&gt;We'll
also assume that &lt;em&gt;Card&lt;/em&gt; is subclassed based on the type of credit card.&amp;nbsp;
It now becomes trivial to configure our IoC container to supply a &lt;em&gt;specific implementation&lt;/em&gt; (read
sub-type) of &lt;em&gt;ICardValidator&lt;/em&gt; for each implementation (again, read sub-type)
of &lt;em&gt;Card&lt;/em&gt;.&amp;nbsp; Now, when you want a &lt;em&gt;Card&lt;/em&gt; instance, you ask the IoC
container for one, and depending on what type of card it is, you will get the appropriate &lt;em&gt;ICardValidator&lt;/em&gt; as
well.
&lt;/p&gt;
&lt;p&gt;
What's the catch?&amp;nbsp; Well there is some additional complexity which will show up
somewhere in the application due to the IoC, but typically IoC configuration can be
delegated down to the configuration file level, so even then the ugliness is pushed
away to it's own dark corner.
&lt;/p&gt;
&lt;p&gt;
But wait!&amp;nbsp; Why should we have different instances of &lt;em&gt;Card&lt;/em&gt;?&amp;nbsp; What
if the Card class is just a container for the card data?&amp;nbsp; Well, our Ioc still
gives us some advantages.&amp;nbsp; If we look back at our first example with the switch
statement, we've got a nice &lt;em&gt;CardType&lt;/em&gt; enum, which could be a property of our &lt;em&gt;Card&lt;/em&gt; class.&amp;nbsp;
Using an IoC container like the one provided by the Castle project, you have the ability
to configure a key string for your instances.&amp;nbsp; This would make it trivial to
map the enum choices to specific keys within the container, which the &lt;em&gt;Card&lt;/em&gt; class
would use to get an ICardValidator instance.&amp;nbsp; This would also make it possible
to make the validators slightly more advanced by adding something like a Decorator
pattern, in which specific aspects of the validation could be factored into separate
classes, and then "stacked" to produce the final validation logic (This is the same
concept used by the Stream classes in .Net and Java.&amp;nbsp; You can modify the behavior
of a stream by passing it to the constructor of a stream with different behavior).
&lt;/p&gt;
&lt;p&gt;
It is definatly&amp;nbsp;worth mentioning&amp;nbsp;that there is a&amp;nbsp;sudden appearance
of tight coupling to the IoC container itself from our consuming classes.&amp;nbsp; You
probably want to try to abstract away the fact that the IoC container exists from
the majority of the application.&amp;nbsp; Factory classes go a fair ways in making this
happen, but another good idea is to introduce a single service to do type resolution.&amp;nbsp;
The Factory classes can then ask this service for the object they want, and they never
need to know the IoC container is there.&amp;nbsp; This approach also gives you the ability
to create some objects using IoC and others in another (more traditional) way.
&lt;/p&gt;
&lt;p&gt;
So is this it?&amp;nbsp; Have I finally found the answer I've been looking for?&amp;nbsp;
It's hard to say right now.&amp;nbsp; For the time being this is a decent way to handle
things, provided the complexity of the underlying system, and the need for loose-coupling
are both high enough to justify the additional complexity of the IoC.&amp;nbsp; But who
knows, in another couple months I may find something new, or even something old, which
seems better, cleaner, simpler.&amp;nbsp; That, after all, is my final goal....And I need
to remind myself of that regularly, lest I become complacent.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.drrandom.org/aggbug.ashx?id=4ec5e15f-86a5-49b2-bdde-569311078d63" /&gt;</description>
      <comments>http://www.drrandom.org/CommentView,guid,4ec5e15f-86a5-49b2-bdde-569311078d63.aspx</comments>
      <category>.Net</category>
      <category>IoC</category>
      <category>tips</category>
    </item>
  </channel>
</rss>