<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="/stylesheets/rss.css"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
  <channel>
    <title>Object Mentor Blog: Category Clean Code</title>
    <link>http://blog.objectmentor.com/articles/category/clean-code</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description></description>
    <item>
      <title>20% more bugs?  Or 20% less features?</title>
      <description>&lt;p&gt;People often make the argument that time to market is more important that quality.  I&amp;#8217;m not sure just what they mean by that.  Do they mean that it&amp;#8217;s ok if 20% of the features don&amp;#8217;t work so long as they deliver quickly?  If so, that&amp;#8217;s just stupid.  Why not develop 20% fewer features, and develop them well.  It seems to me that &lt;em&gt;choosing&lt;/em&gt; which 20% you are not going to develop and then &lt;em&gt;choosing&lt;/em&gt; to develop the other 80% to a high standard of quality is a better management decision than telling the developers to work sloppily.&lt;/p&gt;</description>
      <pubDate>Tue, 06 Apr 2010 22:03:23 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:9282cb2f-5432-45d6-a819-1df5fde99b61</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2010/04/06/20-more-bugs-or-20-less-features</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Software on the Cheap</title>
      <description>&lt;p&gt;When it comes to software, you get what you pay for.&lt;/p&gt;


	&lt;p&gt;Have you ever stopped to wonder how much a line of code costs?  
It ought to be easy to figure out.&lt;/p&gt;


	&lt;p&gt;In the last 14 months, I have written about 20KSLOC in FitNesse.  Of course that was part time.  My real job is running Object Mentor, consulting, teaching, mentoring, writing, and a whole load of other things.  Programming takes up perhaps 15% of my time.&lt;/p&gt;


	&lt;p&gt;On the other hand most programmers have lots of other things to do.  They go to meetings, and then they go to more meetings.  When they are done with those meetings, they go to meetings.  And then there are the meetings to go to.  Oh yeah, and then there&amp;#8217;s all the fiddling around with time accounting tools, and horrific source code control systems that perform like a salamander crawling through frozen mud.&lt;/p&gt;


	&lt;p&gt;So, maybe 15% isn&amp;#8217;t such a bad ratio.&lt;/p&gt;


	&lt;p&gt;The loaded rate (Salary plus everything else) for a typical programmer is on the order of $200K. (I know that sounds like a lot, but you can look it up.) So $200K / (20KSLOC / 14mo * 12mo) = $11.66/SLOC.&lt;/p&gt;


	&lt;p&gt;Let&amp;#8217;s look at one of those lines: &lt;code&gt;StringBuffer nameBuffer = new StringBuffer();&lt;/code&gt;
Does that look like $11.66 to you?  Would you pay that much for it?  Well, don&amp;#8217;t answer yet, because for each &lt;code&gt;StringBuffer&lt;/code&gt; line you buy, you get &lt;code&gt;import java.lang.StringBuffer;&lt;/code&gt; absolutely free!&lt;/p&gt;


	&lt;p&gt;Some factories pay their employees a &amp;#8220;piece rate&amp;#8221;.  Would you accept $11.66 per line of code instead of a salary? Of course it couldn&amp;#8217;t just be any old line of code.  It&amp;#8217;d have to be tested!&lt;/p&gt;


	&lt;p&gt;Hey, I bet all programmers would do &lt;span class="caps"&gt;TDD&lt;/span&gt; if we paid them a piece rate!&lt;/p&gt;


	&lt;h2&gt;Down to business.&lt;/h2&gt;


	&lt;p&gt;The point of that silly analysis was to demonstrate that software is &lt;em&gt;expensive&lt;/em&gt;.  Even the dumbest little app will likely require more than 1,000 lines of code; and that means it could cost $12K to write!&lt;/p&gt;


	&lt;p&gt;Imagine that you aren&amp;#8217;t a programmer, but you have a clever idea for a new website that&amp;#8217;ll make you a zillion dollars.  You&amp;#8217;ve storyboarded it all out.  You&amp;#8217;ve worked out all the details.  Now all you need is some high-school kid to zip out the code for you. Right?  Hell, you could pay him minimum wage!  The little twerp would be happy to get it!&lt;/p&gt;


	&lt;p&gt;That tragic comedy is altogether too common.  Too many people have borrowed money against their father&amp;#8217;s retirement account to fund a terrible implementation of a good idea.  Appalled at how much the reputable firms charge per hour ($100 or more) they go looking for a cheap solution.&lt;/p&gt;


	&lt;p&gt;&amp;#8220;After all, this software is &lt;em&gt;simple&lt;/em&gt;.&amp;#8221; Or so the reasoning goes.  &amp;#8220;It&amp;#8217;s not like we&amp;#8217;re trying to send a rocket to the moon or anything.  And, besides, those expensive guys were just out to cheat us.  Software just isn&amp;#8217;t that hard to write.&amp;#8221;  Uh huh.&lt;/p&gt;


	&lt;p&gt;So the poor schmuck finds some freshman in college, or maybe a bored housewife who read a book on &lt;span class="caps"&gt;HTML&lt;/span&gt; last year and created a cute website to show off her kittens. Have these programmers heard about &lt;span class="caps"&gt;TDD&lt;/span&gt;?  Have they heard about Design Patterns?  Principles?  How about source code control?&lt;/p&gt;


	&lt;p&gt;Clearly they haven&amp;#8217;t.  They&amp;#8217;re going to sling a bunch of horrific code together, without any tests, versioning, or control.  The project will start well, with exciting initial results.  But then it will slowly grind to a halt, while the cash continues out the door unabated.&lt;/p&gt;


	&lt;p&gt;In the end the website isn&amp;#8217;t going to get built (and the poor schmuck&amp;#8217;s father won&amp;#8217;t be retiring as soon as he thought). It will be a disaster that will either be terminated, or will require double or triple the investment to get right.&lt;/p&gt;


	&lt;h2&gt;The Bottom Line.&lt;/h2&gt;


	&lt;p&gt;The bottom line is that, when it comes to software, you get what you pay for.  If you want good software done well, then you are going to pay for it, and it will probably cost you $12/line or more.  And, believe me, that&amp;#8217;s the &lt;em&gt;cheapest&lt;/em&gt; way to get your software done.&lt;/p&gt;


	&lt;p&gt;If you go out hunting for the cheap solution, then you&amp;#8217;re going to end up paying more, and losing time.  Software is one of those things that costs a fortune to write well, and double that to write poorly.  If you go for cheap, you&amp;#8217;re going to pay double; and maybe even triple.&lt;/p&gt;</description>
      <pubDate>Mon, 01 Feb 2010 16:17:00 -0600</pubDate>
      <guid isPermaLink="false">urn:uuid:85351364-b4f5-4faa-af8a-4fb1f604ecae</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2010/02/01/software-on-the-cheap</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Mocking Mocking and Testing Outcomes.</title>
      <description>&lt;p&gt;The number of mocking frameworks has proliferated in recent years.  This pleases me because it is a symptom that testing in general, and &lt;span class="caps"&gt;TDD&lt;/span&gt; in particular, have become prevalent enough to support a rich panoply of third-party products.&lt;/p&gt;


	&lt;p&gt;On the other hand, all frameworks carry a disease with them that I call &lt;em&gt;The Mount Everest Syndrome&lt;/em&gt;: &amp;#8220;I use it because it&amp;#8217;s there.&amp;#8221;  The more mocking frameworks that appear, the more I see them enthusiastically used.  Yet the prolific use of mocking frameworks is a rather serious design smell&amp;#8230;&lt;/p&gt;


	&lt;p&gt;Lately I have seen several books and articles that present &lt;span class="caps"&gt;TDD&lt;/span&gt; through the lens of a mocking framework.  If you were a newbie to &lt;span class="caps"&gt;TDD&lt;/span&gt;, these writings might give you the idea that &lt;span class="caps"&gt;TDD&lt;/span&gt; was defined by the use of mocking tools, rather than by the &lt;a href="http://butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd"&gt;disciplines&lt;/a&gt; of &lt;span class="caps"&gt;TDD&lt;/span&gt;.&lt;/p&gt;


	&lt;p&gt;So when should use use a mocking framework?  The answer is the same for any other framework.  You use a framework only when that framework will give you a significant advantage.&lt;/p&gt;


	&lt;p&gt;Why so austere?  Why shouldn&amp;#8217;t you use frameworks &amp;#8220;just because they are there&amp;#8221;?  Because frameworks &lt;em&gt;always&lt;/em&gt; come with a cost.  They must be learned by the author, and by all the readers.  They become part of the configuration and have to be maintained.  They must be tracked from version to version.  But perhaps the most significant reason is that once you have a hammer, everything starts to look like a nail.  The framework will put you into a constraining mindset that prevents you from seeing other, better solutions.&lt;/p&gt;


Consider, for example, this lovely bit of code that I&amp;#8217;ve been reviewing recently.  It uses the Moq framework to initialize a test double:
&lt;pre&gt;&lt;code&gt;
var vehicleMock = Mocks.Create&amp;lt;IClientVehicle&amp;gt;()
 .WithPersistentKey()
 .WithLogicalKey().WithLogicalName()
 .WithRentalSessionManager(rsm =&amp;gt;
    {
      var rs = Mocks.Create&amp;lt;IRentalSession&amp;gt;();
      rsm.Setup(o =&amp;gt; o.GetCurrentSession()).Returns(rs.Object);
      rsm.Setup(o =&amp;gt;
       o.GetLogicalKeyOfSessionMember(It.IsAny&amp;lt;string&amp;gt;(),
        It.IsAny&amp;lt;int&amp;gt;())).Returns("Rental");
    })
 .AddVehicleMember&amp;lt;IRoadFactory&amp;gt;()
 .AddVehicleMember&amp;lt;IRoadItemFactory&amp;gt;(rf =&amp;gt; rf.Setup(t =&amp;gt; 
    t.CreateItems(It.IsAny&amp;lt;IRoad&amp;gt;())).Returns(pac))
 .AddVehicleMember&amp;lt;ILegacyCorporateRental&amp;gt;()
 .AddVehicleMember&amp;lt;IRentalStation&amp;gt;(
    m =&amp;gt; m.Setup(k =&amp;gt; k.Facility.FacilityID).Returns(0))
 .AddVehicleMember&amp;lt;IRoadManager&amp;gt;(m=&amp;gt;
    m.Setup(k=&amp;gt;k.GetRoundedBalanceDue(25,It.IsAny&amp;lt;IRoad&amp;gt;())).Returns(25));
&lt;/code&gt;&lt;/pre&gt;
Some of you might think I&amp;#8217;m setting up a straw-man.  I&amp;#8217;m not.  I realize that bad code can be written in any language or framework, and that you can&amp;#8217;t blame the language or framework for bad code.  
&lt;p/&gt;&lt;p/&gt;
The point I am making is that code like this was &lt;em&gt;the way&lt;/em&gt; that all unit tests in this application were written.  The team was new to &lt;span class="caps"&gt;TDD&lt;/span&gt;, and they got hold of a tool, and perhaps read a book or article, and decided that &lt;span class="caps"&gt;TDD&lt;/span&gt; was done by using a mocking tool.  This team is not the first team I&amp;#8217;ve seen who have fallen into this trap.  In fact, I think that the &lt;span class="caps"&gt;TDD&lt;/span&gt; industry as a whole has fallen into this trap to one degree or another.

	&lt;p&gt;Now don&amp;#8217;t get me wrong.  I like mocking tools.  I use them in Ruby, Java, and .Net. I think they provide a convenient way to make test-doubles in situations where more direct means are difficult.&lt;/p&gt;


For example, I recently wrote the following unit test in FitNesse using the Mockito framework.  
&lt;pre&gt;&lt;code&gt;
  @Before
  public void setUp() {
    manager = mock(GSSManager.class);
    properties = new Properties();
  }

  @Test
  public void credentialsShouldBeNullIfNoServiceName() throws Exception {
    NegotiateAuthenticator authenticator = 
      new NegotiateAuthenticator(manager, properties);
    assertNull(authenticator.getServerCredentials());
    verify(manager, never()).createName(
      anyString(), (Oid) anyObject(), (Oid) anyObject());
  }
&lt;/code&gt;&lt;/pre&gt;
The first line in the &lt;code&gt;setUp&lt;/code&gt; function is lovely.  It&amp;#8217;s kind of hard to get prettier than that.  Anybody reading it understands that &lt;code&gt;manager&lt;/code&gt; will be a mock of the &lt;code&gt;GSSManager&lt;/code&gt; class.  
&lt;p/&gt;&lt;p/&gt;
It&amp;#8217;s not too hard to understand the test itself.  Apparently we are happy to have the &lt;code&gt;manager&lt;/code&gt; be a dummy object with the constraint that &lt;code&gt;createName&lt;/code&gt; is never called by &lt;code&gt;NegotiateAuthenticator&lt;/code&gt;.  The &lt;code&gt;anyString()&lt;/code&gt; and &lt;code&gt;anyObject()&lt;/code&gt; calls are pretty self explanatory.

	&lt;p&gt;On the other hand, I wish I could have said this:&lt;/p&gt;


	&lt;p&gt;&lt;code&gt;assertTrue(manager.createNameWasNotCalled());&lt;/code&gt;&lt;/p&gt;


	&lt;p&gt;That statement does not require my poor readers to understand anything about Mockito.  Of course it does require me to hand-roll a manager mock.  Would that be hard?  Let&amp;#8217;s try.&lt;/p&gt;


First I need to create a dummy.  
&lt;pre&gt;&lt;code&gt;
  private class MockGSSManager extends GSSManager {
    public Oid[] getMechs() {
      return new Oid[0];
    }

    public Oid[] getNamesForMech(Oid oid) throws GSSException {
      return new Oid[0];
    }

    public Oid[] getMechsForName(Oid oid) {
      return new Oid[0];
    }

    public GSSName createName(String s, Oid oid) throws GSSException {
      return null;
    }

    public GSSName createName(byte[] bytes, Oid oid) throws GSSException {
      return null;
    }

    public GSSName createName(String s, Oid oid, Oid oid1) throws GSSException {
      return null;
    }

    public GSSName createName(byte[] bytes, Oid oid, Oid oid1) throws GSSException {
      return null;
    }

    public GSSCredential createCredential(int i) throws GSSException {
      return null;
    }

    public GSSCredential createCredential(GSSName gssName, int i, Oid oid, int i1) throws GSSException {
      return null;
    }

    public GSSCredential createCredential(GSSName gssName, int i, Oid[] oids, int i1) throws GSSException {
      return null;
    }

    public GSSContext createContext(GSSName gssName, Oid oid, GSSCredential gssCredential, int i) throws GSSException {
      return null;
    }

    public GSSContext createContext(GSSCredential gssCredential) throws GSSException {
      return null;
    }

    public GSSContext createContext(byte[] bytes) throws GSSException {
      return null;
    }

    public void addProviderAtFront(Provider provider, Oid oid) throws GSSException {
    }

    public void addProviderAtEnd(Provider provider, Oid oid) throws GSSException {
    }
  }
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;&amp;#8220;Oh, ick!&amp;#8221; you say.  Yes, I agree it&amp;#8217;s a lot of code.  On the other hand, it took me just a single keystroke on my &lt;span class="caps"&gt;IDE&lt;/span&gt; to generate all those dummy methods.  (In IntelliJ it was simply command-I to implement all unimplemented methods.)  So it wasn&amp;#8217;t particularly hard.  And, of course, I can put this code somewhere where nobody had to look at it unless they want to.  It has the advantage that anybody who knows Java can understand it, and can look right at the methods to see what they are returning.  No &amp;#8220;special&amp;#8221; knowledge of the mocking framework is necessary.&lt;/p&gt;


Next, let&amp;#8217;s&amp;#8217; make a test double that does precisely what this test needs.
&lt;pre&gt;&lt;code&gt;
  private class GSSManagerSpy extends MockGSSManager {
    public boolean createNameWasCalled;

    public GSSName createName(String s, Oid oid) throws GSSException {
      createNameWasCalled = true;
      return null;
    }
  }
&lt;/code&gt;&lt;/pre&gt;
Well, that just wasn&amp;#8217;t that hard.  It&amp;#8217;s really easy to understand too. 

Now, let&amp;#8217;s rewrite the test.
&lt;pre&gt;&lt;code&gt;
  @Test
  public void credentialsShouldBeNullIfNoServiceNameWithHandRolledMocks() throws Exception {
    NegotiateAuthenticator authenticator = new NegotiateAuthenticator(managerSpy, properties);
    assertNull(authenticator.getServerCredentials());
    assertFalse(managerSpy.createNameWasCalled);
  }
&lt;/code&gt;&lt;/pre&gt;
Well, that test is just a &lt;em&gt;load&lt;/em&gt; easier to read than &lt;code&gt;verify(manager, never()).createName(anyString(), (Oid) anyObject(), (Oid) anyObject());&lt;/code&gt;.
&lt;p/&gt;&lt;p/&gt;
&amp;#8220;But Uncle Bob!&amp;#8221; I hear you say.  &amp;#8220;That scenario is too simple.  What if there were lots of dependencies and things&amp;#8230;&amp;#8221; 

I&amp;#8217;m glad you asked that question, because the very next test is just such a situation.  
&lt;pre&gt;&lt;code&gt;
  @Test
  public void credentialsShouldBeNonNullIfServiceNamePresent() throws Exception {
    properties.setProperty("NegotiateAuthenticator.serviceName", "service");
    properties.setProperty("NegotiateAuthenticator.serviceNameType", "1.1");
    properties.setProperty("NegotiateAuthenticator.mechanism", "1.2");
    GSSName gssName = mock(GSSName.class);
    GSSCredential gssCredential = mock(GSSCredential.class);
    when(manager.createName(anyString(), (Oid) anyObject(), (Oid) anyObject())).thenReturn(gssName);
    when(manager.createCredential((GSSName) anyObject(), anyInt(), (Oid) anyObject(), anyInt())).thenReturn(gssCredential);
    NegotiateAuthenticator authenticator = new NegotiateAuthenticator(manager, properties);
    Oid serviceNameType = authenticator.getServiceNameType();
    Oid mechanism = authenticator.getMechanism();
    verify(manager).createName("service", serviceNameType, mechanism);
    assertEquals("1.1", serviceNameType.toString());
    assertEquals("1.2", mechanism.toString());
    verify(manager).createCredential(gssName, GSSCredential.INDEFINITE_LIFETIME, mechanism, GSSCredential.ACCEPT_ONLY);
    assertEquals(gssCredential, authenticator.getServerCredentials());
  }
&lt;/code&gt;&lt;/pre&gt;
Now I&amp;#8217;ve got three test doubles that interact with each other; and I am verifying that the code under test is manipulating them all correctly.  I &lt;em&gt;could&lt;/em&gt; create hand-rolled test doubles for this; but the wiring between them would be scattered in the various test-double derivatives.  I&amp;#8217;d also have to write a significant number of accessors to get the values of the arguments to &lt;code&gt;createName&lt;/code&gt; and &lt;code&gt;createCredential&lt;/code&gt;.  In short, the hand-rolled test-double code would be harder to understand than the Mockito code.  The Mockito code puts the whole story in one simple test method rather than scattering it hither and yon in a plethora of little derivatives.
&lt;p/&gt;&lt;p/&gt;
What&amp;#8217;s more, since it&amp;#8217;s clear that I should use a mocking framework for this test, I think I should be consistent and use if for &lt;em&gt;all&lt;/em&gt; the tests in this file.   So the hand-rolled &lt;code&gt;MockGSSManager&lt;/code&gt; and &lt;code&gt;ManagerSpy&lt;/code&gt; are history.

	&lt;p&gt;&amp;#8220;But Uncle Bob, aren&amp;#8217;t we always going to have dependencies like that?  So aren&amp;#8217;t we &lt;em&gt;always&lt;/em&gt; going to have to use a mocking framework?&amp;#8221;&lt;/p&gt;


	&lt;p&gt;That, my dear reader, is the real point of this blog.  The answer to that salient questions is a profound: &amp;#8220;&lt;strong&gt;No!&lt;/strong&gt;&amp;#8220;&lt;/p&gt;


	&lt;p&gt;Why did I have to use Mockito for these tests?  Because the number of objects in play was large.  The module under test (&lt;code&gt;NegotiateAuthenticator&lt;/code&gt;) used &lt;code&gt;GSSName&lt;/code&gt;, &lt;code&gt;GSSCredential&lt;/code&gt;, and &lt;code&gt;GSSManager&lt;/code&gt;.  In other words the coupling between the module under test and the test itself was high.  (I see lightbulbs above some of your heads.) That&amp;#8217;s right, boys and girls, we don&amp;#8217;t want coupling to be high!&lt;/p&gt;


	&lt;p&gt;It is the high coupling between modules and tests that creates the need for a mocking framework.  This high coupling is also the cause of the dreaded &amp;#8220;Fragile Test&amp;#8221; problem.  How many tests break when you change a module?  If the number is high, then the coupling between your modules and tests in high.  Therefore, I conclude that those systems that make prolific use of mocking frameworks are likely to suffer from fragile tests.&lt;/p&gt;


	&lt;p&gt;Of the 277 unit test files in FitNesse, only 11 use Mockito.  The reason for small number is two-fold.  First, we test outcomes more often than we test mechanisms.  That means we test how a small group of classes behaves, rather than testing the dance of method calls between those classes.  The second reason is that our test doubles have no middle class.  They are either very simple stubs and spies or they are moderately complex fakes.&lt;/p&gt;


	&lt;p&gt;Testing outcomes is a traditional decoupling technique.  The test doesn&amp;#8217;t care &lt;em&gt;how&lt;/em&gt; the end result is calculated, so long as the end result is correct.  There may be a dance of several method calls between a few different objects; but the test is oblivious since it only checks the answer.  Therefore the tests are not strongly coupled to the solution and are not fragile.&lt;/p&gt;


	&lt;p&gt;Keeping middle-class test doubles (i.e. Mocks) to a minimum is another way of decoupling.  Mocks, by their very nature, are coupled to mechanisms instead of outcomes.  Mocks, or the setup code that builds them, have deep knowledge of the inner workings of several different classes.  That knowledge is the very definition of high-coupling.&lt;/p&gt;


	&lt;p&gt;What is a &amp;#8220;moderately complex fake&amp;#8221; and why does it help to reduce coupling?  One example within FitNesse is &lt;code&gt;MockSocket&lt;/code&gt;.  (The name of this class is historical.  Nowadays it should be called &lt;code&gt;FakeSocket&lt;/code&gt;.)  This class derives from &lt;code&gt;Socket&lt;/code&gt; and implements all its methods either to remember what was sent to the socket, or to allow a user to read some canned data.  This is a &amp;#8220;fake&amp;#8221; because it simulates the behavior of a socket.  It is not a mock because it has no coupling to any mechanisms.  You don&amp;#8217;t ask it whether it succeeded or failed, you ask it to send or recieve a string.  This allows our unit tests to test outcomes rather than mechanisms.&lt;/p&gt;


	&lt;p&gt;The moral of this story is that the point at which you start to really need a mocking framework is the very point at which the coupling between your tests and code is getting too high.  There are times when you can&amp;#8217;t avoid this coupling, and those are the times when mocking frameworks &lt;em&gt;really&lt;/em&gt; pay off.  However, you should strive to keep the coupling between your code and tests low enough that you don&amp;#8217;t need to use the mocking framework very often.&lt;/p&gt;


	&lt;p&gt;You do this by testing outcomes instead of mechanisms.&lt;/p&gt;</description>
      <pubDate>Sat, 23 Jan 2010 11:32:00 -0600</pubDate>
      <guid isPermaLink="false">urn:uuid:b863ec60-399c-430f-8e82-78e54684cae4</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2010/01/23/mocking-mocking-and-testing-outcomes</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Design Principles</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Dependency Injection Inversion</title>
      <description>&lt;p&gt;Dependency Injection is all the rage.  There are several frameworks that will help you inject dependencies into your system.  Some use &lt;span class="caps"&gt;XML&lt;/span&gt; (God help us) to specify those dependencies.  Others use simple statements in code.  In either case, the goal of these frameworks is to help you create instances without having to resort to &lt;code&gt;new&lt;/code&gt; or Factories.&lt;/p&gt;


	&lt;p&gt;I think these frameworks are great tools.  But I also think you should carefully restrict how and where you use them.&lt;/p&gt;


	&lt;p&gt;Consider, for example, this simple example using Google&amp;#8217;s Guice framework.&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
 public class BillingApplication {
   public static void main(String[] args) {
    Injector injector = Guice.createInjector(new BillingModule());
    BillingService billingService = injector.getInstance(BillingService.class);
    billingService.processCharge(2034, "Bob");
  }
 }
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;My goal is to create an instance of &lt;code&gt;BillingService&lt;/code&gt;.  To do this, I first get an &lt;code&gt;Injector&lt;/code&gt; from Guice.  Then I use the &lt;code&gt;injector&lt;/code&gt; to get an instance of my &lt;code&gt;BillingService&lt;/code&gt; class.  What&amp;#8217;s so great about this?  Well, take a look at the constructor of the &lt;code&gt;BillingService&lt;/code&gt; class.&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
class BillingService {
  private CreditCardProcessor processor;
  private TransactionLog transactionLog;

  @Inject
  BillingService(CreditCardProcessor processor, TransactionLog transactionLog) {
    this.processor = processor;
    this.transactionLog = transactionLog;
  }

  public void processCharge(int amount, String id) {
    boolean approval = processor.approve(amount, id);
    transactionLog.log(
      String.format("Transaction by %s for %d %s",
      id, amount, approvalCode(approval)));
  }

  private String approvalCode(boolean approval) {
    return approval?"approved":"denied";
  }
}

&lt;/code&gt;&lt;/pre&gt;
Oh ho!  The &lt;code&gt;BillingService&lt;/code&gt; constructor requires two arguments!  A &lt;code&gt;CreditCardProcessor&lt;/code&gt; and a &lt;code&gt;TransactionLog&lt;/code&gt;.  How was the &lt;code&gt;main&lt;/code&gt; program able to create an instance of &lt;code&gt;BillingService&lt;/code&gt; without those two arguments?  That&amp;#8217;s the magic of Guice (and of all Dependency Injection frameworks).  Guice knows that the &lt;code&gt;BillingService&lt;/code&gt; needs those two arguments, and it knows how to create them.  Did you see that funky &lt;code&gt;@Inject&lt;/code&gt; attribute above the constructor?  That&amp;#8217;s how it got connected into Guice.

	&lt;p&gt;And here&amp;#8217;s the magic module that tells Guice how to create the arguments for the &lt;code&gt;BillingService&lt;/code&gt;&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
public class BillingModule extends AbstractModule {
  protected void configure() {
    bind(TransactionLog.class).to(DatabaseTransactionLog.class);
    bind(CreditCardProcessor.class).to(MyCreditCardProcessor.class);
  }
}

&lt;/code&gt;&lt;/pre&gt;
Clever these Google-folk!  The two &lt;code&gt;bind&lt;/code&gt; functions tell Guice that whenever we need an instance of a &lt;code&gt;TransactionLog&lt;/code&gt; it should use an instance of &lt;code&gt;DatabaseTransactionLog&lt;/code&gt;.  Whenever it needs a &lt;code&gt;CreditCardProcessor&lt;/code&gt; it should use an instance of &lt;code&gt;MyCreditCardProcessor&lt;/code&gt;.

	&lt;p&gt;Isn&amp;#8217;t that cool!  Now you don&amp;#8217;t have to build factories.  You don&amp;#8217;t have to use &lt;code&gt;new&lt;/code&gt;.  You just tell Guice how to map interfaces to implementations, and which constructors to inject those implementations in to, and then call &lt;code&gt;Injector.getInstance(SomeClass.class);&lt;/code&gt; and voila!  You have your instance automatically constructed for you.  Cool.&lt;/p&gt;


	&lt;p&gt;Well, yes it&amp;#8217;s cool.  On the other hand, consider this code:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
public class BillingApplicationNoGuice {
  public static void main(String[] args) {
    CreditCardProcessor cp = new MyCreditCardProcessor();
    TransactionLog tl = new DatabaseTransactionLog();
    BillingService bs = new BillingService(cp, tl);
    bs.processCharge(9000, "Bob");
  }
}

&lt;/code&gt;&lt;/pre&gt; 
Why is this worse?  It seems to me it&amp;#8217;s better.

	&lt;p&gt;&lt;em&gt;But Uncle Bob&lt;/em&gt;, you&amp;#8217;ve violated &lt;span class="caps"&gt;DIP&lt;/span&gt; by creating concrete instances!&lt;/p&gt;


	&lt;p&gt;True, but you have to mention concrete instances somewhere.  &lt;code&gt;main&lt;/code&gt; seems like a perfectly good place for that.  Indeed, it seems better than hiding the concrete references in &lt;code&gt;BillingModule&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;I don&amp;#8217;t want a bunch of secret modules with &lt;code&gt;bind&lt;/code&gt; calls scattered all around my code.  I don&amp;#8217;t want to have to hunt for the particular &lt;code&gt;bind&lt;/code&gt; call for the &lt;code&gt;Zapple&lt;/code&gt; interface when I&amp;#8217;m looking at some module.  I want to know where all the instances are created.&lt;/p&gt;


	&lt;p&gt;&lt;em&gt;But Uncle Bob&lt;/em&gt;, You&amp;#8217;d know where they are because this is a &lt;em&gt;Guice&lt;/em&gt; application.&lt;/p&gt;


	&lt;p&gt;I don&amp;#8217;t want to write a &lt;em&gt;Guice&lt;/em&gt; application.  Guice is a framework, and I don&amp;#8217;t want framework code smeared all through my application.  I want to keep frameworks nicely decoupled and at arms-length from the main body of my code.  I don&amp;#8217;t want to have &lt;code&gt;@Inject&lt;/code&gt; attributes everywhere and &lt;code&gt;bind&lt;/code&gt; calls hidden under rocks.&lt;/p&gt;


	&lt;p&gt;&lt;em&gt;But Uncle Bob&lt;/em&gt;, What if I want to get an instance of &lt;code&gt;BillingService&lt;/code&gt; from deep in the bowels of my application?  With Guice I can just say &lt;code&gt;injector.getInstance(BillingService.class);&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;True, but I don&amp;#8217;t want to have &lt;code&gt;createInstance&lt;/code&gt; calls scattered all through my code.  I don&amp;#8217;t want Guice to be poured all over my app. I want my app to be clean, not soaked in Guice.&lt;/p&gt;


	&lt;p&gt;&lt;em&gt;But Uncle Bob&lt;/em&gt;, That means I have to use &lt;code&gt;new&lt;/code&gt; or factories, or pass globals around.&lt;/p&gt;


	&lt;p&gt;You think the &lt;code&gt;injector&lt;/code&gt; is not a global?  You think &lt;code&gt;BillingService.class&lt;/code&gt; is not a global?  There will always be globals to deal with.  You can&amp;#8217;t write systems without them.  You just need to manage them nicely.&lt;/p&gt;


	&lt;p&gt;And, no, I don&amp;#8217;t have to use &lt;code&gt;new&lt;/code&gt; everywhere, and I don&amp;#8217;t need factories.  I can do something as simple as:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
public class BillingApplicationNoGuice {
  public static void main(String[] args) {
    CreditCardProcessor cp = new MyCreditCardProcessor();
    TransactionLog tl = new DatabaseTransactionLog();
    BillingService.instance = new BillingService(cp, tl);

    // Deep in the bowels of my system.
    BillingService.instance.processCharge(9000, "Bob");
  }
}

&lt;/code&gt;&lt;/pre&gt;
&lt;em&gt;But Uncle Bob&lt;/em&gt;, what if you want to create many instances of &lt;code&gt;BillingService&lt;/code&gt; rather than just that one singleton?

	&lt;p&gt;Then I&amp;#8217;d use a factory, like so:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
public class BillingApplication {
   public static void main(String[] args) {
    Injector injector = Guice.createInjector(new BillingModule());
    BillingService.factory = new BillingServiceFactory(injector);

    // Deep in the bowels of my code.
    BillingService billingService = BillingService.factory.make();
    billingService.processCharge(2034, "Bob");
  }
}

&lt;/code&gt;&lt;/pre&gt;
&lt;em&gt;But Uncle Bob&lt;/em&gt;, I thought the whole idea was to avoid factories!

	&lt;p&gt;Hardly.  After all, Guice is just a big factory.  But you didn&amp;#8217;t let me finish.  Did you notice that I passed the Guice injector into the factory?  Here&amp;#8217;s the factory implementation.&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
public class BillingServiceFactory extends AbstractModule {
  private Injector injector;

  public BillingServiceFactory(Injector injector) {
    this.injector = injector;
  }

  protected void configure() {
    bind(TransactionLog.class).to(DatabaseTransactionLog.class);
    bind(CreditCardProcessor.class).to(MyCreditCardProcessor.class);
  }

  public BillingService make() {
    return injector.getInstance(BillingService.class);
  }
}

&lt;/code&gt;&lt;/pre&gt;
I like this because now all the Guice is in one well understood place.  I don&amp;#8217;t have Guice all over my application.  Rather, I&amp;#8217;ve got factories that contain the Guice.  Guicey factories that keep the Guice from being smeared all through my application.  

	&lt;p&gt;What&amp;#8217;s more, if I wanted to replace Guice with some other DI framework, I know exactly what classes would need to change, and how to change them.  So I&amp;#8217;ve kept Guice uncoupled from my application.&lt;/p&gt;


	&lt;p&gt;Indeed, using this form allows me to defer using Guice until I think it&amp;#8217;s necessary.  I can just build the factories the good old &lt;span class="caps"&gt;GOF&lt;/span&gt; way until the need to externalize dependencies emerges.&lt;/p&gt;


	&lt;p&gt;&lt;em&gt;But Uncle Bob&lt;/em&gt;, don&amp;#8217;t you think Dependency Injection is a good thing?&lt;/p&gt;


	&lt;p&gt;Of course I do.  Dependency Injection is just a special case of Dependency Inversion.  I think Dependency Inversion is so important that I want to invert the dependencies on Guice!  I don&amp;#8217;t want lots of concrete Guice dependencies scattered through my code.&lt;/p&gt;


	&lt;p&gt;&lt;span class="caps"&gt;BTW&lt;/span&gt;, did you notice that I was using Dependency Injection even when I wasn&amp;#8217;t using Guice at all?  This is nice and simple &lt;em&gt;manual&lt;/em&gt; dependency injection.  Here&amp;#8217;s that code again in case you don&amp;#8217;t want to look back:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;

public class BillingApplicationNoGuice {
  public static void main(String[] args) {
    CreditCardProcessor cp = new MyCreditCardProcessor();
    TransactionLog tl = new DatabaseTransactionLog();
    BillingService bs = new BillingService(cp, tl);
    bs.processCharge(9000, "Bob");
  }
}

&lt;/code&gt;&lt;/pre&gt;
Dependency Injection doesn&amp;#8217;t require a framework; it just requires that you invert your dependencies and then construct and pass your arguments to deeper layers.   Consider, for example, that the following test works just fine in &lt;em&gt;all&lt;/em&gt; the cases above.  It does not rely on Guice, it only relies on the fact that dependencies were inverted and can be injected into &lt;code&gt;BillingService&lt;/code&gt;

&lt;pre&gt;&lt;code&gt;

public class BillingServiceTest {
  private LogSpy log;

  @Before
  public void setup() {
    log = new LogSpy();
  }

  @Test
  public void approval() throws Exception {
    BillingService bs = new BillingService(new Approver(), log);
    bs.processCharge(9000, "Bob");
    assertEquals("Transaction by Bob for 9000 approved", log.getLogged());
  }

  @Test
  public void denial() throws Exception {
    BillingService bs = new BillingService(new Denier(), log);
    bs.processCharge(9000, "Bob");
    assertEquals("Transaction by Bob for 9000 denied", log.getLogged());    
  }
}

class Approver implements CreditCardProcessor {
  public boolean approve(int amount, String id) {
    return true;
  }
}

class Denier implements CreditCardProcessor {
  public boolean approve(int amount, String id) {
    return false;
  }
}

class LogSpy implements TransactionLog {
  private String logged;

  public void log(String s) {
    logged = s;
  }

  public String getLogged() {
    return logged;
  }
}

&lt;/code&gt;&lt;/pre&gt;
Also notice that I rolled my own Test Doubles (we used to call them mocks, but we&amp;#8217;re not allowed to anymore.)  It would have been tragic to use a mocking framework for such a simple set of tests.

	&lt;p&gt;Most of the time the best kind of Dependency Injection to use, is the manual kind.  Externalized dependency injection of the kind that Guice provides is appropriate for those classes that you &lt;em&gt;know&lt;/em&gt; will be extension points for your system.&lt;/p&gt;


	&lt;p&gt;But for classes that aren&amp;#8217;t obvious extension points, you will simply know the concrete type you need, and can create it at a relatively high level and inject it down as an interface to the lower levels.  If, one day, you find that you need to externalize that dependency, it&amp;#8217;ll be easy because you&amp;#8217;ve already inverted and injected it.&lt;/p&gt;</description>
      <pubDate>Sun, 17 Jan 2010 12:42:00 -0600</pubDate>
      <guid isPermaLink="false">urn:uuid:00f97566-88ff-41a0-a0b1-4baee8225dc0</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2010/01/17/dependency-injection-inversion</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Design Principles</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Archeological Dig</title>
      <description>&lt;p&gt;I was going through some old files today, and I stumbled upon some acetate slides from 1995.  They were entitled: &amp;#8220;Managing OO Projects&amp;#8221;.  Wow!  What a difference fifteen years makes!   (Or does it?) ...&lt;/p&gt;


	&lt;p&gt;In 1995-99 I was frequently asked to speak to managers about what a transition to OO (usually from C to C++) would do for (or to) them.  I would spend a half day to a day going over the issues, costs, and benefits.&lt;/p&gt;


	&lt;p&gt;One part of that talk (usually about 90 min) was a discussion about software process.  It was the process part of the talk that those acetate slides that I found described.&lt;/p&gt;


	&lt;p&gt;1995 was during the ascendency of Waterfall.  Waterfall thinking was king. &lt;span class="caps"&gt;RUP&lt;/span&gt; had not yet been conceived as an acronym.  And though Booch was beating the drum for incrementalism, most people (even many within Rational) were thinking in terms of six to eighteen month waterfalls.&lt;/p&gt;


	&lt;p&gt;So, &lt;a href="http://butunclebob.com/files/unclebob/Managing%20OO%20Projects.pdf"&gt;here&lt;/a&gt; are the slides that I uncovered deep within an old filing cabinet.  I scanned them in.  They were produced on a Macintosh using the old &amp;#8220;More&amp;#8221; program.  (Where is that program now?  It was &lt;em&gt;so&lt;/em&gt; good.)&lt;/p&gt;


Go ahead and read them now.  Then come back here and continue&amp;#8230;
&lt;hr&gt;
What struck me about those slides was the consistency of the message with today.  It was all about iterative development.  Small iterations (though I never deigned to define the length in the slides, I frequently told people 2 weeks), measured results, etc. etc.  Any Agile evangelist could use those slides today.  He or she would have to dance quickly around a few statements, but overall the message has not shifted very much.

	&lt;p&gt;What&amp;#8217;s even more interesting is the coupling between the process, and OO.  The slides talk a lot about dependency management and dependency structure.  There are hints of the &lt;span class="caps"&gt;SOLID&lt;/span&gt; principles contained in those slides.  (Indeed several of the principles had already been identified by that time.)  This coupling between process and software structure was a harbinger of the current craftsmanship/clean-code movement.&lt;/p&gt;


	&lt;p&gt;Of course the one glaring omission from these slides is &lt;span class="caps"&gt;TDD&lt;/span&gt;.  That makes me think that &lt;span class="caps"&gt;TDD&lt;/span&gt; was the true catalyst of change, and the bridge that conveyed our industry from then to now.&lt;/p&gt;


	&lt;p&gt;Anyway, I guess the more things change, the more they stay the same.&lt;/p&gt;


	&lt;p&gt;Comments please!&lt;/p&gt;</description>
      <pubDate>Wed, 11 Nov 2009 10:39:00 -0600</pubDate>
      <guid isPermaLink="false">urn:uuid:2719dd93-f02d-4cbb-9850-265f68fbfb65</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2009/11/11/archeological-dig</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Software Craftsmanship</category>
      <category>Agile Methods</category>
      <category>Design Principles</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Excuse me sir, What Planet is this?</title>
      <description>&lt;p&gt;Update 12 hours later.&lt;/p&gt;


	&lt;p&gt;I&amp;#8217;m not very proud of this blog (or as one commenter correctly called it &amp;#8220;blart&amp;#8221;).  It is derisive, sneering, and petulant.  It is unprofessional.  I guess I was having a bad morning.  I slipped.  I didn&amp;#8217;t check with my green band.&lt;/p&gt;


	&lt;p&gt;So I apologize to the audience at large, and to Cashto.  You should expect better from me.&lt;/p&gt;


	&lt;p&gt;I thought about pulling the blog down; but I think I&amp;#8217;ll leave it up here as an example of how &lt;i&gt;not&lt;/i&gt; to write a blog.&lt;/p&gt;


	&lt;p&gt;Some folks on twitter have been asking me to respond to this &lt;a href="http://blogs.msdn.com/cashto/archive/2009/03/31/it-s-ok-not-to-write-unit-tests.aspx"&gt;blough&lt;/a&gt; (don&amp;#8217;t bother to read it right now, I&amp;#8217;ll give you the capsule summary below.  Read it later if you must).  It&amp;#8217;s a typical screed complete with all the usual complaints, pejoratives, and illogic.  Generally I don&amp;#8217;t respond to blarts like this because I don&amp;#8217;t imagine that any readers take them very seriously.  But it appears that this blelch has made the twitter rounds and that I&amp;#8217;m going to have to say &lt;em&gt;something&lt;/em&gt;.&lt;/p&gt;


	&lt;p&gt;Here are the writer&amp;#8217;s main points:&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;He likens unit tests to training wheels and says you can&amp;#8217;t use them to win the &lt;em&gt;Tour de France&lt;/em&gt;. 
	&lt;ul&gt;
	&lt;li&gt;I think winning the &lt;em&gt;Tour de France&lt;/em&gt; has much more to do with self-discipline than he imagines it does.  I mean it&amp;#8217;s not really just as simple as: &amp;#8220;Get on a bike and ride like hell!&amp;#8221;&lt;/li&gt;
	&lt;/ul&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;He says testing is popular amongst college students
	&lt;ul&gt;
	&lt;li&gt;I&amp;#8217;d like to see his data!&lt;/li&gt;
	&lt;/ul&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;He goes on to say: (cue John Cleese): &amp;#8220;(ahem) unit tests lose their effectiveness around level four of the &lt;em&gt;Dreyfus model of skill acquisition&amp;#8221;.&lt;/em&gt;  
	&lt;ul&gt;
	&lt;li&gt;(blank stunned stare).  Is this a joke?  All false erudition aside, &lt;span class="caps"&gt;WTF&lt;/span&gt; is he talking about?&lt;/li&gt;
	&lt;/ul&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;He says that unit tests &lt;em&gt;don&amp;#8217;t&lt;/em&gt; give us confidence in refactoring because they &lt;strong&gt;over-specify&lt;/strong&gt; behavior and are too &lt;strong&gt;fine-grained&lt;/strong&gt;.  
	&lt;ul&gt;
	&lt;li&gt;He apparently prefers hyphenations to green bars.&lt;/li&gt;
	&lt;/ul&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;He says they mostly follow the &amp;#8220;happy path&amp;#8221; and therefore don&amp;#8217;t find bugs.  
	&lt;ul&gt;
	&lt;li&gt;Maybe when &lt;em&gt;he&lt;/em&gt; writes them!  This is a &lt;em&gt;big&lt;/em&gt; clue that the author can&amp;#8217;t spell &lt;span class="caps"&gt;TDD&lt;/span&gt;.&lt;/li&gt;
	&lt;/ul&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;He complains about Jester 
	&lt;ul&gt;
	&lt;li&gt;without getting the joke!&lt;/li&gt;
	&lt;/ul&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;He says unit tests &amp;#8220;encourage some pretty questionable practices.&amp;#8221;  He flings a few design principles around and says that unit testing doesn&amp;#8217;t help with them. 
	&lt;ul&gt;
	&lt;li&gt;as the author, editor, and/or advocate of many of those principles; I have a slightly different view.&lt;/li&gt;
	&lt;/ul&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;He says that &amp;#8220;many are starting to discover that functional programming teaches far better design principles than unit testing ever will&amp;#8221;  
	&lt;ul&gt;
	&lt;li&gt;Oh no!  Not the old &amp;#8220;My language teaches design.&amp;#8221; claim.  We&amp;#8217;ve heard it all before.  They said it about C++, Java, &lt;span class="caps"&gt;COM&lt;/span&gt; (?!), etc&amp;#8230;  The lesson of the &amp;#8216;90s?  &lt;em&gt;Languages don&amp;#8217;t teach design&lt;/em&gt;.  You can make a mess in &lt;em&gt;any&lt;/em&gt; language.&lt;/li&gt;
	&lt;/ul&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;He says: &amp;#8220;tests can have negative &lt;span class="caps"&gt;ROI&lt;/span&gt;. Not only do they cost a lot to write, they&amp;#8217;re fragile, they&amp;#8217;re always broken, they get in the way of your refactoring, they&amp;#8217;re always having you chase down bogus failures, and the only way to get anything done is to ignore them.&amp;#8221;  
	&lt;ul&gt;
	&lt;li&gt;In one of my favorite episodes of Dr. Who, Tom Baker exits the Tardis, walks up to someone on the street and says: &amp;#8220;Excuse me sir, what planet is this?&amp;#8221;&lt;/li&gt;
	&lt;/ul&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;He says: &amp;#8220;What I&amp;#8217;m saying is that it&amp;#8217;s okay if you don&amp;#8217;t write unit tests for everything. You probably have already suspected this for a long time, but now you know. I don&amp;#8217;t want you to feel guilty about it any more.&amp;#8221; 
	&lt;ul&gt;
	&lt;li&gt;Translation: &amp;#8220;&lt;i&gt;I&lt;/i&gt; don&amp;#8217;t want to feel guilty about it anymore so I&amp;#8217;m going to try to convince you&amp;#8230;&amp;#8221;  I sincerely doubt this author has &lt;em&gt;your&lt;/em&gt; best interests at heart.&lt;/li&gt;
	&lt;/ul&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;He says: &amp;#8220;Debugging is easy, at least in comparison to writing all those tedious tests.&amp;#8221; 
	&lt;ul&gt;
	&lt;li&gt;Refer back to the Dr. Who quote.&lt;/li&gt;
	&lt;/ul&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;&lt;br&gt;
&lt;br&gt;
To quote Barack Obama: &amp;#8220;Enough!&amp;#8221;&lt;/p&gt;


	&lt;p&gt;Has this guy ever done &lt;span class="caps"&gt;TDD&lt;/span&gt;?  I rather doubt it.  Or if he did, he was so inept at it that his tests were &amp;#8220;fragile&amp;#8221;, &amp;#8220;always broken&amp;#8221;, and &amp;#8220;in the way of refactoring&amp;#8221;.  I think he should give it another try and this time spend a bit more time on test design.&lt;/p&gt;


	&lt;p&gt;Perhaps he&amp;#8217;s one of those guys who thought that unit tests were best written &lt;em&gt;after&lt;/em&gt; the code.  Certainly his list of complains makes a lot of sense in that light.  Hint:  If you want to fail at unit testing, write them last.&lt;/p&gt;


	&lt;p&gt;The bottom line is that the guy probably had a bad experience writing unit tests.  He&amp;#8217;s tired of writing them and wants to write fewer of them.  He&amp;#8217;d rather debug.  He thinks he can refactor without tests (which is definitively false).  He thinks he can go faster by writing fewer tests.  Fine, that&amp;#8217;s his choice. And he&amp;#8217;s found a rationalization to support his desires.  Great.&lt;/p&gt;


	&lt;p&gt;I predict that his results will not compare well with those who adopt the discipline of &lt;span class="caps"&gt;TDD&lt;/span&gt;.  I predict that after a few years he&amp;#8217;ll either change his mind, or go into management.&lt;/p&gt;


	&lt;p&gt;Oh, and to the author:  Gesundheit!&lt;/p&gt;</description>
      <pubDate>Thu, 05 Nov 2009 10:35:00 -0600</pubDate>
      <guid isPermaLink="false">urn:uuid:2a532aa7-e2ff-49b1-bfdf-38f1aa9fead9</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2009/11/05/its-ok-not-to-write-unit-tests-not</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Agile Methods</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Manual Mocking: Resisting the Invasion of Dots and Parentheses</title>
      <description>&lt;p&gt;The twittersphere has been all abuzz today because of something I tweeted early this morning (follow @unclebobmartin).  In my tweet I said that I hand-roll most of my own mock objects in Java, rather than using a mocking framework like &lt;a href="mockito.org"&gt;mockito&lt;/a&gt;.&lt;/p&gt;


	&lt;p&gt;The replies were numerous and vociferous.  Dave Astels poignantly stated that hand-rolling mocks is so 2001!&lt;/p&gt;


	&lt;p&gt;So why do I roll my own mocks?&lt;/p&gt;


Consider the following two tests:
&lt;pre&gt;
public class SelectorTest {
  private List&amp;lt;Object&amp;gt; list;

  @Before
  public void setup() {
    list = new ArrayList&amp;lt;Object&amp;gt;();
    list.add(new Object());
  }

  @Test
  public void falseMatcherShouldSelectNoElements_mockist() {
    Matcher&amp;lt;Object&amp;gt; falseMatcher = mock(Matcher.class);
    Selector&amp;lt;Object&amp;gt; selector = new Selector&amp;lt;Object&amp;gt;(falseMatcher);
    when(falseMatcher.match(anyObject())).thenReturn(false);
    List&amp;lt;Object&amp;gt; selection = selector.select(list);
    assertThat(selection.size(), equalTo(0));
  }

  @Test
  public void falseMatcherShouldSelectNoElements_classic() {
    Matcher&amp;lt;Object&amp;gt; falseMatcher = new FalseMatcher();
    Selector&amp;lt;Object&amp;gt; selector = new Selector&amp;lt;Object&amp;gt;(falseMatcher);
    List&amp;lt;Object&amp;gt; selection = selector.select(list);
    assertThat(selection.size(), equalTo(0));}

  private static class FalseMatcher implements Matcher&amp;lt;Object&amp;gt; {
    public boolean match(Object element) {
      return false;
    }
  }
}
&lt;/pre&gt;

	&lt;p&gt;The first test shows the really cool power of &lt;a href="mockito.org"&gt;mockito&lt;/a&gt; (which is my current favorite in the menagerie of java mocking frameworks).  Just in case you can&amp;#8217;t parse the syntax, let me describe it for you:&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;falseMatcher is assigned the return value of the &amp;#8220;mock&amp;#8221; function.  This is a very cool function that takes the argument class and builds a new stubbed object that derives from it.  In mockito, the argument can be a class or an interface.  Cool!&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Now don&amp;#8217;t get all panicy about the strange parenthetic syntax of the &amp;#8216;when&amp;#8217; statement.  The &amp;#8216;when&amp;#8217; statement simply tells the mock what to do when a method is called on it.  In this case it instructs the falseMatcher to return false when the &amp;#8216;match&amp;#8217; function is called with any object at all.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;The second test needs no explanation.&lt;/p&gt;


	&lt;p&gt;...&lt;/p&gt;


	&lt;p&gt;And that&amp;#8217;s kind of the point.  Why would I include a bizzare, dot-ridden, parentheses-laden syntax into my tests, when I can just as easily hand-roll the stub in pure and simple java?  How hard was it to hand-roll that stub?  Frankly, it took a lot less time and effort to hand-roll it than it took to write the (when(myobj.mymethod(anyx())).)()).))); statement.&lt;/p&gt;


	&lt;p&gt;OK, I&amp;#8217;m poking a little fun here.  But it&amp;#8217;s true.  My &lt;span class="caps"&gt;IDE&lt;/span&gt; (InteliJ) generated the stub for me.  I simply started with:&lt;/p&gt;


&lt;pre&gt;
Matcher&amp;lt;Object&amp;gt; falseMatcher = new Matcher&amp;lt;Object&amp;gt;() {};
&lt;/pre&gt;

	&lt;p&gt;InteliJ complained that some methods weren&amp;#8217;t implemented and offered to implement them for me.  I told it to go ahead.  It wrote the &amp;#8216;match&amp;#8217; method exactly as you see it.  Then I chose &amp;#8220;Convert Anonymous to Inner&amp;#8230;&amp;#8221; from the refactoring menu and named the new class FalseMatcher.  Voila!  No muss, no fuss, no parenthetic maze of dots.&lt;/p&gt;


Now look, I&amp;#8217;m not saying you shouldn&amp;#8217;t use mockito, or any of these other mocking tools.  I use them myself when I must.  Here, for example, is a test I wrote in FitNesse.  I was forced to use a mocking framework because I did not have the source code of the classes I was mocking.
&lt;pre&gt;
  @Before
  public void setUp() {
    manager = mock(GSSManager.class);
    properties = new Properties();
  }

  @Test
  public void credentialsShouldBeNonNullIfServiceNamePresent() throws Exception {
    properties.setProperty("NegotiateAuthenticator.serviceName", "service");
    properties.setProperty("NegotiateAuthenticator.serviceNameType", "1.1");
    properties.setProperty("NegotiateAuthenticator.mechanism", "1.2");
    GSSName gssName = mock(GSSName.class);
    GSSCredential gssCredential = mock(GSSCredential.class);
    when(manager.createName(anyString(), (Oid) anyObject(), (Oid) anyObject())).thenReturn(gssName);
    when(manager.createCredential((GSSName) anyObject(), anyInt(), (Oid) anyObject(), anyInt())).thenReturn(gssCredential);
    NegotiateAuthenticator authenticator = new NegotiateAuthenticator(manager, properties);
    Oid serviceNameType = authenticator.getServiceNameType();
    Oid mechanism = authenticator.getMechanism();
    verify(manager).createName("service", serviceNameType, mechanism);
    assertEquals("1.1", serviceNameType.toString());
    assertEquals("1.2", mechanism.toString());
    verify(manager).createCredential(gssName, GSSCredential.INDEFINITE_LIFETIME, mechanism, GSSCredential.ACCEPT_ONLY);
    assertEquals(gssCredential, authenticator.getServerCredentials());
  }
&lt;/pre&gt;

	&lt;p&gt;If I&amp;#8217;d had the source code of the &lt;span class="caps"&gt;GSS&lt;/span&gt; classes, I could have created some very simple stubs and spies that would have allowed me to make these tests a &lt;em&gt;lot&lt;/em&gt; cleaner than they currently appear.  Indeed, I might have been able to test the true &lt;em&gt;behavior&lt;/em&gt; of the classes rather than simply testing that I was calling them appropriately&amp;#8230;&lt;/p&gt;


	&lt;h2&gt;&lt;em&gt;Mockism&lt;/em&gt;&lt;/h2&gt;


	&lt;p&gt;That last bit is pretty important.  Some time ago Martin Fowler wrote a &lt;a href="http://martinfowler.com/articles/mocksArentStubs.html#SoShouldIBeAClassicistOrAMockist"&gt;blog&lt;/a&gt; about the &lt;em&gt;Mockist&lt;/em&gt; and &lt;em&gt;Classical&lt;/em&gt; style of &lt;span class="caps"&gt;TDD&lt;/span&gt;.  In short, &lt;em&gt;Mockists&lt;/em&gt; don&amp;#8217;t test the behavior of the system so much as they test that their classes &amp;#8220;dance&amp;#8221; well with other classes.  That is, they mock/stub out all the other classes that the class under test uses, and then make sure that all the right functions are called in all the right orders with all the right arguments. etc.  There is value to doing this in many cases.  However you can get pretty badly carried away with the approach.&lt;/p&gt;


	&lt;p&gt;The classical approach is to test for desired behavior, and trust that if the test passes, then the class being tested must be dancing well with its partners.&lt;/p&gt;


	&lt;p&gt;Personally, I don&amp;#8217;t belong to either camp.  I sometimes test the choreography, and I sometimes test the behavior.  I test the choreography when I am trying to isolate one part of the system from another.  I test for the behavior when such isolation is not important to me.&lt;/p&gt;


	&lt;p&gt;The point of all this is that I have observed that a heavy dependence on mocking frameworks tends to tempt you towards testing the dance when you &lt;em&gt;should&lt;/em&gt; be testing behavior.  Tools can drive the way we think.  So remember, &lt;em&gt;you&lt;/em&gt; dominate the tool; don&amp;#8217;t let the tool dominate you!&lt;/p&gt;


	&lt;h2&gt;But aren&amp;#8217;t hand-rolled mocks fragile?&lt;/h2&gt;


	&lt;p&gt;Yes, they can be.  If you are mocking a class or interface that it very volatile (i.e. you are adding new methods, or modifying method signatures a lot) then you&amp;#8217;ll have to go back and maintain all your hand-rolled mocks every time you make such a change.  On the other hand, if you use a mocking framework, the framework will take care of that for you unless one of the methods you are specifically testing is modified.&lt;/p&gt;


	&lt;p&gt;But here&amp;#8217;s the thing.  Interfaces should not usually be volatile.  They should not continue to grow and grow, and the methods should not change much.  OK, I realize that&amp;#8217;s wishful thinking.  But, &lt;em&gt;yes&lt;/em&gt;, I wish for the kind of a design in which interfaces are the &lt;em&gt;least&lt;/em&gt; volatile source files that you have.  That&amp;#8217;s kind of the point of interfaces after all&amp;#8230;  You create interfaces so that you can separate volatile implementations from non-volatile clients.  (Or at least that&amp;#8217;s one reason.)&lt;/p&gt;


	&lt;p&gt;So if you are tempted to use a mocking framework because you don&amp;#8217;t want to maintain your volatile interfaces, perhaps you should be asking yourself the more pertinent question about why your interfaces are so volatile.&lt;/p&gt;


	&lt;p&gt;Still, if you&amp;#8217;ve got volatile interfaces, and there&amp;#8217;s just no way around it, then a mocking framework may be the right choice for you.&lt;/p&gt;


	&lt;h2&gt;So here&amp;#8217;s the bottom line.&lt;/h2&gt;


	&lt;ul&gt;
	&lt;li&gt;It&amp;#8217;s easy to roll your own stubs and mocks. Your &lt;span class="caps"&gt;IDE&lt;/span&gt; will help you and they&amp;#8217;ll be easier and more natural to read than the dots and parentheses that the mocking frameworks impose upon you.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Mocking frameworks drive you towards testing choreography rather than behavior.  This can be useful, but it&amp;#8217;s not always appropriate.  And besides, even when you are testing choreography, the hand-rolled stubs and mocks are probably easier to write and read.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;There are special cases where mocking tools are &lt;em&gt;invaluable&lt;/em&gt;, specifically when you have to test choreography with objects that you have no source for or when your design has left you with a plethora of volatile interfaces.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;Am I telling you to avoid using mocking frameworks?  No, not at all.  I&amp;#8217;m just telling you that &lt;em&gt;you&lt;/em&gt; should drive tools, tools should not drive you.&lt;/p&gt;


	&lt;p&gt;If you have a situation where a mocking tool is the right choice, by all means use it.   But don&amp;#8217;t use it because you think it&amp;#8217;s &amp;#8220;agile&amp;#8221;, or because you think it&amp;#8217;s &amp;#8220;right&amp;#8221; or because you somehow think you are supposed to.  And remember, hand-rolling often results in simpler tests without the litter of dots and parentheses!&lt;/p&gt;</description>
      <pubDate>Wed, 28 Oct 2009 18:12:16 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:55f13a22-2823-4ae4-bd47-d32a1759e267</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2009/10/28/manual-mocking-resisting-the-invasion-of-dots-and-parentheses</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Agile Methods</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>We must ship now and deal with consequences</title>
      <description>&lt;p&gt;Martin Fowler has written a good &lt;a href="http://martinfowler.com/bliki/TechnicalDebtQuadrant.html"&gt;blog&lt;/a&gt; about technical debt.  He suggests that there are two axes of debt: &lt;em&gt;deliberate&lt;/em&gt; and &lt;em&gt;prudent&lt;/em&gt;.  This creates four quadrants: &lt;em&gt;deliberate-prudent&lt;/em&gt;, &lt;em&gt;deliberate-imprudent&lt;/em&gt;, &lt;em&gt;inadvertent-prudent&lt;/em&gt;, and &lt;em&gt;inadvertent-imprudent&lt;/em&gt;.  I agree with just about everything in his blog except for one particular caption&amp;#8230;&lt;/p&gt;


	&lt;h2&gt;Inadvertent-Imprudent Debt.&lt;/h2&gt;


	&lt;p&gt;There is more of this debt than any other kind.  It is all too common that software developers create a mess and don&amp;#8217;t know they are doing it.  They have not developed a nose that identifies code smells.  They don&amp;#8217;t know design principles, or design patterns.  They think that the reek of rotten code is normal, and don&amp;#8217;t even identify it as smelling bad.  They think that their slow pace through the thick morass of tangled code is the norm, and have no idea they could move faster.  These people destroy projects and bring whole companies to their knees.  Their name is &lt;em&gt;Doom&lt;/em&gt;.&lt;/p&gt;


	&lt;h2&gt;Deliberate-Imprudent Debt.&lt;/h2&gt;


	&lt;p&gt;There is a meme in our industry (call it the DI meme) that tells young software developers that rushing to the finish line at all costs is the right thing to do.  This is far worse than the ignorance of the first group because these folks &lt;em&gt;willfully&lt;/em&gt; create debt without counting the cost.  Worse, this meme is contagious.  People who are infected with it tend to infect others, causing an epidemic of deliberately imprudent debtors (sound familiar?) The end result, as we are now all know, is economic catastrophe, inflation (of estimates) and crushing interest (maintenance) payments.  They have become death, the destroyer of worlds.&lt;/p&gt;


	&lt;h2&gt;Inadvertent-Prudent Debt.&lt;/h2&gt;


	&lt;p&gt;This is something of an oxymoron.  Ironically, it is also the best of all possible states.  The fact is that no matter how careful we are, there is always a better solution that we will stumble upon later.  How many times have you finished a system only to realize that if you wrote it again, you&amp;#8217;d do it very differently, and much better?&lt;/p&gt;


	&lt;p&gt;The result is that we are always creating a debt, because our hindsight will always show us a better option after it is too late.  So even the best outcome still leaves us owing.  (Mother Earth will eventually collect that debt!)&lt;/p&gt;


	&lt;h2&gt;Deliberate-Prudent Debt.&lt;/h2&gt;


	&lt;p&gt;This is the quadrant that I have the biggest problem with.  And it is this quadrant in which Martin uses the caption I don&amp;#8217;t like.  The Caption is: &lt;em&gt;&amp;#8220;We must ship now and deal with consequences.&amp;#8221;&lt;/em&gt;&lt;/p&gt;


	&lt;p&gt;Does this happen?  Yes.  &lt;em&gt;Should&lt;/em&gt; it happen?  Rarely, yes.  But it damned well better not happen very often, and it damned well better not happen out of some misplaced urge to get done without counting the cost.&lt;/p&gt;


	&lt;p&gt;The problem I have with this quadrant (DP) is that people who are really in quadrant DI &lt;em&gt;think&lt;/em&gt; they are in DP, and use words such as those that appear in the caption as an excuse to rack up a huge imprudent debt.&lt;/p&gt;


	&lt;p&gt;The real issue is the definition of the word: &lt;em&gt;Imprudent&lt;/em&gt;.&lt;/p&gt;


	&lt;p&gt;So let me ask you a question.  How prudent is debt?  There is a very simple formula for determining whether debt is prudent or imprudent.  You can use this formula in real life, in business, and in programming.  The formula is:  Does the debt increase your net worth, and can you make the payments?&lt;/p&gt;


	&lt;p&gt;People often focus on the first criterion, without properly considering the second.  Buying a house is almost certain to increase your net worth despite the debt (though lately&amp;#8230;).  On the other hand, if you cannot make the payments, you won&amp;#8217;t keep that house for long.  The reason for our current economic woes has a lot to do with people trying to increase their net worth despite the fact that they couldn&amp;#8217;t afford the payments.  (indeed, they were encouraged by a meme very similar to the DI meme!)&lt;/p&gt;


	&lt;h2&gt;Bad code is &lt;em&gt;always&lt;/em&gt; imprudent.&lt;/h2&gt;


	&lt;p&gt;Writing bad code &lt;em&gt;never&lt;/em&gt; increases your net worth; and the interest rate is really high.  People who write bad code are like those twenty-somethings who max out all their credit cards.  Every transaction &lt;em&gt;decreases&lt;/em&gt; net worth, and has horrendous consequences for cash flow.  In the end, the vast bulk of your effort goes to paying the interest (the inevitable slow down of the team as they push the messes around).  Paying down the principle becomes infeasible. (Just the way credit card companies like it.)&lt;/p&gt;


	&lt;h2&gt;Some Suboptimal Design Decision are Prudent Debt.&lt;/h2&gt;


	&lt;p&gt;But most are not.  Every once in awhile there is a suboptimal design decision that will increase the net worth of the project by getting that project into customer&amp;#8217;s hand&amp;#8217;s early.&lt;/p&gt;


	&lt;p&gt;This is not the same as delivering software that is under-featured.  It is often prudent to increase the net worth of a project by giving customers early access to a system without a full and rich feature set.  This is not debt.  This is more like a savings account that &lt;em&gt;earns&lt;/em&gt; interest.&lt;/p&gt;


	&lt;p&gt;Indeed, this is one reason that most technical debt is imprudent.  If you are truly concerned about getting to market early, it is almost always better to do it with &lt;em&gt;fewer features&lt;/em&gt;, than with suboptimal design.  Missing features are a promise that can be kept.  Paying back suboptimal designs creates interest payments that often submerge any attempts at payback and can slow the team to the breaking point.&lt;/p&gt;


	&lt;p&gt;But there &lt;em&gt;are&lt;/em&gt; some cases where a sub-optimal design can increase your net worth by allowing you to deliver early. However, the interest rate needs to be very low, and the principle payments need to be affordable, and big enough to pay back the debt in short order.&lt;/p&gt;


	&lt;p&gt;What does a low interest rate mean?  It means that the sub-optimal design does not infiltrate every part of your system.  It means that you can put the sub-optimal design off in a corner where it doesn&amp;#8217;t impact your daily development life.&lt;/p&gt;


	&lt;p&gt;For example, I recently implemented a feature in FitNesse using &lt;span class="caps"&gt;HTML&lt;/span&gt; Frames.  This is sub-optimal.  On the other hand, the feature is constrained to one small part of the system, and it simply doesn&amp;#8217;t impact any other part of the system.  It does not impede my progress.  There is no mess for me to move around.  The interest rate is almost zero!  (nice deal if you can get it!)&lt;/p&gt;


	&lt;p&gt;Implementing that feature with ajax is a much larger project. I would have had to invest a great deal of time and effort, and would have had to restructure massive amounts of the internal code.  So the choice was a good one.&lt;/p&gt;


	&lt;p&gt;Better yet, the customer experience has pretty much been a big yawn.  I thought people would really like the feature and would drive me to expand upon it.  Instead, the customer base has virtually ignored it.&lt;/p&gt;


	&lt;p&gt;So my solution will be to pay back this debt by eliminating the feature.  It was a cheap experiment, that resulted in my &lt;em&gt;not&lt;/em&gt; having to spend a lot of time and effort on a new architecture!  Net worth indeed!&lt;/p&gt;


	&lt;p&gt;But it might have gone the other way.  My customers may have said: &amp;#8220;Wow, Great! We want more!&amp;#8221;  At that point it would have been &lt;em&gt;terrible&lt;/em&gt; to expand on the &lt;span class="caps"&gt;HTML&lt;/span&gt; Frames!  That decision would have been in the DI quadrant.  Deliberate imprudence!  Rather, my strategy would have been to replace the suboptimal Frames design of the feature with an isolated ajax implementation, and then to gradually migrate the ajax solution throughout the project.  That would have been annoying, but loan payments always are.&lt;/p&gt;


	&lt;h2&gt;Summary&lt;/h2&gt;


	&lt;p&gt;So, don&amp;#8217;t let the caption in the DP quadrant be an excuse.  Don&amp;#8217;t fall for the DI meme that says &amp;#8220;We just gotta bite the bullet&amp;#8221;.  Tread &lt;em&gt;very&lt;/em&gt; carefully when you enter the DP quadrant.  Look around at all your options, because it&amp;#8217;s easy to &lt;em&gt;think&lt;/em&gt; you are in the DP quadrant when you are really in the DI quadrant.&lt;/p&gt;


	&lt;p&gt;Remember: &lt;em&gt;Murphy shall send you strong delusion, that you should believe you are in DP; so that you will be damned in DI.&lt;/em&gt;&lt;/p&gt;</description>
      <pubDate>Thu, 15 Oct 2009 06:17:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:169be751-1a4f-45b8-8429-9eb3820be4a3</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2009/10/15/we-must-ship-now-and-deal-with-consequences</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Software Craftsmanship</category>
      <category>Agile Methods</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>TDD Derangement Syndrome</title>
      <description>&lt;p&gt;My recent blog about &lt;span class="caps"&gt;TDD&lt;/span&gt;, Design Patterns, Concurrency, and Sudoku seemed to draw the ire of a few vocal &lt;span class="caps"&gt;TDD&lt;/span&gt; detractors.  Some of these people were rude, insulting, derisive, dismissive, and immature.  Well, Halloween is not too far away.&lt;/p&gt;


	&lt;p&gt;In spite of their self-righteous snickering they did ask a few reasonable questions.  To be fair I thought it would be appropriate for me to answer them.&lt;/p&gt;


	&lt;h2&gt;Is there any research on &lt;span class="caps"&gt;TDD&lt;/span&gt;?&lt;/h2&gt;


	&lt;p&gt;It turns out that there is a fair bit.&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;One simple google search led me to &lt;a href="http://haacked.com/archive/2008/01/22/research-supports-the-effectiveness-of-tdd.aspx"&gt;this blog&lt;/a&gt; by Phil Haack in which he reviewed a &lt;span class="caps"&gt;TDD&lt;/span&gt; research paper.  Quoting from the paper:&lt;/li&gt;
	&lt;/ul&gt;


	&lt;blockquote&gt;
		&lt;p&gt;We found that test-first students on average wrote more tests and, in turn, students who wrote more tests tended to be more productive. We also observed that the minimum quality increased linearly with the number of programmer tests, independent of the development strategy employed.&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;ul&gt;
	&lt;li&gt;The same google search led me to &lt;a href="http://weblogs.asp.net/mhawley/archive/2004/04/15/114005.aspx"&gt;this blog&lt;/a&gt; by Matt Hawley, in which he reviewed several other research papers.  Part of his summary:&lt;/li&gt;
	&lt;/ul&gt;


	&lt;blockquote&gt;
		&lt;p&gt;* 87.5% of developers reported better requirements understanding.
    * 95.8% of developers reported reduced debugging efforts.
    * 78% of developers reported &lt;span class="caps"&gt;TDD&lt;/span&gt; improved overall productivity.
    * 50% of developers found that it decreased overall development time.
    * 92% of developers felt that &lt;span class="caps"&gt;TDD&lt;/span&gt; yielded high-quality code.
    * 79% of developers believed &lt;span class="caps"&gt;TDD&lt;/span&gt; promoted simpler design.&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;p&gt;Actually, I recognize some of Matt&amp;#8217;s results as coming from a &lt;a href="http://www.google.com/url?sa=t&amp;#38;source=web&amp;#38;ct=res&amp;#38;cd=1&amp;#38;url=http%3A%2F%2Fcollaboration.csc.ncsu.edu%2Flaurie%2FPapers%2FTDDpaperv8.pdf&amp;#38;ei=WoTMSvSXMYSqtgfDnMjrAQ&amp;#38;usg=AFQjCNHk6TJnNC32UGD8cN65EWGjoQkTBA&amp;#38;sig2=pbzOxiSB7_HAOoBTyDqetQ"&gt;rather famous 2003 study&lt;/a&gt; (also in the list of google results) by Laurie Wiliams and Boby George. This study describes a controlled experiment that they conducted in three different companies.  Though Matt&amp;#8217;s summary above is based (in part) on that study, there is more to say.&lt;/p&gt;


	&lt;p&gt;In the George-William study teams that practiced &lt;span class="caps"&gt;TDD&lt;/span&gt; took 16% &lt;em&gt;longer&lt;/em&gt; to &lt;em&gt;claim that they were done&lt;/em&gt; than the teams that did not practice &lt;span class="caps"&gt;TDD&lt;/span&gt;. Apparently tests are more accurate than claims since the non-TDD teams failed to pass one third of the researcher&amp;#8217;s hidden acceptance tests, whereas the &lt;span class="caps"&gt;TDD&lt;/span&gt; teams passed about 6 out of 7.  To paraphrase Kent Beck: &amp;#8220;If it doesn&amp;#8217;t have to work, I can get it done a &lt;em&gt;lot&lt;/em&gt; faster!&amp;#8221;&lt;/p&gt;


	&lt;p&gt;Another point of interest in this study is that the &lt;span class="caps"&gt;TDD&lt;/span&gt; teams produced a suite of automated tests with &lt;em&gt;very&lt;/em&gt; high test coverage (close to 100% in most cases) whereas most of the non-TDD teams did not produce such a suite; even though they had been instructed to.&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;Jim Shore wrote a review of &lt;a href="http://jamesshore.com/Blog/AoA-Correction-Test-Driven-Development.html"&gt;yet another research summary&lt;/a&gt; which I found in the same google search.  This one combines 7 different studies (including George-Williams).  Here the results range from dramatically improved quality and productivity to no observed effect.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Finally, there is &lt;a href="http://www.google.com/url?sa=t&amp;#38;source=web&amp;#38;ct=res&amp;#38;cd=4&amp;#38;url=http%3A%2F%2Fresearch.microsoft.com%2Fen-us%2Fprojects%2Fesm%2Fnagappan_tdd.pdf&amp;#38;ei=y4rMSryKDeWltgf6rOXgAQ&amp;#38;usg=AFQjCNGO5ql_sCI2dG5oR6mN8EFBa2OZNA&amp;#38;sig2=U8nr4HFFE6Ezog93OIhRTw"&gt;this&lt;/a&gt; 2008 case Study of &lt;span class="caps"&gt;TDD&lt;/span&gt; at &lt;span class="caps"&gt;IBM&lt;/span&gt; and Microsoft which shows that TDDers enjoy a defect density reduction ranging from 30% to 90% (as measured by defect tracking tools) and a productivity cost of between 15% and 35% (the subjective opinion of the managers).  I refer you back to Kent Beck&amp;#8217;s comment above.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;I&amp;#8217;m sure there is more research out there.  After all this was just one google search.  I think it&amp;#8217;s odd that the &lt;span class="caps"&gt;TDD&lt;/span&gt; detractors didn&amp;#8217;t find anything when they did &lt;em&gt;their&lt;/em&gt; google searches.&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;Oh yeah, and then there was that &lt;a href="http://www2.computer.org/portal/web/csdl/magazines/software#4"&gt;whole issue of &lt;span class="caps"&gt;IEEE&lt;/span&gt; Software&lt;/a&gt; that was dedicated to papers and research on &lt;span class="caps"&gt;TDD&lt;/span&gt;.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;h2&gt;What projects have been written with &lt;span class="caps"&gt;TDD&lt;/span&gt;, hmmm?&lt;/h2&gt;


	&lt;p&gt;Quite a few, actually.  The following is a list of projects that have an automated suite of unit tests with very high coverage.  Those that I know for a fact use &lt;span class="caps"&gt;TDD&lt;/span&gt;, I have noted as such.  The others, I can only surmise.  If you know of any others, please post a comment here.&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;JUnit.  This one is kind of obvious.  JUnit was written by Kent Beck and Erich Gamma using &lt;span class="caps"&gt;TDD&lt;/span&gt; throughout.  If you measure software success by sheer distribution, this particular program is &lt;em&gt;wildly&lt;/em&gt; successful.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Fit.  Written by Ward Cunningham.  The progenitor of most current acceptance testing frameworks.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;FitNesse.  This testing framework has tens of thousands of users.  It is 70,000 lines of java code, with 90%+ code coverage.  &lt;span class="caps"&gt;TDD&lt;/span&gt; throughout.  Very small bug-list.  Again, if you measure by distribution, another raving success.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Cucumber, &lt;/li&gt;
		&lt;li&gt;Rspec.  These two are Testing frameworks in Ruby.  Of course you&amp;#8217;d expect a testing framework to be written with &lt;span class="caps"&gt;TDD&lt;/span&gt;, wouldn&amp;#8217;t you? I know these were. &lt;span class="caps"&gt;TDD&lt;/span&gt; throughout.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Limelight.  A gui framework in JRUby.  &lt;span class="caps"&gt;TDD&lt;/span&gt; throughout.&lt;/li&gt;
		&lt;li&gt;jfreechart. &lt;/li&gt;
		&lt;li&gt;Spring&lt;/li&gt;
		&lt;li&gt;JRuby&lt;/li&gt;
		&lt;li&gt;Smallsql&lt;/li&gt;
		&lt;li&gt;Ant&lt;/li&gt;
		&lt;li&gt;MarsProject&lt;/li&gt;
		&lt;li&gt;Log4J&lt;/li&gt;
		&lt;li&gt;Jmock&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;Are there others?  I&amp;#8217;m sure there are.  This was just a quick web search.  
Again, if you know of more, please add a comment.&lt;/p&gt;</description>
      <pubDate>Wed, 07 Oct 2009 08:32:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:31f3a32e-467c-4c54-9ec8-3b63fe961ff1</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2009/10/07/tdd-derangement-syndrome</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Software Craftsmanship</category>
      <category>Agile Methods</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Echoes from the Stone Age</title>
      <description>&lt;p&gt;The echoes from Joel Spolsky&amp;#8217;s &lt;a href="http://www.joelonsoftware.com/items/2009/09/23.html"&gt;Duct Tape blog&lt;/a&gt; continue to bounce off the blogosphere and twitterverse.  &lt;a href="http://www.tbray.org/ongoing/When/200x/2009/09/25/On-Duct-Tape"&gt;Tim Bray&lt;/a&gt; and &lt;a href="http://gigamonkeys.com/blog/2009/10/05/coders-unit-testing.html"&gt;Peter Seibel&lt;/a&gt; have both written responses to Joel, me, and each other.&lt;/p&gt;


	&lt;p&gt;Here are some stray thoughts&amp;#8230;&lt;/p&gt;


	&lt;h2&gt;&lt;span class="caps"&gt;TDD&lt;/span&gt;&lt;/h2&gt;


	&lt;p&gt;Anyone who continues to think that &lt;span class="caps"&gt;TDD&lt;/span&gt; slows you down is living in the stone age.  Sorry, that&amp;#8217;s just the truth.  &lt;span class="caps"&gt;TDD&lt;/span&gt; does not slow you down, it speeds you up.&lt;/p&gt;


	&lt;p&gt;Look, &lt;span class="caps"&gt;TDD&lt;/span&gt; is not my religion, it is one of my &lt;em&gt;disciplines&lt;/em&gt;.  It&amp;#8217;s like &lt;em&gt;dual entry bookkeeping&lt;/em&gt; for accountants, or &lt;em&gt;sterile procedure&lt;/em&gt; for surgeons.  Professionals adopt such disciplines because they understand the theory behind them, and have directly experienced the benefits of using them.&lt;/p&gt;


	&lt;p&gt;I have experienced the tremendous benefit that &lt;span class="caps"&gt;TDD&lt;/span&gt; has had in my work, and I have observed it in others.  I have seen and experienced the way that &lt;span class="caps"&gt;TDD&lt;/span&gt; helps programmers conceive their designs.  I have seen and experienced the way it documents their decisions.  I have seen and experienced the decouplings imposed by the tests, and I have seen and experienced the fearlessness with which TDDers can change and clean their code.&lt;/p&gt;


	&lt;p&gt;To be fair, I don&amp;#8217;t think &lt;span class="caps"&gt;TDD&lt;/span&gt; is &lt;em&gt;always&lt;/em&gt; appropriate.  There are situations when I break the discipline and write code before tests.  I&amp;#8217;ll write about these situations in another blog.  However, these situations are few and far between.  In general, for me and many others, &lt;span class="caps"&gt;TDD&lt;/span&gt; is a way to go fast, well, and sure.&lt;/p&gt;


	&lt;p&gt;The upshot of all this is simple.  &lt;span class="caps"&gt;TDD&lt;/span&gt; is a professional discipline.  &lt;span class="caps"&gt;TDD&lt;/span&gt; works.  &lt;span class="caps"&gt;TDD&lt;/span&gt; makes you faster.  &lt;span class="caps"&gt;TDD&lt;/span&gt; is not going away.  And anyone who has not &lt;em&gt;really&lt;/em&gt; tried it, and yet claims that it would slow them down, is simply being willfully ignorant.  I don&amp;#8217;t care if your name is Don Knuth, Jamie Zawinski, Peter Seibel, or Peter Pan.  Give it a &lt;em&gt;real&lt;/em&gt; try, and &lt;em&gt;then&lt;/em&gt; you have the right to comment.&lt;/p&gt;


	&lt;p&gt;Let me put this another way.  And now I&amp;#8217;m talking directly to those who make the claim that &lt;span class="caps"&gt;TDD&lt;/span&gt; would slow them down.  Are you really such a good programmer that you don&amp;#8217;t need to thoroughly check your work?  Can you conceive of a better way to check your work than to express your intent in terms of an executable test?  And can you think of a better way to ensure that you can write that test other than to write it first?&lt;/p&gt;


	&lt;p&gt;If you can, then I want to hear all about it.  but I don&amp;#8217;t want to hear that you write a few unit tests after the fact.  I don&amp;#8217;t want to hear that you manually check your code.  I don&amp;#8217;t want to hear that you &lt;em&gt;do design&lt;/em&gt; and therefore don&amp;#8217;t need to write tests.  Those are all stone-age concepts.  I know.  I&amp;#8217;ve been there.&lt;/p&gt;


	&lt;p&gt;So there. &amp;lt;grin&amp;gt;&lt;/p&gt;


	&lt;h2&gt;The Design Pattern Religion&lt;/h2&gt;


	&lt;p&gt;Tim Bray said:&lt;/p&gt;


	&lt;blockquote&gt;
		&lt;p&gt;My experience suggests that there are few surer ways to doom a big software project than via the Design Patterns religion.&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;p&gt;He&amp;#8217;s right of course.  The Design Patterns &lt;em&gt;religion&lt;/em&gt; is a foul bird that ravages teams and cuts down young projects in their prime.  But let&amp;#8217;s be clear about what that religion is.  The Design Patterns religion is the ardent belief that the use of design patterns is &lt;em&gt;good&lt;/em&gt;.&lt;/p&gt;


	&lt;p&gt;Here&amp;#8217;s a clue.  Design Patterns aren&amp;#8217;t good.  They also aren&amp;#8217;t bad.  They just are.  Given a particular software design situation, there may be a pattern that fits and is beneficial.  There may also be patterns that would be detrimental.  It&amp;#8217;s quite possible that none of the currently documented patterns are appropriate and that you should close the book and just solve the problem.&lt;/p&gt;


	&lt;p&gt;Here&amp;#8217;s another clue.  You don&amp;#8217;t &lt;em&gt;use&lt;/em&gt; patterns.  You don&amp;#8217;t &lt;em&gt;apply&lt;/em&gt; patterns.  Patterns just are.  If a particular pattern is appropriate to solve a given problem, then it will be &lt;em&gt;obvious&lt;/em&gt;.  Indeed it is often &lt;em&gt;so&lt;/em&gt; obvious that you don&amp;#8217;t realize that the pattern is in place until you are done.  You look &lt;em&gt;back&lt;/em&gt; at your code and realize: &amp;#8220;Oh, that&amp;#8217;s a Decorator!&amp;#8221;.&lt;/p&gt;


	&lt;p&gt;So am I saying that Design Patterns are useless?&lt;/p&gt;


	&lt;p&gt;NO!  I want you to read the patterns books.  I want you to know those patterns inside and out.  If I point at you and say &amp;#8220;Visitor&amp;#8221; I want you at the board drawing all the different variants of the pattern without hesitation.  I want you to get all the names and roles right.  I want you to &lt;em&gt;know&lt;/em&gt; patterns.&lt;/p&gt;


	&lt;p&gt;But I don&amp;#8217;t want you to &lt;em&gt;use&lt;/em&gt; patterns.  I don&amp;#8217;t want you to &lt;em&gt;believe&lt;/em&gt; in patterns.  I don&amp;#8217;t want you to make patterns into a religion.  Rather I want you to be able to recognize them when they appear, and to &lt;em&gt;regularize&lt;/em&gt; them in your code so that others can recognize them too.&lt;/p&gt;


	&lt;p&gt;Design Patterns have a &lt;em&gt;huge&lt;/em&gt; benefit.  They have &lt;em&gt;names&lt;/em&gt;.  If you are reading code, and you see the word &amp;#8220;Composite&amp;#8221;, and if the author took care to regularize the code to the accepted names and roles of the &amp;#8220;Composite&amp;#8221; pattern, then you will &lt;em&gt;know&lt;/em&gt; what that part of the code is doing instantly.  And &lt;em&gt;that&lt;/em&gt; is powerful!&lt;/p&gt;


	&lt;h2&gt;Minimizing Concurrency.&lt;/h2&gt;


	&lt;p&gt;In my first &lt;a href="http://blog.objectmentor.com/articles/2009/09/24/the-duct-tape-programmer"&gt;Duct Tape blog&lt;/a&gt; I made the statement:&lt;/p&gt;


	&lt;blockquote&gt;
		&lt;p&gt;I found myself annoyed at Joel&amp;rsquo;s notion that most programmers aren&amp;rsquo;t smart enough to use templates, design patterns, multi-threading, &lt;span class="caps"&gt;COM&lt;/span&gt;, etc. I don&amp;rsquo;t think that&amp;rsquo;s the case. I think that any programmer that&amp;rsquo;s not smart enough to use tools like that is probably not smart enough to be a programmer period.&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;p&gt;Tim responds with:&lt;/p&gt;


	&lt;blockquote&gt;
		&lt;p&gt;...multi-threading is part of the problem, not part of the solution; that essentially no application programmer understands threads well enough to avoid deadlocks and races and horrible non-repeatable bugs. And that &lt;span class="caps"&gt;COM&lt;/span&gt; was one of the most colossal piles of crap my profession ever foisted on itself.&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;p&gt;Is concurrency really part of the problem?  Yes!  Concurrency is a &lt;em&gt;really big&lt;/em&gt; part of the problem.  Indeed, the first rule of concurrency is: &lt;em&gt;&lt;span class="caps"&gt;DON&lt;/span&gt;&amp;#8217;T&lt;/em&gt;.  The second rule is: &lt;em&gt;&lt;span class="caps"&gt;REALLY&lt;/span&gt;, DON&amp;#8217;T&lt;/em&gt;.&lt;/p&gt;


	&lt;p&gt;The problem is that some times you have no choice.  And in those situations, where you absolutely must use concurrency, &lt;em&gt;you should know it inside and out!&lt;/em&gt;&lt;/p&gt;


	&lt;p&gt;I completely and utterly reject the notion that &lt;em&gt;ignorance&lt;/em&gt; is the best defense.  I reject that &lt;em&gt;lack of skill&lt;/em&gt; can &lt;em&gt;ever&lt;/em&gt; be an advantage.  So I want you to &lt;em&gt;know&lt;/em&gt; concurrency.  I want to shout &amp;#8220;Dining Philosophers&amp;#8221; and have you run to the board without hesitation and show me all the different solutions.  If I holler &amp;#8220;Deadlock&amp;#8221;, I want you to quickly identify the causes and solutions.&lt;/p&gt;


	&lt;p&gt;Here&amp;#8217;s a clue.  If you want to avoid using something, &lt;em&gt;know&lt;/em&gt; that something &lt;em&gt;cold&lt;/em&gt;.&lt;/p&gt;


	&lt;h2&gt;Sudoku&lt;/h2&gt;


	&lt;p&gt;At the end of his blog, Peter jumps on the pile of bodies already crushing Ron Jeffries regarding the Sudoku problem from July of 2006.&lt;/p&gt;


	&lt;p&gt;I find the pile-up disturbing.  Ron had the courage to fail in public.  Indeed he announced up front that he might &amp;#8220;crash and burn&amp;#8221;.  And yet he got lambasted for it by people who hid behind someone else&amp;#8217;s work.  The responses to Ron&amp;#8217;s tutorial blogs were completely unfair because the authors of those blogs had everything worked out for them by Dr. Peter Norvig before they published their screeds.  They were comparing apples to oranges because their responses were about the &lt;em&gt;solution&lt;/em&gt; whereas Ron&amp;#8217;s blogs were about the &lt;em&gt;process&lt;/em&gt;.&lt;/p&gt;


	&lt;p&gt;Which one of us has not gone down a rat-hole when hunting for a solution to a complex problem?  Let &lt;em&gt;that&lt;/em&gt; person write the first blog.  Everyone else ought to be a bit more humble.&lt;/p&gt;


	&lt;p&gt;Do the people on the pile think that Ron is unable to solve the Sudoku problem?  (Some have said as much.)  Then they don&amp;#8217;t know Ron very well.  Ron could code them all under the table with one hand tied behind his back.&lt;/p&gt;


	&lt;p&gt;Personal issues aside, I find the discussion fascinating in it&amp;#8217;s own right.  Ron had attempted to solve the Sudoku problem by gaining insight into that problem through the process of coding intermediate solutions.  This is a common enough &lt;span class="caps"&gt;TDD&lt;/span&gt; approach.  Indeed, the &lt;a href="http://butunclebob.com/ArticleS.UncleBob.TheBowlingGameKata"&gt;Bowling Game&lt;/a&gt; and the &lt;a href="http://butunclebob.com/ArticleS.UncleBob.ThePrimeFactorsKata"&gt;Prime Factors Kata&lt;/a&gt; are both examples where this approach can work reasonably well.&lt;/p&gt;


	&lt;p&gt;This approach follows the advice of no less than Grady Booch who (quoting Heinlein) said:  &amp;#8220;&lt;em&gt;when faced with a problem you do not understand, do any part of it you do understand, then look at it again.&lt;/em&gt;&amp;#8220;&lt;/p&gt;


	&lt;p&gt;Ron was attempting to use &lt;span class="caps"&gt;TDD&lt;/span&gt; to &lt;em&gt;probe&lt;/em&gt; into the problem to see if he could gain any insight.  This technique often bears fruit.  Sometimes it does not.&lt;/p&gt;


	&lt;p&gt;Here is a classic example.  Imagine you were going to write a sort algorithm test first:&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;Test 1: Sort an empty array.
Solution: Return the input array.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Test 2: Sort an array with one element.
Solution: Return the input array.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Test 3: Sort an array with two elements.
Solution: Compare the two elements and swap if out of order.  Return the result.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Test 4: Sort an array with three elements.
Solution: Compare the first two and swap if out of order.  Compare the second two and swap if out of order.  Compare the first two again and swap if out of order.  Return the result.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Test 5: Sort an array with four elements.
Solution: Put the compare and swap operations into a nested loop.  Return the result.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;The end result is a bubble sort.  The algorithm virtually self assembles.  If you had never heard of a bubble sort before, this simple set of tests would have driven you to implement it naturally.&lt;/p&gt;


	&lt;p&gt;Problems like Bowling, Prime Factors, and Bubble Sort hold out the interesting promise that &lt;span class="caps"&gt;TDD&lt;/span&gt; may be a way to &lt;em&gt;derive&lt;/em&gt; algorithmms from first principles!&lt;/p&gt;


	&lt;p&gt;On the other hand, what set of tests would drive you to implement a QuickSort?  There are none that I know of.  QuickSort and Sudoku may require a serious amount of introspection and concentrated thought before the solution is apparent.  They may belong to a class of algorithms that do not self-assemble like Bowling, Prime Factors, and Bubble Sort.&lt;/p&gt;


	&lt;p&gt;This &lt;a href="http://www.infoq.com/news/2007/05/tdd-sudoku"&gt;blog&lt;/a&gt; by Kurt Christensen provides all the links to the various Sudoku articles, and sums it up this way.&lt;/p&gt;


	&lt;blockquote&gt;
		&lt;p&gt;&lt;span class="caps"&gt;TDD&lt;/span&gt; may not be the best tool for inventing new algorithms, it may very well be the best tool for applying those algorithms to the problem at hand.&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;p&gt;Actually I think &lt;span class="caps"&gt;TDD&lt;/span&gt; is a good way to find out if an algorithm will self-assemble or not.  It usually doesn&amp;#8217;t take a lot of time to figure out which it&amp;#8217;s going to be.&lt;/p&gt;</description>
      <pubDate>Tue, 06 Oct 2009 11:07:29 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:1624b718-36a6-4521-aa4e-14d5b9623dc0</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2009/10/06/echoes-from-the-stone-age</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Software Craftsmanship</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>A Mess is not a Technical Debt.</title>
      <description>&lt;p&gt;The term &lt;a href="http://martinfowler.com/bliki/TechnicalDebt.html"&gt;Technical Debt&lt;/a&gt; was created by Ward Cunningham to describe the engineering trade-off&amp;#8217;s that software developers and business stakeholders must often make in order to meet schedules and customer expectations.  In short, you may need to use suboptimal designs in the short term, because the schedule does not allow longer term designs to be used.  As a simple example, your initial website design may need to be frames based because you don&amp;#8217;t have time to build an Ajax framework.&lt;/p&gt;


	&lt;p&gt;Clearly this causes a debt.  If the customer is looking for a web 2.0 system, then frames just aren&amp;#8217;t going to cut it for long.  So time is going to have to be carved out of a future schedule to refit the system with an Ajax solution.&lt;/p&gt;


	&lt;p&gt;In short, the business has decided that it can afford to delay release 2 in order to accelerate release 1.  Is this wise?&lt;/p&gt;


	&lt;p&gt;Businesses make this kind of trade-off all the time; and there&amp;#8217;s nothing inherently unwise about it.  If the early release of 1.0 drives the business that pays for the development of 2.0 then the business has won.  So &lt;em&gt;this kind&lt;/em&gt; of reasoned technical debt may indeed be appropriate.&lt;/p&gt;


	&lt;p&gt;Unfortunately there is another situation that is sometimes called &amp;#8220;technical debt&amp;#8221; but that is neither reasoned nor wise.  A mess.&lt;/p&gt;


	&lt;p&gt;Technical debt may be necessary, but it had also better be &lt;em&gt;clean&lt;/em&gt;!  If you are going to implement a frames solution instead of an &lt;span class="caps"&gt;AJAX&lt;/span&gt; solution, then make sure that the workmanship of the frames solution is top-notch.  Make sure the design is well balanced, and the code is clean.  If you make a mess while implementing that frames solution, you&amp;#8217;ll never be able to replace it with an &lt;span class="caps"&gt;AJAX&lt;/span&gt; framework.  The mess will impede your progress forever.&lt;/p&gt;


	&lt;p&gt;A mess is not a technical debt.  A mess is just a mess.  Technical debt decisions are made based on real project constraints.  They are risky, but they can be beneficial.  The decision to make a mess is never rational, is always based on laziness and unprofessionalism, and has no chance of paying of in the future.  A mess is &lt;em&gt;always&lt;/em&gt; a loss.&lt;/p&gt;


	&lt;p&gt;When you buy a house and take on a big mortgage debt, you tighten up all your spending and accounting.  You clean up your books and your budgets.  You behave with &lt;em&gt;increased&lt;/em&gt; discipline.  The same is true of technical debt.  The more technical debt you take on, the tighter your disciplines need to be.  You should do &lt;em&gt;more&lt;/em&gt; testing, and &lt;em&gt;more&lt;/em&gt; pairing and &lt;em&gt;more&lt;/em&gt; refactoring.  Technical debt is not a license to make a mess.  Technical debt creates the need for even greater cleanliness.&lt;/p&gt;


	&lt;p&gt;When you decide to take on a technical debt, you had better make sure that your code stays squeaky clean.  Keeping the system clean is the only way you will pay down that debt.&lt;/p&gt;</description>
      <pubDate>Tue, 22 Sep 2009 08:15:19 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:0d502aec-a625-4ce1-9ad9-6e67aa589b44</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2009/09/22/a-mess-is-not-a-technical-debt</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>One Thing: Extract till you Drop.</title>
      <description>&lt;p&gt;For years authors and consultants (like me) have been telling us that functions should do &lt;em&gt;one thing&lt;/em&gt;.  They should do it well.  They should do it only.&lt;/p&gt;


	&lt;p&gt;The question is: What the hell does &amp;#8220;one thing&amp;#8221; mean?&lt;/p&gt;


	&lt;p&gt;After all, one man&amp;#8217;s &amp;#8220;one thing&amp;#8221; might be someone else&amp;#8217;s &amp;#8220;two things&amp;#8221;.&lt;/p&gt;


Consider this class:
&lt;pre&gt;
  class SymbolReplacer {
    protected String stringToReplace;
    protected List&amp;lt;String&amp;gt; alreadyReplaced = new ArrayList&amp;lt;String&amp;gt;();

    SymbolReplacer(String s) {
      this.stringToReplace = s;
    }

    String replace() {
      Pattern symbolPattern = Pattern.compile("\\$([a-zA-Z]\\w*)");
      Matcher symbolMatcher = symbolPattern.matcher(stringToReplace);
      while (symbolMatcher.find()) {
        String symbolName = symbolMatcher.group(1);
        if (getSymbol(symbolName) != null &amp;#38;&amp;#38; !alreadyReplaced.contains(symbolName)) {
          alreadyReplaced.add(symbolName);
          stringToReplace = stringToReplace.replace("$" + symbolName, translate(symbolName));
        }
      }
      return stringToReplace;
    }

    protected String translate(String symbolName) {
      return getSymbol(symbolName);
    }
  }
&lt;/pre&gt;

	&lt;p&gt;It&amp;#8217;s not too hard to understand.  The &lt;span style="font-family:courier;"&gt;replace()&lt;/span&gt; function searches through a string looking for &lt;em&gt;$NAME&lt;/em&gt; and replaces each instance with the appropriate translation of &lt;em&gt;&lt;span class="caps"&gt;NAME&lt;/span&gt;&lt;/em&gt;.  It also makes sure that it doesn&amp;#8217;t replace a name more than once.  Simple.&lt;/p&gt;


	&lt;p&gt;Of course the words &amp;#8220;It also&amp;#8230;&amp;#8221; pretty much proves that this function does more than one thing.  So we can probably split the function up into two functions as follows:&lt;/p&gt;


&lt;pre&gt;
    String replace() {
      Pattern symbolPattern = Pattern.compile("\\$([a-zA-Z]\\w*)");
      Matcher symbolMatcher = symbolPattern.matcher(stringToReplace);
      while (symbolMatcher.find()) {
        String symbolName = symbolMatcher.group(1);
        replaceAllInstances(symbolName);
      }
      return stringToReplace;
    }

    private void replaceAllInstances(String symbolName) {
      if (getSymbol(symbolName) != null &amp;#38;&amp;#38; !alreadyReplaced.contains(symbolName)) {
        alreadyReplaced.add(symbolName);
        stringToReplace = stringToReplace.replace("$" + symbolName, translate(symbolName));
      }
    }
&lt;/pre&gt;

	&lt;p&gt;OK, so now the &lt;span style="font-family:courier;"&gt;replace()&lt;/span&gt; function simply finds all the symbols that need replacing, and the &lt;span style="font-family:courier;"&gt;replaceAllInstances()&lt;/span&gt; function replaces them if they haven&amp;#8217;t already been replaced.  So do these function do one thing each?&lt;/p&gt;


	&lt;p&gt;Well, the &lt;span style="font-family:courier;"&gt;replace()&lt;/span&gt; compiles the pattern and build the &lt;span style="font-family:courier;"&gt;Matcher()&lt;/span&gt;  Maybe those actions should be moved into the constructor?&lt;/p&gt;


&lt;pre&gt;
  class SymbolReplacer {
    protected String stringToReplace;
    protected List&amp;lt;String&amp;gt; alreadyReplaced = new ArrayList&amp;lt;String&amp;gt;();
    private Matcher symbolMatcher;
    private final Pattern symbolPattern = Pattern.compile("\\$([a-zA-Z]\\w*)");

    SymbolReplacer(String s) {
      this.stringToReplace = s;
      symbolMatcher = symbolPattern.matcher(s);
    }

    String replace() {
      while (symbolMatcher.find()) {
        String symbolName = symbolMatcher.group(1);
        replaceAllInstances(symbolName);
      }
      return stringToReplace;
    }

    private void replaceAllInstances(String symbolName) {
      if (getSymbol(symbolName) != null &amp;#38;&amp;#38; !alreadyReplaced.contains(symbolName)) {
        alreadyReplaced.add(symbolName);
        stringToReplace = stringToReplace.replace("$" + symbolName, translate(symbolName));
      }
    }

    protected String translate(String symbolName) {
      return getSymbol(symbolName);
    }
  }
&lt;/pre&gt;

	&lt;p&gt;OK, so &lt;em&gt;now&lt;/em&gt; certainly the &lt;span style="font-family:courier;"&gt;replace()&lt;/span&gt; function is doing &lt;em&gt;one thing&lt;/em&gt;?  Ah, but I see at least two.  It loops, extracts the &lt;span style="font-family:courier;"&gt;symbolName&lt;/span&gt; and then does the replace.  OK, so how about this?&lt;/p&gt;


&lt;pre&gt;
    String replace() {
      for (String symbolName = nextSymbol(); symbolName != null; symbolName = nextSymbol())
        replaceAllInstances(symbolName);

      return stringToReplace;
    }

    private String nextSymbol() {
      return symbolMatcher.find() ? symbolMatcher.group(1) : null;
    }
&lt;/pre&gt;

	&lt;p&gt;I had to restructure things a little bit.  The loop is a bit ugly.  I wish I could have said &lt;span style="font-family:courier;"&gt;for (String symbolName : symbolMatcher)&lt;/span&gt; but I guess &lt;span style="font-family:courier;"&gt;Matchers&lt;/span&gt; don&amp;#8217;t work that way.&lt;/p&gt;


	&lt;p&gt;I kind of like the &lt;span style="font-family:courier;"&gt;nextSymbol()&lt;/span&gt; function.  It gets the &lt;span style="font-family:courier;"&gt;Matcher&lt;/span&gt; nicely out of the way.&lt;/p&gt;


	&lt;p&gt;So now the &lt;span style="font-family:courier;"&gt;replace()&lt;/span&gt; and &lt;span style="font-family:courier;"&gt;nextSymbol()&lt;/span&gt; functions are &lt;em&gt;certainly&lt;/em&gt; doing one thing.  Aren&amp;#8217;t they?&lt;/p&gt;


	&lt;p&gt;Well, I suppose I could separate the loop from the return in &lt;span style="font-family:courier;"&gt;replace()&lt;/span&gt;.&lt;/p&gt;


&lt;pre&gt;
    String replace() {
      replaceAllSymbols();
      return stringToReplace;
    }

    private void replaceAllSymbols() {
      for (String symbolName = nextSymbol(); symbolName != null; symbolName = nextSymbol())
        replaceAllInstances(symbolName);
    }
&lt;/pre&gt;

	&lt;p&gt;I don&amp;#8217;t see how I could make these functions smaller.  They &lt;em&gt;must&lt;/em&gt; be doing &lt;em&gt;one thing&lt;/em&gt;.  There&amp;#8217;s no way to extract any other functions from them!&lt;/p&gt;


	&lt;p&gt;Uh&amp;#8230;  Wait.  Is &lt;em&gt;that&lt;/em&gt; the definition of &lt;em&gt;one thing&lt;/em&gt;?  Is a function doing &lt;em&gt;one thing&lt;/em&gt; if, and only if, you simply cannot extract any other functions from it?  What else &lt;em&gt;could&lt;/em&gt; &amp;#8220;one thing&amp;#8221; mean?  After all, If I can extract one function out of another, the original function must have been doing more than one thing.&lt;/p&gt;


	&lt;p&gt;So does that mean that for all these years the authors and consultants (like me) have been telling us to extract until you can&amp;#8217;t extract anymore?&lt;/p&gt;


Let&amp;#8217;s try that with the rest of this class and see what it looks like&amp;#8230;
&lt;pre&gt;
  class SymbolReplacer {
    protected String stringToReplace;
    protected List&amp;lt;String&amp;gt; alreadyReplaced = new ArrayList&amp;lt;String&amp;gt;();
    private Matcher symbolMatcher;
    private final Pattern symbolPattern = Pattern.compile("\\$([a-zA-Z]\\w*)");

    SymbolReplacer(String s) {
      this.stringToReplace = s;
      symbolMatcher = symbolPattern.matcher(s);
    }

    String replace() {
      replaceAllSymbols();
      return stringToReplace;
    }

    private void replaceAllSymbols() {
      for (String symbolName = nextSymbol(); symbolName != null; symbolName = nextSymbol())
        replaceAllInstances(symbolName);
    }

    private String nextSymbol() {
      return symbolMatcher.find() ? symbolMatcher.group(1) : null;
    }

    private void replaceAllInstances(String symbolName) {
      if (shouldReplaceSymbol(symbolName))
        replaceSymbol(symbolName);
    }

    private boolean shouldReplaceSymbol(String symbolName) {
      return getSymbol(symbolName) != null &amp;#38;&amp;#38; !alreadyReplaced.contains(symbolName);
    }

    private void replaceSymbol(String symbolName) {
      alreadyReplaced.add(symbolName);
      stringToReplace = stringToReplace.replace(
        symbolExpression(symbolName), 
        translate(symbolName));
    }

    private String symbolExpression(String symbolName) {
      return "$" + symbolName;
    }

    protected String translate(String symbolName) {
      return getSymbol(symbolName);
    }
  }
&lt;/pre&gt;

	&lt;p&gt;Well, I think it&amp;#8217;s pretty clear that each of these functions is doing &lt;em&gt;one thing&lt;/em&gt;.  I&amp;#8217;m not sure how I&amp;#8217;d extract anything further from any of them.&lt;/p&gt;


	&lt;p&gt;Perhaps you think this is taking things too far.  I used to think so too.  But after programming for over 40+ years, I&amp;#8217;m beginning to come to the conclusion that this level of extraction is not taking things too far at all.  In fact, to me, it looks just about right.&lt;/p&gt;


	&lt;p&gt;So, my advice: Extract till you just can&amp;#8217;t extract any more.  Extract till you drop.&lt;/p&gt;


	&lt;p&gt;After all, with modern tools it takes &lt;em&gt;very&lt;/em&gt; little time.  It makes each function almost trivial.  The code reads very nicely.  It forces you to put little snippets of code into nicely named functions.  And, well gosh, extracting till you drop is kind of fun!&lt;/p&gt;</description>
      <pubDate>Fri, 11 Sep 2009 13:33:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:fa921995-cdc4-4867-8541-9bfa9a2834e4</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2009/09/11/one-thing-extract-till-you-drop</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Software Craftsmanship</category>
      <category>Design Principles</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>As the tests get more specific, the code gets more generic.</title>
      <description>&lt;p&gt;I tweeted this not too long ago.  The basic idea is that as you add tests, the tests get more and more specific.  This makes sense since tests are, after all, specifications.  The more specifications you have, the more specific the whole body of specifications becomes.&lt;/p&gt;


	&lt;p&gt;As a general rule, good design dictates that the more specific your requirements become, the more general your code needs to be.  This is saying roughly the same thing as Greenspun&amp;#8217;s Tenth Rule of Programming: &amp;#8220;Any sufficiently complicated [...] program contains an ad hoc informally-specified bug-ridden slow implementation of half of Common Lisp.&amp;#8221;  Or rather, as more and more constraints pile upon a program, the designers look for ways to push those constraints out of the program itself and into the data.&lt;/p&gt;


	&lt;p&gt;In return for my tweet people asked for examples.&lt;/p&gt;


	&lt;p&gt;One of the better examples (though perhaps a bit trivial) is the &lt;a href="http://butunclebob.com/ArticleS.UncleBob.ThePrimeFactorsKata"&gt;Prime Factors Kata&lt;/a&gt;.   This lovely little experiment grows and grows as you add test cases, and then suddenly collapses into an elegant three line algorithm.&lt;/p&gt;


	&lt;p&gt;The tests continue to become ever more specific.  The production code starts out &lt;em&gt;just as&lt;/em&gt; specific as the tests.  But with the second or third test the programmer must make a decision.  He can write the production code to mirror the tests (i.e. writing it as an if/else statement that detects which test is running and supplying the expected answer) or he can come up with some kind of more general algorithm that satisfies the tests without looking anything like them.&lt;/p&gt;


	&lt;p&gt;The algorithm grows and warps and twists; and then, just when it looks like it&amp;#8217;s destined to become a wretched mess; it simply evaporates into a lovely little three line nested loop.&lt;/p&gt;


	&lt;p&gt;We see the principle at work in other ways as well.  Often the programmers have a whole list of tests that they know must pass.  As they write them one by one, they write the production code that satisfies them.  Then, as in the &lt;a href="http://butunclebob.com/ArticleS.UncleBob.TheBowlingGameKata"&gt;Bowling Game Kata&lt;/a&gt; the tests start to pass unexpectedly.  You were done with the code, and you weren&amp;#8217;t aware of it.  You continue writing tests, expecting one to fail, but they all pass.  The test code grows, but the production code remains the same.&lt;/p&gt;


	&lt;p&gt;Sometimes this happens in a less surprising way.  Sometimes you &lt;em&gt;know&lt;/em&gt; that you have implemented an algorithm that will pass all remaining tests, but you write those tests anyway because they are part of the specification&lt;/p&gt;


	&lt;p&gt;The point is that test code and production code do not grow at the same rate.  Indeed, as the application increases in complexity, the test code grows at a rate that is faster than the production code.  Sometimes the production code actually shrinks as the test code grows because the programmers moved a load of functionality out of the code and into the data.&lt;/p&gt;


	&lt;p&gt;Consider FitNesse.  A year ago there were 45,000 lines of code, of which 15,000 were tests, so 33% of the total were tests.&lt;/p&gt;


	&lt;p&gt;Now Fitnesse is 58,000 lines of code of which 26,000 are tests.  We added 13,000 lines of code overall, but 8,000 (61%), are tests! The tests have grown to over 44% of the total.&lt;/p&gt;</description>
      <pubDate>Thu, 06 Aug 2009 14:23:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:69954d56-0bc3-481c-86db-474de0f760e4</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2009/08/06/as-the-tests-get-more-specific-the-code-gets-more-generic</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Uncle Bob, JSPS: Learning Clojure</title>
      <description>&lt;p&gt;(JSPS: Just Some Poor Schmuck)&lt;/p&gt;


	&lt;p&gt;I&amp;#8217;m trying to learn &lt;a href="http://clojure.org/"&gt;Clojure&lt;/a&gt;, and I&amp;#8217;m finding the effort challenging.  Perhaps you can help me.&lt;/p&gt;


	&lt;p&gt;Programming in Clojure (A derivative of Lisp) requires a certain &amp;#8220;inside-out&amp;#8221; thinking.  I&amp;#8217;m finding the combination of the shift in thought process and &lt;span class="caps"&gt;TDD&lt;/span&gt; quite difficult to resolve.  So I thought I&amp;#8217;d ask for your help.&lt;/p&gt;


	&lt;p&gt;Below is the &lt;a href="http://butunclebob.com/ArticleS.UncleBob.TheBowlingGameKata"&gt;Bowling Game&lt;/a&gt; written in Clojure complete with unit tests.  I&amp;#8217;m not at all pleased with the result.  The tests, especially, look bizzare and backwards to me.&lt;/p&gt;


	&lt;p&gt;Please post your own solutions to this so that we can all compare and contrast them.&lt;/p&gt;


	&lt;h2&gt;Tests&lt;/h2&gt;


&lt;pre&gt;
(ns bowling-game)
(use 'clojure.contrib.test-is)
(use 'bowling-game)

(defn roll-list [game list]
  (if (empty? list)
    game
    (roll-list (roll game (first list)) (rest list))
    ))

(defn roll-many [game n pins]
  (loop [i n g game]
    (if (zero? i)
      g
      (recur (dec i) (roll g pins)))))

(defn gutter-game [game] (roll-many game 20 0))

(deftest can-create-game
  (is (not (nil? (new-game)))))

(deftest gutter-game-should-score-0
  (is (= 0 (score (gutter-game (new-game))))))

(deftest all-ones-should-score-20
  (is (= 20 (score (roll-many (new-game) 20 1)))))

(deftest one-spare
  (is (= 16 (score
    (roll-many
      (roll-list (new-game) [5 5 3])
      17 0)))))

(deftest one_strike
  (is (= 24 (score
    (roll-many
      (roll-list (new-game) [10 3 4])
      16 0)))))

(deftest perfect-game
  (is (= 300 (score (roll-many (new-game) 12 10)))))

(run-tests 'bowling-game)
&lt;/pre&gt;

	&lt;h2&gt;Code&lt;/h2&gt;


&lt;pre&gt;
(ns bowling-game)
(defn new-game [] [])

(defn next-two-balls [rolls]
  (+ (rolls 0) (rolls 1)))

(defn score-strike [rolls]
  [1 (+ 10 (+ (rolls 1) (rolls 2)))])

(defn score-spare [rolls]
  [2 (+ 10 (rolls 2))])

(defn score-no-mark [rolls]
  [2 (next-two-balls rolls)])

(defn score-next-frame [rolls]
  (if (= 10 (first rolls))
    (score-strike rolls)
    (if (= 10 (next-two-balls rolls))
      (score-spare rolls)
      (score-no-mark rolls))))

(defn score [game]
  (loop [frame 1 rolls game score 0]
    (if (&amp;gt; frame 10)
      score
      (let [frame-score (score-next-frame rolls)]
        (recur (inc frame) (subvec rolls (frame-score 0)) (+ score (frame-score 1)))))))

(defn roll [game pins]
  (conj game pins))
&lt;/pre&gt;</description>
      <pubDate>Sun, 19 Jul 2009 21:10:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:23b5c784-3251-492b-ac4f-77492c3b576f</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2009/07/19/uncle-bob-jsps-learning-clojure</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>The Rush</title>
      <description>&lt;p&gt;There&amp;#8217;s nothing like the feeling of achievement when you get a complex software system working.  It&amp;#8217;s the feeling of the hunter making a hard fought kill.  By the sheer power of your intellect you have imposed your will upon inanimate nature, and forced it to do your bidding.  You feel the &lt;em&gt;rush&lt;/em&gt; of power, the satisfaction of victory.  You are the master!&lt;/p&gt;


	&lt;p&gt;That&amp;#8217;s the good news.&lt;/p&gt;


	&lt;p&gt;The bad news is that you&amp;#8217;ve made a mess of things along the way.&lt;/p&gt;


	&lt;p&gt;This is inevitable.  It takes a great deal of focus and endurance to get a system working just right.  While you are consumed by that focus, you have little room for niceties like small functions, nice names, decoupling, and cleanliness.&lt;/p&gt;


	&lt;p&gt;My apprentice and I just finished achieving a major milestone in FitNesse.  It used to be that each new release of FitNesse was contained in a zip file that had all the files and directories laid out just perfectly.  This is great for a brand new installation, but doesn&amp;#8217;t work so well when you are upgrading.  What we managed to get working last night was the ability for FitNesse to self-install from it&amp;#8217;s jar file.  Now, whether you are installing for the first time, or just upgrading, FitNesse will install itself into your environment appropriately.&lt;/p&gt;


	&lt;p&gt;If you&amp;#8217;ve ever written a self-install like this, you know there are lots of niggling little details to attend to.  While the problem is conceptually simple, the realization is a maze of complexity.&lt;/p&gt;


	&lt;p&gt;Last night, with dinner waiting on the table and getting cold, we got the last little problem licked, and saw the whole self-installation work as we wanted.  We congratulated each other with a high-five, and then went upstairs to eat a well-deserved meal.  Later that evening I went down to the office and checked in the code.&lt;/p&gt;


	&lt;p&gt;This morning I woke up, and while in the shower, I realized that we had a lot of work left to do.  We need to go back over all that code and clean it up.  I&amp;#8217;m sure we left a swath of detritus while on the hunt.&lt;/p&gt;


	&lt;p&gt;The rush of victory should never be confused with the cold and crystalline concept of &lt;em&gt;done&lt;/em&gt;.  Once you get your systems to work, you still have to go back and clean up the wreckage left behind by the victorious battle.  You are not &lt;em&gt;done&lt;/em&gt; until the victorious code has been cleaned, polished, and oiled.&lt;/p&gt;</description>
      <pubDate>Fri, 26 Jun 2009 08:40:13 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:ff86f7eb-465c-43d7-8584-e9f35b3dc900</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2009/06/26/the-rush</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Software Craftsmanship</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Clean Code and Battle Scarred Architecture</title>
      <description>&lt;p&gt;If you go &lt;a href="http://internal.objectmentor.com:9090/job/fitnesse/crap/"&gt;here&lt;/a&gt; you&amp;#8217;ll see that I struggle to keep the &lt;a href="http://www.crap4j.org/"&gt;&lt;span class="caps"&gt;CRAP&lt;/span&gt;&lt;/a&gt; out of FitNesse.  Despite the whimsical name of this metric (which I take a perverse delight in), I find it to be remarkably useful.&lt;/p&gt;


	&lt;p&gt;&lt;span class="caps"&gt;CRAP&lt;/span&gt; is a metric that is applied to each function in the system.  The formula for &lt;span class="caps"&gt;CRAP&lt;/span&gt; is:
&lt;acronym title="f"&gt;CRAP&lt;/acronym&gt; = comp(f)&lt;sup&gt;2.&lt;/sup&gt; X (1 &amp;#8211; cov(f)/100)&lt;sup&gt;3.&lt;/sup&gt; + comp(f)&lt;/p&gt;


	&lt;p&gt;Where comp(f) = the cyclomatic complexity of the function f.
and cov(f) = the unit test coverage of function f.&lt;/p&gt;


	&lt;p&gt;So a function&amp;#8217;s &lt;span class="caps"&gt;CRAP&lt;/span&gt; will be small iff the cyclomatic complexity is low and the test coverage is high.  &lt;span class="caps"&gt;CRAP&lt;/span&gt; will be &lt;em&gt;huge&lt;/em&gt; if cyclomatic complexity is high, and there is no coverage.&lt;/p&gt;


	&lt;p&gt;What does this have to do with architecture?  Read on&amp;#8230;&lt;/p&gt;


	&lt;p&gt;I work very hard to keep the ratio of crappy methods near .1%.  Of the 5643 methods in FitNesse, only 6 are crappy, and five of those I have no control over.&lt;/p&gt;


	&lt;p&gt;If you study the graph you can see how quickly I react to even the slightest uptick in crap.  I don&amp;#8217;t tolerate it because it means that either I&amp;#8217;ve got a horrifically complex method that needs to be refactored, or (and this is far more likely) I&amp;#8217;ve got a method that isn&amp;#8217;t sufficiently tested.&lt;/p&gt;


	&lt;p&gt;Why am I so fastidious about this?  Why am I so concerned about keeping the crap out of FitNesse?  The reason is pretty simple.  It&amp;#8217;s the &lt;em&gt;least&lt;/em&gt; I can do.&lt;/p&gt;


	&lt;p&gt;If you look inside of FitNesse, you&amp;#8217;ll find that there are lots of structures and decisions that don&amp;#8217;t seem to make a lot of sense at first reading.  There are complexities and abstractions that will leave you shaking your head.&lt;/p&gt;


	&lt;p&gt;For example.  We generate all our &lt;span class="caps"&gt;HTML&lt;/span&gt; &lt;em&gt;in code&lt;/em&gt;.  Yes, you read that correctly.  We write Java code that constructs &lt;span class="caps"&gt;HTML&lt;/span&gt;.  And yes, that means we are slinging angle brackets around.&lt;/p&gt;


	&lt;p&gt;To be fair, we&amp;#8217;ve managed to move most of the angle bracket slingers into a single module that hides the &lt;span class="caps"&gt;HTML&lt;/span&gt; construction behind an abstraction barrier.  This helps a lot, but &lt;em&gt;cripe&lt;/em&gt; who would sling angle brackets when template system are so prevalent?  I hope nobody.  But FitNesse was not conceived at a time when template systems made sense (at least to us).&lt;/p&gt;


	&lt;p&gt;Fear not, I am working through the Fitnesse code replacing the &lt;span class="caps"&gt;HTML&lt;/span&gt; generation with Velocity templates.  It&amp;#8217;ll take some time, but I&amp;#8217;ll get it done.  The point is, that just like every other software system you&amp;#8217;ve seen, FitNesse is a collection of historical compromises.  The architecture shows the scars of many decisions that have since had to be reversed or deeply modified.&lt;/p&gt;


	&lt;p&gt;What does this have to do with &lt;span class="caps"&gt;CRAP&lt;/span&gt;?  Simply this.  The battle scarred architecture is something that will never really go away.  I can stop the bleeding, and disinfect the wounds, but there will always be evidence of the battle.&lt;/p&gt;


	&lt;p&gt;That scarring makes the system hard to understand.  It complicates the job of adding features and fixing bugs.  It decreases the effectiveness of the developers who work on FitNesse.  And though I work hard to massage the scars and bandage the wounds,  the war goes on.&lt;/p&gt;


	&lt;p&gt;&lt;em&gt;But I can keep the &lt;span class="caps"&gt;CRAP&lt;/span&gt; out!&lt;/em&gt;  I &lt;em&gt;can&lt;/em&gt; keep the code so clean and simple at the micro level, that the poor folks who try to make sense out of the macro scale aren&amp;#8217;t impeded by huge deeply nested functions that aren&amp;#8217;t tested!&lt;/p&gt;


	&lt;p&gt;Think of it this way.  &lt;span class="caps"&gt;CRAP&lt;/span&gt; is disease at the cellular level.  &lt;span class="caps"&gt;CRAP&lt;/span&gt; is a rot so pervasive that it can infest every nook and cranny of the system.  My system may have scars, &lt;em&gt;but it&amp;#8217;s not diseased!&lt;/em&gt;  In fact, despite the evidence of battles long past, the FitNesse code is &lt;em&gt;very&lt;/em&gt; healthy.&lt;/p&gt;


	&lt;p&gt;And I aim to keep it that way.&lt;/p&gt;</description>
      <pubDate>Wed, 20 May 2009 17:35:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:33c6eb39-6431-415a-9e68-edea9078cdd0</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2009/05/20/clean-code-and-battle-scarred-architecture</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Agile Methods</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Crap Code Inevitable?  Rumblings from ACCU.</title>
      <description>&lt;p&gt;I gave the opening Keynote at &lt;a href="http://accu.org/index.php/conferences/accu_conference_2009"&gt;&lt;span class="caps"&gt;ACCU 2009&lt;/span&gt;&lt;/a&gt; on Wednesday.  It was entitled: &lt;em&gt;The Birth of Craftsmanship&lt;/em&gt;.  Nicolai Josuttis finshed the day with the closing keynote: &lt;em&gt;Welcome Crappy Code &amp;#8211; The Death of Code Quality&lt;/em&gt;.  It was like a blow to the gut.&lt;/p&gt;


	&lt;p&gt;In my keynote I attempted to show the historical trajectory that has led to the emergence of the &lt;a href="http://manifesto.softwarecraftsmanship.org/"&gt;software craftsmanship&lt;/a&gt; movement.  My argument was that since the business practices of &lt;span class="caps"&gt;SCRUM&lt;/span&gt; have been widely adopted, and since teams who follow those practices but do not follow the technical practices of XP experience a relentless decrease in velocity, and since that decrease in velocity is &lt;em&gt;exposed&lt;/em&gt; by the transparency of scrum, then if follows that the eventual adoption of those technical XP practices is virtually assured.  My conclusion was that Craftsmanship was the &amp;#8220;next big thing&amp;#8221; (tm) that would capture the attention of our industry for the next few years, driven by the business need to increase velocity.  (See Martin Fowler&amp;#8217;s blog on &lt;a href="http://martinfowler.com/bliki/FlaccidScrum.html"&gt;Flaccid Scrum&lt;/a&gt;)  In short, we are on a trajectory towards a higher degree of professionalism and craftsmanship.&lt;/p&gt;


	&lt;p&gt;Nicolai&amp;#8217;s thesis was the exact opposite of mine.  His argument was that we are all ruled by marketing and that businesses will do whatever it takes to cut costs and increase revenue, and therefore businesses will drive software quality inexorably downward.  He stipulated that this will necessarily create a crisis as the defect rates and deadline slips increased, but that all attempts to improve quality would be short lived and followed by a larger drive to decrease quality even further.&lt;/p&gt;


	&lt;p&gt;Josuttis&amp;#8217; talk was an hour of highly depressing rhetoric couched in articulate delivery and brilliant humor.  One of the more memorable moments came when he playacted how a manger would respond to a developer&amp;#8217;s plea to let them write clean code like Uncle Bob says.  The manager replies: &amp;#8220;I don&amp;#8217;t care what Uncle Bob says, and if you don&amp;#8217;t like it you can leave and take Uncle Bob with you.&amp;#8221;&lt;/p&gt;


	&lt;p&gt;One of the funnier moments came when Josuttis came up with his rules for crap code, one of which was &amp;#8220;Praise Copy and Paste&amp;#8221;.  Here he showed the evolution of a module from the viewpoint of clean code, and then from the viewpoint of copy-paste.  His conclusion, delivered with a lovely irony, was the the copy-paste solution was more maintainable because it was clear which code belonged to which version.&lt;/p&gt;


	&lt;p&gt;It was at this point that I thought that this whole talk was a ribald joke, an elaborate spoof.  I predicted that he was about to turn the tables on everyone and ringingly endorse the craftsmanship movement.&lt;/p&gt;


	&lt;p&gt;Alas, it was not so. In the end he said that he was serious about his claims, and that he was convinced that crap code would dominate our future.  And then he gave his closing plea which went like this:&lt;/p&gt;


	&lt;p&gt;We finally accepted that requirements change, and so we invented Agile.&lt;/p&gt;


	&lt;p&gt;We must finally accept that code will be crap and so we must ???&lt;/p&gt;


	&lt;p&gt;He left the question marks on the screen and closed the talk.&lt;/p&gt;


	&lt;p&gt;This was like a blow to the gut.  The mood of the conference changed, at least for me, from a high of enthralled geekery, to depths of hoplessness and feelings of futile striving against the inevitable. Our cause was lost.  Defeat was imminent.  There was no hope.&lt;/p&gt;


	&lt;p&gt;&lt;strong&gt;Bulls Bollocks!&lt;/strong&gt;&lt;/p&gt;


	&lt;p&gt;To his credit, there are a few things that Josuttis got right.  There &lt;em&gt;is&lt;/em&gt; a lot of crap code out there.  And there &lt;em&gt;is&lt;/em&gt; a growing cohort of crappy coders writing that crap code.&lt;/p&gt;


	&lt;p&gt;But the solution to that is not to give up and become one of them.  The solution to that is to design our systems so that they don&amp;#8217;t require an army of maintainers slinging code.  Instead we need to design our systems such that the vast majority of changes can be implemented in DSLs that are tuned to business needs, and do not require &amp;#8220;programmers&amp;#8221; to maintain.&lt;/p&gt;


	&lt;p&gt;The thing that Josuttis got completely wrong, in my mildly arrogant opinion, is the notion that low quality code is cheaper than high quality code.  Low quality code is &lt;em&gt;not&lt;/em&gt; cheaper; it is &lt;em&gt;vastly&lt;/em&gt; more expensive, even in the short term.  Bad code slows everyone down from the minute that it is written.  It creates a continuous and copious drag on further progress. It requires armies of coders to overcome that drag; and those armies must grow exponentially to maintain constant velocity against that drag.&lt;/p&gt;


	&lt;p&gt;This strikes at the very heart of Josuttis&amp;#8217; argument.  His claim that crappy code is inevitable is based on the notion that crappy code is cheaper than clean code, and that therefore businesses will demand the crap every time.  But it has generally not been &lt;em&gt;business&lt;/em&gt; that has demanded crappy code.  Rather it has been &lt;em&gt;developers&lt;/em&gt; who mistakenly thought that the business&amp;#8217; need for speed meant that they had to produce crappy code.  Once &lt;em&gt;we&lt;/em&gt;, as &lt;em&gt;professional developers&lt;/em&gt;, realize that the only way to go fast is to create clean and well designed code, then we will see the business&amp;#8217; need for speed as a demand for high quality code.&lt;/p&gt;


	&lt;p&gt;My vision of the future is quite different from Josuttis&amp;#8217;.  I see software developers working together to create a discipline of craftsmanship, professionalism, and quality similar to the way that doctors, lawyers, architects, and many other professionals and artisans have done.  I see a future where team velocities increase while development costs decrease because of the steadily increasing skill of the teams.    I see a future where large software systems are engineered by relatively small teams of craftsmen, and are configured and customized by business people using DSLs tuned to their needs.&lt;/p&gt;


	&lt;p&gt;I see a future of &lt;em&gt;Clean Code&lt;/em&gt;, Craftsmanship, Professionalism, and an overriding imperative for Code Quality.&lt;/p&gt;</description>
      <pubDate>Thu, 23 Apr 2009 04:56:22 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:3032f508-8860-43f1-a16b-5b26b563999d</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2009/04/23/crap-code-inevitable-rumblings-from-accu</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Software Craftsmanship</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Is the Supremacy of Object-Oriented Programming Over?</title>
      <description>&lt;p&gt;I never expected to see this. When I started my career, Object-Oriented Programming (OOP) was going mainstream. For many problems, it was and still is a natural way to &lt;em&gt;modularize&lt;/em&gt; an application. It grew to (mostly) rule the world. Now it seems that the supremacy of objects may be coming to an end, of sorts.&lt;/p&gt;


	&lt;p&gt;I say this because of recent trends in our industry and my hands-on experience with many enterprise and Internet applications, mostly at client sites. You might be thinking that I&amp;#8217;m referring to the mainstream breakout of Functional Programming (FP), which is happening right now. The &lt;em&gt;killer app&lt;/em&gt; for FP is concurrency. We&amp;#8217;ve all heard that more and more applications must be concurrent these days (which doesn&amp;#8217;t necessarily mean multithreaded). When we remove side effects from functions and disallow mutable variables, our concurrency issues largely go away. The success of the Actor model of concurrency, as used to great effect in &lt;a href="http://erlang.org/"&gt;Erlang&lt;/a&gt;, is one example of a functional-style approach. The rise of &lt;a href="http://labs.google.com/papers/mapreduce.html"&gt;map-reduce&lt;/a&gt; computations is another example of a functional technique going mainstream. A related phenomenon is the emergence of key-value store databases, like &lt;a href="http://labs.google.com/papers/bigtable.html"&gt;BigTable&lt;/a&gt; and &lt;a href="http://couchdb.apache.org/"&gt;CouchDB&lt;/a&gt;, is a reaction to the overhead of &lt;span class="caps"&gt;SQL&lt;/span&gt; databases, when the performance cost of the Relational Model isn&amp;#8217;t justified. These databases are typically managed with functional techniques, like map-reduce.&lt;/p&gt;


	&lt;p&gt;But actually, I&amp;#8217;m thinking of something else. Hybrid languages like &lt;a href="http://scala-lang.org"&gt;Scala&lt;/a&gt;, &lt;a href="http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/"&gt;F#&lt;/a&gt;, and &lt;a href="http://caml.inria.fr/ocaml/index.en.html"&gt;OCaml&lt;/a&gt; have demonstrated that &lt;span class="caps"&gt;OOP&lt;/span&gt; and FP can complement each other. In a given context, they let you use the idioms that make the most sense for your particular needs. For example, immutable &amp;#8220;objects&amp;#8221; and functional-style pattern matching is a killer combination.&lt;/p&gt;


	&lt;p&gt;What&amp;#8217;s really got me thinking that objects are losing their supremacy is a very mundane problem. It&amp;#8217;s a problem that isn&amp;#8217;t new, but like concurrency, it just seems to grow worse and worse.&lt;/p&gt;


	&lt;p&gt;The problem is that there is never a stable, clear object model in applications any more. What constitutes a &lt;code&gt;BankAccount&lt;/code&gt; or &lt;code&gt;Customer&lt;/code&gt; or whatever is fluid. It changes with each iteration. It&amp;#8217;s different from one subsystem to another even within the &lt;em&gt;same&lt;/em&gt; iteration! I see a lot of misfit object models that try to be all things to all people, so they are bloated and the teams that own them can&amp;#8217;t be agile. The other extreme is &amp;#8220;balkanization&amp;#8221;, where each subsystem has its own model. We tend to think the latter case is bad. However, is lean and mean, but non-standard, worse than bloated, yet standardized?&lt;/p&gt;


	&lt;p&gt;The fact is, for a lot of these applications, it&amp;#8217;s just data. The ceremony of object wrappers doesn&amp;#8217;t carry its weight. Just put the data in a hash map (or a list if you don&amp;#8217;t need the bits &amp;#8220;labeled&amp;#8221;) and then process the collection with your iterate, map, and reduce functions. This may sound heretical, but how much Java code could you delete today if you replaced it with a stored procedure?&lt;/p&gt;


	&lt;p&gt;These alternatives won&amp;#8217;t work for all situations, of course. Sometimes polymorphism carries its weight. Unfortunately, it&amp;#8217;s too tempting to use objects as if more is always better, like &lt;a href="http://www.google.com/search?client=safari&amp;#38;rls=en-us&amp;#38;q=more+cowbell&amp;#38;ie=UTF-8&amp;#38;oe=UTF-8"&gt;cow bell&lt;/a&gt;.&lt;/p&gt;


	&lt;p&gt;So what would replace objects for supremacy? Well, my point is really that there is no one true way. We&amp;#8217;ve led ourselves down the wrong path. Or, to be more precise, we followed a single, very good path, but we didn&amp;#8217;t know when to take a different path.&lt;/p&gt;


	&lt;p&gt;Increasingly, the best, most nimble designs I see use objects with a light touch; shallow hierarchies, small objects that try to obey the Single Responsibility Principle, composition rather than inheritance, &lt;em&gt;etc.&lt;/em&gt; Coupled with a liberal use of functional idioms (like iterate, map, and reduce), these designs strike the right balance between the protection of data hiding &lt;em&gt;vs.&lt;/em&gt; openness for easy processing. By the way, you can build these designs in almost any of our popular languages. Some languages make this easier than others, of course.&lt;/p&gt;


	&lt;p&gt;Despite the hype, I think &lt;a href="http://www.martinfowler.com/bliki/DomainSpecificLanguage.html"&gt;Domain-Specific Languages&lt;/a&gt; (DSLs) are also very important and worth mentioning in this context. (&lt;a href="http://en.wikipedia.org/wiki/Language-oriented_programming"&gt;Language-Oriented Programming&lt;/a&gt; &amp;#8211; &lt;span class="caps"&gt;LOP&lt;/span&gt; &amp;#8211; generalizes these ideas). It&amp;#8217;s true that people drink the &lt;span class="caps"&gt;DSL&lt;/span&gt; Kool-Aid and create a mess. However, when used appropriately, DSLs reduce a program to its &lt;a href="http://en.wikipedia.org/wiki/Essential_complexity"&gt;essential complexity&lt;/a&gt;, while hiding and modularizing the &lt;a href="http://en.wikipedia.org/wiki/Accidental_complexity"&gt;accidental complexity&lt;/a&gt; of the implementation. When it becomes easy to write a user story in code, we won&amp;#8217;t obsess as much over the details of a &lt;code&gt;BankAccount&lt;/code&gt; as they change from one story to another. We will embrace more flexible data persistence models, too.&lt;/p&gt;


	&lt;p&gt;Back to &lt;span class="caps"&gt;OOP&lt;/span&gt; and FP, I see the potential for their combination to lead to a rebirth of the old vision of &lt;em&gt;software components&lt;/em&gt;, but that&amp;#8217;s a topic for another blog post.&lt;/p&gt;</description>
      <pubDate>Mon, 20 Apr 2009 21:45:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:69ac398f-694c-4e0b-bc13-a8765608f6cf</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2009/04/20/is-the-supremacy-of-object-oriented-programming-over</link>
      <category>Dean's Deprecations</category>
      <category>Agile Methods</category>
      <category>Design Principles</category>
      <category>Clean Code</category>
      <category>design</category>
      <category>OOP</category>
      <category>FP</category>
      <category>polyglot</category>
      <category>Polyparadigm</category>
      <category>Scala</category>
      <category>F</category>
      <category>OCaml</category>
      <category>MapReduce</category>
      <category>BigTable</category>
      <category>CouchDB</category>
      <category>SQL</category>
      <category>dsl</category>
      <category>LOP</category>
    </item>
    <item>
      <title>Let's Hear it for the Zealots!</title>
      <description>&lt;p&gt;In his March 1st, 2009 &lt;a href="http://www.sdtimes.com/link/33300"&gt;column&lt;/a&gt; in SDTimes, Andrew Binstock takes the &amp;#8220;Zealots of Agile&amp;#8221; to task for claiming that Agile is the &lt;em&gt;one true way&lt;/em&gt;.  He made the counter-argument that non-agile projects have succeeded, and that agile projects have failed.  He implied that the attitudes of the agile zealots are blind to these facts.&lt;/p&gt;


	&lt;p&gt;What a load of dingoes kidneys!&lt;/p&gt;


	&lt;p&gt;There is a difference between a zealot, and a religious fanatic.  A religious fanatic cannot envision themselves to be wrong.  We in the agile community may indeed be zealots, but we know we can be wrong.  We know that projects succeeded before agile, and we know that agile projects have failed.  We know that there are other schools of thought that are just as valid as ours.  Indeed, most of us expect (even hope!) that agile will be superseded by something better one day.&lt;/p&gt;


	&lt;p&gt;Some of you may remember my keynote address at the 2002 XPUniverse in Chicago.  My son, Micah, and I got up in front of the group dressed in Jiu Jistsu garb, and commenced to do a martial arts demonstration.&lt;/p&gt;


	&lt;p&gt;After the demonstration I made the point that a student of Karate could have given an equally spellbinding, though quite different, show.  A student of Tae Kwon Do would amaze us with still other wonderful moves.  The morale, of course, was that there are many ways to get the job done.  There are many equally valid schools of thought.&lt;/p&gt;


	&lt;p&gt;However, the knowledge that there are other valid schools of thought does not dilute the zeal a student has for the school of thought he has chosen to study.  Do you think that a Jiu Jistsu master isn&amp;#8217;t a zealot?  You&amp;#8217;d better believe he is!  To be great, one must have zeal.  To rail against zeal is to rail against the desire for greatness.  It is &lt;em&gt;zeal&lt;/em&gt; that makes you go the extra distance to become great.  The Jiu Jitsu master may respect the Karate master, but his goal is to become great at Jiu Jitsu.&lt;/p&gt;


	&lt;p&gt;So I think it is &lt;em&gt;healthy&lt;/em&gt; that agile proponents are vociferous advocates of their school of thought.  They are like Karate students who are excited about their new skills, and want to teach those skills to others.  If their zeal to excel can infect others with similar zeal, so much the better.  We &lt;em&gt;need&lt;/em&gt; people in this industry who want to excel.&lt;/p&gt;


	&lt;p&gt;In his column Andrew derided agile zealots for claiming that Agile was the &lt;em&gt;one true path&lt;/em&gt;.  I don&amp;#8217;t know of any prominent agile advocate who has ever made that claim.  Indeed, when Kent Beck and I sat down in 1999 to plan out the XP Immersion training, we were very concerned that we might turn the XP movement into a religion.  We did not want to create the impression that XPers were the chosen people and that wisdom would die with us.  So we were, in fact, very careful to avoid any hint of the &amp;#8220;one true path&amp;#8221; argument.&lt;/p&gt;


	&lt;p&gt;As evidence of this, consider the Snowbird meeting in 2001.  That meeting was &lt;em&gt;inclusive&lt;/em&gt;, not exclusive.  We invited people from all over the spectrum to join us there.  &lt;span class="caps"&gt;DSDM&lt;/span&gt;, FDD, Scrum, Crystal, &lt;span class="caps"&gt;MDA&lt;/span&gt;, &amp;#38; &lt;span class="caps"&gt;RUP&lt;/span&gt; were all represented; and the agile manifesto (Yes, Andrew, Manifesto![1]) was the result.  That manifesto was a simple statement of values, not a claim to deific knowledge.&lt;/p&gt;


	&lt;p&gt;Am I an Agile Zealot?  Damned right I am!  Do I think Agile is the best way to get software done?  Damned right I do!  I wouldn&amp;#8217;t be doing Agile if I didn&amp;#8217;t think it was best.  Do I think Agile is better than someone else&amp;#8217;s school of thought?  Let me put it this way: I&amp;#8217;m quite happy to go head to head against someone who follows another school of thought.  I believe I&amp;#8217;d code him right into the ground!  Isn&amp;#8217;t that what any good student of his craft would think?  But I also recognize that one day I&amp;#8217;ll lose that competition, and that will be a great day for me because it will give me the opportunity to learn something new and better.&lt;/p&gt;


	&lt;p&gt;Andrew also mentioned that Kent Beck and I are so obsessed with our &amp;#8220;evangelical fervor&amp;#8221; that we: &amp;#8220;endlessly test and endlessly refine and refactor code to the point that it becomes an all-consuming diversion that does not advance the project&amp;#8221;.  &lt;span class="caps"&gt;WTF&lt;/span&gt;?  I&amp;#8217;ve been making monthly releases of FitNesse, and Kent has been cranking out releases of JunitMax; neither of us has been so busy gilding our respective lilies that we are failing to move our respective projects forward. Look around Andrew, we&amp;#8217;re shipping code over here brother.&lt;/p&gt;


	&lt;p&gt;As part of his rant against our &amp;#8220;evangelical fervor&amp;#8221; Andrew asked this rather snide question: &amp;#8220;I broke up that code into a separate class and added seven methods for what benefit, again?&amp;#8221;  This would appear to be a dig against refactoring &amp;#8211; or perhaps &lt;em&gt;excess&lt;/em&gt; refactoring.  Still the question has a simple answer.  We would only break up a module into a class with seven methods if that module was big, ugly, and complex, and by breaking it up we made it simple and easy to understand and modify.  It seems to me that leaving the module in a messy state is irresponsible and unprofessional.&lt;/p&gt;


	&lt;p&gt;Andrew complains that there is very little Agile experience with projects over six million lines of code.  I&amp;#8217;m not sure where he got that number from, perhaps he&amp;#8217;s been watching Steve Austin re-runs.  Actually, the majority of my 2008 consulting business has been with very large companies with products &lt;em&gt;well&lt;/em&gt; over six million lines of code.  Agile-in-the-Large is the name of the game in those companies!&lt;/p&gt;


	&lt;p&gt;Finally, Andrew says Michael Feathers is a &amp;#8220;moderate&amp;#8221; Agile proponent.  This is the same Michael Feathers who wrote a book defining Legacy code as code without tests &amp;#8211; hardly a moderate point of view.  Michael is a master, not a moderate.&lt;/p&gt;


	&lt;p&gt;I think Andrew has fallen into a common trap.  He sees the zeal of the agile proponents and mistakes it for religious fanaticism.  Instead of respecting that zeal as the outward manifestation of the inward desire to excel, he rails against it as being myopic and exclusive and then views all the statements of the agile proponents through that clouded viewport.  Once you have decided that someone is a religious fanatic, it is difficult to accept anything they say.&lt;/p&gt;


	&lt;p&gt;I think standing against religious fanaticism in the software community is a good thing.  I also think that those of us who are zealous must constantly watch that we are not also becoming blind to our own weaknesses and exclusive in our outlook.  But I could wish that those who fear religious fanaticism as much as I do would stop confusing it with professional zeal.&lt;/p&gt;


	&lt;p&gt;So here&amp;#8217;s the bottom line.  People who excel are, by definition, zealots.  People who aren&amp;#8217;t zealous, do not excel. So there&amp;#8217;s nothing wrong with being a zealot; indeed, zeal is a very positive emotion. The trick to being a zealot is to be mindful that the day will eventually come when some other zealot from a different school of thought will code you into the ground.  When that happens, you should thank him for showing you a better way.&lt;/p&gt;


	&lt;p id="fn1"&gt;&lt;sup&gt;1&lt;/sup&gt; I kicked off the Snowbird meeting by challenging the group to write a &amp;#8220;manifesto&amp;#8221;.  I chose the word &amp;#8220;manifesto&amp;#8221; because some years earlier I had read &lt;em&gt;The Object Oriented Database System Manifesto&lt;/em&gt; and I thought it was a clever use of the word.&lt;/p&gt;</description>
      <pubDate>Tue, 10 Mar 2009 16:58:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:7987e28e-935e-4303-b2e4-1e010beba6b7</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2009/03/10/lets-hear-it-for-the-zealots</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Software Craftsmanship</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Quality:  It's alive!  It's ALIVE!</title>
      <description>&lt;p&gt;Recently James Bach wrote a compelling post entitled &lt;a href="http://www.satisfice.com/blog/archives/224"&gt;Quality is Dead&lt;/a&gt;.  As much as I&amp;#8217;d like to agree, something interesting has just happened that tempts me to believe in a rebirth.&lt;/p&gt;


	&lt;p&gt;Just when James finally declares the death of quality, along comes the &lt;a href="http://manifesto.softwarecraftsmanship.org/main"&gt;Manifesto for Software Craftsmanship&lt;/a&gt;.  This simple document that builds upon the four values declared in the &lt;a href="http://agilemanifesto.org/"&gt;Agile Manifesto&lt;/a&gt; went live late on Friday evening.  Now, at 3PM on Saturday over 600 people have signed it!&lt;/p&gt;


	&lt;p&gt;What does this mean?  I think it means that many of us have seen what James was talking about, and are tired of it.  We don&amp;#8217;t want our users posting blogs &amp;#8211; as James did &amp;#8211; crying that they &lt;span class="caps"&gt;HATE&lt;/span&gt; us.  We want our users to be astonished by the elegance and simplicity of our creations.  We want other software developers to look under the hood and be amazed and impressed at the clarity and simplicity they see.&lt;/p&gt;


	&lt;p&gt;&lt;strong&gt;We want to be proud of our work!&lt;/strong&gt;&lt;/p&gt;


	&lt;p&gt;&lt;strong&gt;We want our quality back!&lt;/strong&gt;&lt;/p&gt;


	&lt;p&gt;And so a few weeks ago some software developers gathered at the offices of &lt;a href="http://www.8thlight.com/main"&gt;8th Light&lt;/a&gt; in Libertyville, Illinois, and began the process of creating this manifesto.  There followed a very active and passionate discussion in the &lt;a href="http://groups.google.com/group/software_craftsmanship?lnk=srg"&gt;Software Craftsmanship email group&lt;/a&gt;.  The end result was this manifesto.&lt;/p&gt;


	&lt;p&gt;I encourage all of you to read and sign the manifesto, join the email group, and help bring quality back to life in the software profession.&lt;/p&gt;</description>
      <pubDate>Sat, 07 Mar 2009 15:25:00 -0600</pubDate>
      <guid isPermaLink="false">urn:uuid:7fda0576-ab31-4f6b-bf1c-d87078134a6b</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2009/03/07/quality-its-alive-its-alive</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Software Craftsmanship</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Fudge anyone?</title>
      <description>&lt;p&gt;Back in September, when I was just staring the &lt;a href="http://fitnesse.org/FitNesse.TestSystems"&gt;Slim&lt;/a&gt; project, I made a crucial architectural decision.  I made it dead wrong.  And then life turned to fudge&amp;#8230;&lt;/p&gt;


	&lt;p&gt;The issue was simple.  Slim tables are, well, tables just like Fit tables are.  How should I parse these tables?  Fit parses &lt;span class="caps"&gt;HTML&lt;/span&gt;.  FitNesse parses wiki text &lt;em&gt;into&lt;/em&gt; HTML and delivers it to Fit.  Where should Slim fit in all of this?&lt;/p&gt;


	&lt;p&gt;Keep in mind that Fit &lt;em&gt;must&lt;/em&gt; parse &lt;span class="caps"&gt;HTML&lt;/span&gt; since it lives on the far side of the FitNesse/SUT boundary.  Fit doesn&amp;#8217;t have access to wiki text.  Slim tables, on the other hand, live on the &lt;em&gt;near&lt;/em&gt; side of the FitNesse/SUT boundary, and so have full access to wiki text, and the built in parsers that parse that text.&lt;/p&gt;


	&lt;p&gt;So it seemed to me that I had two options.&lt;/p&gt;


	&lt;ol&gt;
	&lt;li&gt;Follow the example of Fit and parse wiki text into &lt;span class="caps"&gt;HTML&lt;/span&gt;, and then have the Slim Tables parse the &lt;span class="caps"&gt;HTML&lt;/span&gt; in order to process the tables.  &lt;/li&gt;
		&lt;li&gt;Take advantage of the built in wiki text parser inside of FitNesse and bypass &lt;span class="caps"&gt;HTML&lt;/span&gt; altogether.&lt;/li&gt;
	&lt;/ol&gt;


	&lt;p&gt;I chose the latter of the two because the Parsing system of FitNesse is &lt;em&gt;trivial&lt;/em&gt; to use.  You just hand it a string of wiki text, and it hands you a nice little parse tree of wiki widgets.  All I had to do was walk that parse three and process my tables.  Voila!&lt;/p&gt;


	&lt;p&gt;This worked great!  In a matter of hours I was making significant progress on processing Slim decision tables.  Instead of worrying about parsing &lt;span class="caps"&gt;HTML&lt;/span&gt; and building my own parse tree, I could focus on the problems of translating tables into Slim directives and then using the return values from Slim to colorize the table.&lt;/p&gt;


	&lt;p&gt;&lt;em&gt;Generating&lt;/em&gt; html was no problem since that&amp;#8217;s what FitNesse does anyway.  All I had to do was modify the elements of the parse tree and then simply tell the tree to convert itself to &lt;span class="caps"&gt;HTML&lt;/span&gt;.  What a dream.&lt;/p&gt;


	&lt;p&gt;Or so it seemed.  Although things started well, progress started to slow before the week was out.  The problem was that the FitNesse parser is &lt;em&gt;tuned&lt;/em&gt; to the esoteric needs of FitNesse.  The parser makes choices that are perfectly fine if your goal is to generate &lt;span class="caps"&gt;HTML&lt;/span&gt; and pass it to Fit, but that aren&amp;#8217;t quite so nice when you&amp;#8217;re goal is to use the parse tree to process Slim tables.  As a simple example, consider the problem of literals.&lt;/p&gt;


	&lt;p&gt;In FitNesse, any camel case phrase fits the pattern of a wiki word and will be turned into a wiki link.  Sometimes, though, you want to use a camel case phrase and you &lt;em&gt;don&amp;#8217;t&lt;/em&gt; want it converted to a link.  In that case you surround the phrase with literal marks as follows: &lt;code&gt;!- FitNesse-!&lt;/code&gt;.  Anything between literal marks is simply ignored by the parser and passed through to the end.&lt;/p&gt;


	&lt;p&gt;Indeed, things inside of literals are not even escaped for html!  If you put &lt;code&gt;&amp;lt;b&amp;gt;hi&amp;lt;/b&amp;gt;&lt;/code&gt; into a wiki page, it will escape the text you&amp;#8217;ll see &lt;code&gt;&amp;lt;b&amp;gt;hi&amp;lt;/b&amp;gt;&lt;/code&gt; on the screen instead of a bold &amp;#8220;hi&amp;#8221;.  On the other hand, if you put &lt;code&gt;!- &amp;lt;b&amp;gt;hi&amp;lt;/b&amp;gt;-!&lt;/code&gt; on a page, then the &lt;span class="caps"&gt;HTML&lt;/span&gt; is left unescaped and a boldfaced &amp;#8220;hi&amp;#8221; &lt;em&gt;will&lt;/em&gt; appear on the screen.&lt;/p&gt;


	&lt;p&gt;I&amp;#8217;m telling you all of this because the devil is in the details&amp;#8212;so bear with me a bit longer.&lt;/p&gt;


	&lt;p&gt;You know how the C and C++ languages have a preprocessor?  This preprocessor handles all the &lt;code&gt;#include&lt;/code&gt; and &lt;code&gt;#define&lt;/code&gt; statements and then hands the resulting text off to the true compiler.  Well, the wiki parser works the same way!  Literals and &lt;code&gt;!define&lt;/code&gt; variables are processed first, by a different pass of the parser.  Then all the rest of the wiki widgets are parsed by the true parser.  The reason that we had to do this is even more devilishly detailed; so I&amp;#8217;ll spare you.  Suffice it to say that the reasons we need that preprocessor are similar to the reasons that C and C++ need it.&lt;/p&gt;


	&lt;p&gt;What does the preprocessor do with a literal?  It converts it into a special widget.  That widget looks like this: &lt;code&gt;!lit?23?&lt;/code&gt;  What does that mean?  It means replace me with the contents of literal #23.  You see, when FitNesse sees &lt;code&gt;!- FitNesse-!&lt;/code&gt; it replaces it with &lt;code&gt;!lit?nn?&lt;/code&gt; and squirrels &lt;code&gt;FitNesse&lt;/code&gt; away in literal slot &lt;em&gt;nn&lt;/em&gt;.  During the second pass, that &lt;code&gt;!lit?nn?&lt;/code&gt; is replaced with the contents of literal slot &lt;em&gt;nn&lt;/em&gt;.  Simple, right?&lt;/p&gt;


	&lt;p&gt;OK, now back to &lt;span class="caps"&gt;SLIM&lt;/span&gt; table processing.  There I was, in Norway, teaching a class during the day and coding Slim at night, and everything was going just great.  And then, during one of my tests, I happened to put a literal into one of the test tables.  This is perfectly normal, I didn&amp;#8217;t want some camel case phrase turned into a link.  But this perfectly normal gesture made a unit test fail for a very strange reason.  I got this wonderful message from junit: &lt;code&gt;expected MyPage but was !lit?3?&lt;/code&gt;&lt;/p&gt;


	&lt;p&gt;I knew exactly what this meant.  It meant that the value &lt;code&gt;MyPage&lt;/code&gt; had been squirreled away by the first pass of the parser.  I also knew that I had utterly no reasonable way of getting at it.  So I did the only thing any sane programmer would do.  I wrote my own preprocessor and used it instead of the standard one.  This was &amp;#8220;safe&amp;#8221; since in the end I simply reconvert all the colorized tables back into wiki text and let the normal parser render it into &lt;span class="caps"&gt;HTML&lt;/span&gt;.&lt;/p&gt;


	&lt;p&gt;It was a bit of work, but I got it done at one am on a cold Norwegian night.  Tests passing, everything great!&lt;/p&gt;


	&lt;p&gt;Ah, but no.  By writing my own preprocessor, I broke the &lt;code&gt;!define&lt;/code&gt; variable processing &amp;#8211; subtly.  And when I found and fixed that I had re-broken literal processing &amp;#8211; subtly.&lt;/p&gt;


	&lt;p&gt;If you were following my tweets at the time you saw me twitter ever more frantically about literals.  It was the proverbial ball of Mercury.  Every time I put my thumb on it&lt;sup&gt;&lt;a href="#fn1"&gt;1&lt;/a&gt;&lt;/sup&gt; it would squirt away and take some new form.&lt;/p&gt;


	&lt;p&gt;I fell into a trap.  I call it the &lt;em&gt;fudge trap&lt;/em&gt;.  It goes like this:&lt;/p&gt;


	&lt;p style="text-align:center;"&gt;&lt;span style="color:chocolate;"&gt;&lt;code&gt;forever do {&lt;/code&gt;&amp;#8220;I can make this work!  Just one more little fudge right &lt;em&gt;here&lt;/em&gt;!&amp;#8221;&lt;code&gt;}&lt;/code&gt;&lt;/span&gt;&lt;/p&gt;


	&lt;p&gt;I was in this trap for two months!  I was making progress, and getting lots of new features to work, but I was also running into strange little quirks and unexpected bizarre behaviors caused by the fudging I was doing.  So I&amp;#8217;d fudge a little more and then keep working.  But each little fudge added to the next until, eventually, I had a really nasty house of cards (or rather: pile of fudge) ready to topple every time I touched anything else.  I started to fear my own code&lt;sup&gt;&lt;a href="#fn2"&gt;2&lt;/a&gt;&lt;/sup&gt;.  It was time to stop!&lt;/p&gt;


	&lt;p&gt;I knew what I had to do.  I had to go back to my original architectural decision and make it the other way.  There was no escape from this.  The FitNesse parser was too coupled to the wiki-ness, and there was no sane way to repurpose it for test table processing.&lt;/p&gt;


	&lt;p&gt;I dreaded this.  It was such a big change.  I had built so much code in my house of fudge.  All of it would have to be changed or deleted.  And, worse, I needed to write an &lt;span class="caps"&gt;HTML&lt;/span&gt; parser.&lt;/p&gt;


	&lt;p&gt;I was lamenting to &lt;a href="http://www.8thlight.com/main"&gt;Micah&lt;/a&gt; about this one day in late November, and he said: &amp;#8220;Dad, there are &lt;span class="caps"&gt;HTML&lt;/span&gt; parsers out there you know.&amp;#8221;.&lt;/p&gt;


	&lt;p&gt;Uh&amp;#8230;&lt;/p&gt;


	&lt;p&gt;So I went to google and typed &lt;code&gt;Html Parser&lt;/code&gt;.  Duh.  There they were.  Lots and lots of shiny &lt;span class="caps"&gt;HTML&lt;/span&gt; parsers free for the using.&lt;/p&gt;


	&lt;p&gt;I picked &lt;a href="http://htmlparser.sourceforge.net"&gt;one&lt;/a&gt; and started to fiddle with it.  It was &lt;em&gt;easy&lt;/em&gt; to use.&lt;/p&gt;


	&lt;p&gt;Now comes the good part.  I had not been a complete dolt.  Even when I was using the FitNesse parse tree, I ate my own dogfood and &lt;em&gt;wrapped&lt;/em&gt; it in an abstract interface.  No part of the Slim Table processing code actually &lt;em&gt;knew&lt;/em&gt; that it was dealing with a FitNesse parse tree.  It simply used the abstract interface to get its work done.&lt;/p&gt;


	&lt;p&gt;That meant that pulling out the wiki parser and putting in the &lt;span class="caps"&gt;HTML&lt;/span&gt; parser was a matter of re-implementing the abstract interface with the output of the new parser (which happened to be another parse tree!).  This took me about a day.&lt;/p&gt;


	&lt;p&gt;There came a magic moment when I had &lt;em&gt;both&lt;/em&gt; the wiki text version of the parser, and the &lt;span class="caps"&gt;HTML&lt;/span&gt; version of the parser working.  I could switch back and forth between the two by changing one word in one module.  When I got &lt;em&gt;all&lt;/em&gt; my tests passing with &lt;em&gt;both&lt;/em&gt; parsers, I knew I was done.  And then the fun &lt;em&gt;really&lt;/em&gt; began!&lt;/p&gt;


	&lt;p&gt;I &lt;span style="color:red;"&gt;&lt;em&gt;deleted&lt;/em&gt;&lt;/span&gt; ever stitch of that wiki parse tree pile of fudge.  I tore it loose and rent it asunder.  It was gone, never to darken my door with it&amp;#8217;s fudge again.&lt;/p&gt;


	&lt;p&gt;It took me a day.  A day.  And the result is 400 fewer lines of code, and a set of Slim tables that actually work the way they are supposed to.&lt;/p&gt;


	&lt;p&gt;Moral #1: &amp;#8220;Fudge tastes good while you are eating it, but it makes you fat, slow, and dumb.&amp;#8221;&lt;/p&gt;


	&lt;p&gt;Moral #2: &amp;#8220;Eat the damned dog food. It&amp;#8217;ll save your posterior from your own maladroit decisions.&lt;/p&gt;


	&lt;p id="fn1"&gt;&lt;sup&gt;1&lt;/sup&gt; I do not recommend that you actually put your thumb on any Mercury.  Never mind that I used to play with liquid Mercury as a child, sloshing it around from hand to hand and endlessly stirring it with my finger.  Wiser heads than I have determined that merely being in the same room with liquid Mercury can cause severe brain damage, genetic corruption, and birth defects in your children, grandchildren, and pets.&lt;/p&gt;


	&lt;p id="fn2"&gt;&lt;sup&gt;2&lt;/sup&gt; Fearing your own code is an indicator that you are headed for ruin.  This fear is followed by self-loathing, project-loathing, career-loathing, divorce, infanticide, and finally chicken farming.&lt;/p&gt;</description>
      <pubDate>Wed, 31 Dec 2008 16:01:00 -0600</pubDate>
      <guid isPermaLink="false">urn:uuid:36578e35-eb79-4c39-bb15-e36e3acf4548</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2008/12/31/fudge-anyone</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>How to Guarantee That Your Software Will Suck</title>
      <description>&lt;p&gt;This blog is a quick comment about Justin Etheredge&amp;#8217;s &lt;a href="http://www.codethinked.com/post/2008/12/07/How-To-Guarantee-That-Your-Software-Will-Suck.aspx"&gt;blog&lt;/a&gt; by the same name.&lt;/p&gt;


	&lt;p&gt;I thought the blog was good.  Really.  No, I did.  It&amp;#8217;s a pretty good blog.  Honestly.&lt;/p&gt;


	&lt;p&gt;My problem with is is that it points the finger outwards.  It&amp;#8217;s as though software developers have no responsibility.  The blog seems to suggest that projects fail because managers do dumb-ass things like not buying dual monitors, setting deadlines, and requiring documentation.&lt;/p&gt;


	&lt;p&gt;Reading a blog like Justin&amp;#8217;s may make you feel like high-five-ing and doing a little touch-down jig.  OK, fine.  And, after all, there&amp;#8217;s some truth to what Justin has to say.  But there&amp;#8217;s another side of the coin too.  A pretty big side.&lt;/p&gt;


	&lt;p&gt;Your software will suck if you write it badly.  Yes, you should have good tools.  Yes, you should work under realistic schedules.  Yes, you should have time for social interaction.  But these aren&amp;#8217;t the things that make software suck.  &lt;span class="caps"&gt;YOU&lt;/span&gt;, make your software suck.&lt;/p&gt;


	&lt;p&gt;Can you write good software with just one monitor?  Of course you can.  It might not be ideal, but what is?&lt;/p&gt;


	&lt;p&gt;Can you write good software if the deadlines are unreasonable?  Of course you can!  The definition of an unreasonable deadline is a deadline you won&amp;#8217;t make, so you might as well make the code as good as it can be in the time you&amp;#8217;ve got.  If we&amp;#8217;ve learned anything in the last 50 years it&amp;#8217;s that rushing won&amp;#8217;t get you to the deadline faster.&lt;/p&gt;


	&lt;p&gt;Can you write good software if you also have to write documentation?  Can you write good software if your machine isn&amp;#8217;t top-of-the-line?  Can you write good software while standing on your head under water? &lt;em&gt;(er, well, I&amp;#8217;ll give you that might be tough, but for all the others:)&lt;/em&gt; Of course you can!&lt;/p&gt;


	&lt;p&gt;Don&amp;#8217;t get me wrong.  I think short-shrifting on tools, monitors, and schedules is stupid.  I think Justin&amp;#8217;s points are all valid.  But the burden doesn&amp;#8217;t fall solely upon management.  We &lt;em&gt;also&lt;/em&gt; have to do our jobs well.&lt;/p&gt;</description>
      <pubDate>Mon, 08 Dec 2008 19:35:17 -0600</pubDate>
      <guid isPermaLink="false">urn:uuid:8c1e0d33-dead-4bc1-aa79-fb1d5e0751ee</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2008/12/08/how-to-guarantee-that-your-software-will-suck</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Marick's Law</title>
      <description>&lt;p&gt;A month ago I was deep in the throes of shipping the current release of FitNesse.  I just wanted to get it done.  I was close to delivery when I spotted a subtle flaw.  To fix this flaw I decided to insert identical &lt;code&gt;if&lt;/code&gt; statements into each of 9 implementations of an abstract function.&lt;/p&gt;


	&lt;p&gt;My &lt;a href="http://butunclebob.com/ArticleS.UncleBob.GreenWristBand"&gt;green wrist band&lt;/a&gt; was glowing a nasty shade of puke.  I knew I was duplicating code.  I knew that I should use the Template Method pattern.  But that just seemed too &lt;em&gt;hard&lt;/em&gt;. I was convinced that it would be faster to spew the duplicated code out into the derivatives, get the release done, and then clean it up later.&lt;/p&gt;


	&lt;p&gt;So this morning I was doing something else, and I spotted this duplicated code.  I sighed, as I looked down at my &lt;a href="http://butunclebob.com/ArticleS.UncleBob.GreenWristBand"&gt;green wrist band&lt;/a&gt;, and thought to myself that I&amp;#8217;d better eat my own dog food and clean this mess up before it gets any worse.  I was dreading it.&lt;/p&gt;


	&lt;p&gt;I made sure that every occurrence of the statement was identical.  Then I went to the base class with the intention of refactoring a Template Method.  When, what to my wondering eyes should appear, but a Template Method that was already there.&lt;/p&gt;


	&lt;p&gt;I sheepishly copied and pasted the &lt;code&gt;if&lt;/code&gt; statement from one of the derivatives into the Template Method, and then deleted the other eight instances.&lt;/p&gt;


	&lt;p&gt;I ran the tests.&lt;/p&gt;


	&lt;p&gt;They all passed.&lt;/p&gt;


	&lt;p&gt;Damn.&lt;/p&gt;


	&lt;p&gt;My &lt;a href="http://butunclebob.com/ArticleS.UncleBob.GreenWristBand"&gt;green wrist band&lt;/a&gt; is shouting: &amp;#8220;I &lt;span class="caps"&gt;TOLD YOU SO&lt;/span&gt;!&amp;#8221;&lt;/p&gt;


	&lt;p&gt;For my penance I did 20 recitations of Marick&amp;#8217;s law.  &amp;#8220;When it comes to code it &lt;em&gt;never&lt;/em&gt; pays to rush.&amp;#8221;&lt;/p&gt;</description>
      <pubDate>Sat, 29 Nov 2008 14:12:00 -0600</pubDate>
      <guid isPermaLink="false">urn:uuid:438f5dd8-2a4d-4f02-955f-4c48cdf69bec</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2008/11/29/discipline-reminder</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>The Truth about BDD</title>
      <description>&lt;p&gt;I really like the concept of &lt;span class="caps"&gt;BDD&lt;/span&gt; (Behavior Driven Development).  I think Dan North is brilliant, and had done us all a great service by presenting the concept.&lt;/p&gt;


	&lt;p&gt;OK, you can &amp;#8220;feel&amp;#8221; the &amp;#8220;but&amp;#8221; coming, can&amp;#8217;t you?&lt;/p&gt;


	&lt;p&gt;It&amp;#8217;s not so much a &amp;#8220;but&amp;#8221; as an &amp;#8220;aha!&amp;#8221;.  (The punch line is at the end of this article, so don&amp;#8217;t give up in the middle.)&lt;/p&gt;


	&lt;p&gt;&lt;a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development"&gt;&lt;span class="caps"&gt;BDD&lt;/span&gt;&lt;/a&gt; is a variation on &lt;a href="http://en.wikipedia.org/wiki/Test-driven_development"&gt;&lt;span class="caps"&gt;TDD&lt;/span&gt;&lt;/a&gt;.  Whereas in &lt;span class="caps"&gt;TDD&lt;/span&gt; we drive the development of a module by &amp;#8220;first&amp;#8221; stating the requirements as unit tests, in &lt;span class="caps"&gt;BDD&lt;/span&gt; we drive that development by first stating the requirements as, well, requirements.  The form of those requirements is fairly rigid, allowing them to be interpreted by a tool that can execute them in a manner that is similar to unit tests.&lt;/p&gt;


	&lt;p&gt;For example, &lt;pre&gt;
  GIVEN an employee named Bob making $12 per hour.
  WHEN Bob works 40 hours in one week;
  THEN Bob will be paid $480 on Friday evening.&lt;/pre&gt;&lt;/p&gt;


	&lt;p&gt;The Given/When/Then convention is central to the notion of &lt;span class="caps"&gt;BDD&lt;/span&gt;.  It connects the human concept of cause and effect, to the software concept of input/process/output.  With enough formality, a tool can be (&lt;a href="http://jbehave.org"&gt;and has been&lt;/a&gt;) written that interprets the intent of the requirement and then drives the system under test (SUT) to ensure that the requirement works as stated.&lt;/p&gt;


	&lt;p&gt;The argued benefit is that the language you use affects the way you think (See &lt;a href="http://en.wikipedia.org/wiki/Language_and_thought);"&gt;this.&lt;/a&gt; and so if you use a language closer to the way humans think about problems, you&amp;#8217;ll get better thought processes and therefore better results.&lt;/p&gt;


	&lt;p&gt;To say this differently, the Given/When/Then convention stimulates better thought processes than the &lt;code&gt;AssertEquals(expected, actual);&lt;/code&gt; convention.&lt;/p&gt;


	&lt;p&gt;But enough of the overview.  This isn&amp;#8217;t what I wanted to talk about.  What struck me the other day was this&amp;#8230;&lt;/p&gt;


	&lt;p&gt;The Given/When/Then syntax of &lt;span class="caps"&gt;BDD&lt;/span&gt; seemed eerily familiar when I first heard about it several years ago.  It&amp;#8217;s been tickling at the back of my brain since then.  Something about that triplet was trying to resonate with something else in my brain.&lt;/p&gt;


	&lt;p&gt;Then yesterday I realized that Given/When/Then is very similar to If/And/Then; a convention that I have used for the last 20+ years to read state transition tables.&lt;/p&gt;


	&lt;p&gt;Consider my old standard state transition table: The Subway Turnstile:&lt;/p&gt;


	&lt;table&gt;
		&lt;tr&gt;
			&lt;td&gt;&lt;strong&gt;Current State&lt;/strong&gt;&lt;/td&gt;
			&lt;td&gt;&lt;strong&gt;Event&lt;/strong&gt;&lt;/td&gt;
			&lt;td&gt;&lt;strong&gt;New State&lt;/strong&gt;&lt;/td&gt;
			&lt;td&gt;&lt;strong&gt;Action&lt;/strong&gt;&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;&lt;span class="caps"&gt;LOCKED&lt;/span&gt;&lt;/td&gt;
			&lt;td&gt;&lt;span class="caps"&gt;COIN&lt;/span&gt;&lt;/td&gt;
			&lt;td&gt;&lt;span class="caps"&gt;UNLOCKED&lt;/span&gt;&lt;/td&gt;
			&lt;td&gt;Unlock&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;&lt;span class="caps"&gt;LOCKED&lt;/span&gt;&lt;/td&gt;
			&lt;td&gt;&lt;span class="caps"&gt;PASS&lt;/span&gt;&lt;/td&gt;
			&lt;td&gt;&lt;span class="caps"&gt;LOCKED&lt;/span&gt;&lt;/td&gt;
			&lt;td&gt;Alarm&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;&lt;span class="caps"&gt;UNLOCKED&lt;/span&gt;&lt;/td&gt;
			&lt;td&gt;&lt;span class="caps"&gt;COIN&lt;/span&gt;&lt;/td&gt;
			&lt;td&gt;&lt;span class="caps"&gt;UNLOCKED&lt;/span&gt;&lt;/td&gt;
			&lt;td&gt;Thankyou&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;&lt;span class="caps"&gt;UNLOCKED&lt;/span&gt;&lt;/td&gt;
			&lt;td&gt;&lt;span class="caps"&gt;PASS&lt;/span&gt;&lt;/td&gt;
			&lt;td&gt;&lt;span class="caps"&gt;LOCKED&lt;/span&gt;&lt;/td&gt;
			&lt;td&gt;Lock&lt;/td&gt;
		&lt;/tr&gt;
	&lt;/table&gt;




I read this as a set of If/And/Then sentences as follows:
	&lt;ul&gt;
	&lt;li&gt;&lt;em&gt;If&lt;/em&gt; we are in the &lt;span class="caps"&gt;LOCKED&lt;/span&gt; state, &lt;em&gt;and&lt;/em&gt; we get a &lt;span class="caps"&gt;COIN&lt;/span&gt; event, &lt;em&gt;then&lt;/em&gt; we go to the &lt;span class="caps"&gt;UNLOCKED&lt;/span&gt; state, and we invoke the Unlock action.&lt;/li&gt;
		&lt;li&gt;&lt;em&gt;If&lt;/em&gt; we are in the &lt;span class="caps"&gt;LOCKED&lt;/span&gt; state, &lt;em&gt;and&lt;/em&gt; we get a &lt;span class="caps"&gt;PASS&lt;/span&gt; event, &lt;em&gt;then&lt;/em&gt; we stay in the &lt;span class="caps"&gt;UNLOCKED&lt;/span&gt; state, and we invoke the Alarm action.&lt;/li&gt;
		&lt;li&gt;etc.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;This strange similarity caused me to realize that &lt;span class="caps"&gt;GIVEN&lt;/span&gt;/WHEN/THEN is simply a state transition, and that &lt;span class="caps"&gt;BDD&lt;/span&gt; is really just a way to describe a finite state machine.  Clearly &amp;#8220;GIVEN&amp;#8221; is the current state of the system to be explored.  &amp;#8220;WHEN&amp;#8221; describes an event or stimulus to that system.  &amp;#8220;THEN&amp;#8221; describes the resulting state of the system.  &lt;span class="caps"&gt;GIVEN&lt;/span&gt;/WHEN/THEN is nothing more than a description of a state transition, and the sum of all the &lt;span class="caps"&gt;GIVEN&lt;/span&gt;/WHEN/THEN statement is nothing more than a Finite State Machine.&lt;/p&gt;


	&lt;p&gt;Perhaps if I rephrase this you might see why I think this is a bit more than a ho-hum.&lt;/p&gt;


	&lt;p&gt;Some of the brightest minds in our industry, people like Dan North, Dave Astels, David Chelimsky, Aslak Hellesoy, and a host of others, have been pursuing the notion that if we use a &lt;em&gt;better language&lt;/em&gt; to describe automated requirements, we will improve the way we think about those requirements, and therefore write better requirements.  The &lt;em&gt;better language&lt;/em&gt; that they have chosen and used for the last several years uses the Given/When/Then form which, as we have seen, is a description of a finite state machine.  And so it all comes back to Turing.  It all comes back to marks on a tape.  We&amp;#8217;ve decided that the best way to describe the requirements of a system is to describe it as a turing machine.&lt;/p&gt;


	&lt;p&gt;OK, perhaps I overdid the irony there.  Clearly we don&amp;#8217;t need to resort to marks on a tape.  But still there is a grand irony in all this.  The massive churning of neurons struggling with this problem over years and decades have reconnected the circle to the thoughts of that brave pioneer from the 1940s.&lt;/p&gt;


	&lt;p&gt;But enough of irony.  Is this useful?  I think it may be.  You see, one of the great benefits of describing a problem as a Finite State Machine (FSM) is that you can complete the logic of the problem.  That is, if you can enumerate the states and the events, then you know that the number of paths through the system is no larger than S * E.  Or, rather, there are no more than S*E transitions from one state to another.  More importantly, enumerating them is simply a matter of creating a transition for every combination of state and event.&lt;/p&gt;


	&lt;p&gt;One of the more persistent problems in &lt;span class="caps"&gt;BDD&lt;/span&gt; (and &lt;span class="caps"&gt;TDD&lt;/span&gt; for that matter) is knowing when you are &lt;em&gt;done&lt;/em&gt;.  That is, how do you know that you have written enough scenarios (tests).  Perhaps there is some condition that you have forgotten to explore, some pathway through the system that you have not described.&lt;/p&gt;


	&lt;p&gt;This problem is precisely the kind of problem that FSMs are very good at resolving.  &lt;em&gt;If&lt;/em&gt; you can enumerate the states, and events, then you &lt;em&gt;know&lt;/em&gt; the number of paths though the system.  So if Given/When/Then statements are truly nothing more than state transitios, all we need to do is enumerate the number of GIVENs and the number of WHENs.  The number of scenarios will simply be the product of the two.&lt;/p&gt;


	&lt;p&gt;To my knowledge, (which is clearly inadequate) this is not something we&amp;#8217;ve ever tried before at the level of a business requirements document.  But even if we have, the &lt;span class="caps"&gt;BDD&lt;/span&gt; mindset may make it easier to apply.  Indeed, if we can formally enumerate all the Givens and Whens, then a &lt;em&gt;tool&lt;/em&gt; could determine whether our requirements document has executed every path, and could find those paths that we had missed.&lt;/p&gt;


	&lt;p&gt;So, in conclusion, &lt;span class="caps"&gt;TDD&lt;/span&gt; has led us on an interesting path.  &lt;span class="caps"&gt;TDD&lt;/span&gt; was adopted as a way to help us phrase low level requirements and drive the development of software based on those requirements.  &lt;span class="caps"&gt;BDD&lt;/span&gt;, a variation of &lt;span class="caps"&gt;TDD&lt;/span&gt;, was created to help us think better about higher level requirements, and drive the development of systems using a language better than unit tests.  But &lt;span class="caps"&gt;BDD&lt;/span&gt; is really a variation of Finite State Machine specifications, and FSMs can be shown, mathematically, to be complete.  Therefore, we may have a way to conclusively demonstrate that our requirements are complete and consistent. (Apologies to Godel).&lt;/p&gt;


	&lt;p&gt;In the end, the BDDers may have been right that language improves the way we think about things.  Certainly in my silly case, it was the language of &lt;span class="caps"&gt;BDD&lt;/span&gt; that resonated with the language of &lt;span class="caps"&gt;FSM&lt;/span&gt;.&lt;/p&gt;</description>
      <pubDate>Thu, 27 Nov 2008 16:25:38 -0600</pubDate>
      <guid isPermaLink="false">urn:uuid:6102722b-f8ae-42fe-9bb6-516015b47472</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2008/11/27/the-truth-about-bdd</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Agile Methods</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Dirty Rotten ScrumDrels</title>
      <description>&lt;p&gt;So we&amp;#8217;ve finally found the answer.  We know who&amp;#8217;s to blame.  It&amp;#8217;s &lt;span class="caps"&gt;SCRUM&lt;/span&gt;!  &lt;span class="caps"&gt;SCRUM&lt;/span&gt; is the reason that the agile movement is failing.  &lt;span class="caps"&gt;SCRUM&lt;/span&gt; is the reason that agile teams are making a mess.  &lt;span class="caps"&gt;SCRUM&lt;/span&gt; is the root cause behind all the problems and disasters.  &lt;span class="caps"&gt;SCRUM&lt;/span&gt; is the cause of the &lt;em&gt;&amp;#8220;Decline and Fall of Agile.&amp;#8221;&lt;/em&gt;&lt;/p&gt;


	&lt;p&gt;Yeah, and I&amp;#8217;ve got a bridge to sell you.&lt;/p&gt;


	&lt;p&gt;Scrum is not the problem.  Scrum never was the problem.  Scrum never will be the problem.  The problem, dear craftsmen, is our own laziness.&lt;/p&gt;


	&lt;p&gt;It makes no sense to blame Scrum for the fact that we don&amp;#8217;t write tests and don&amp;#8217;t keep our code clean.  We can&amp;#8217;t blame scrum for technical debt.  Technical debt was around long before there was scrum, and it&amp;#8217;ll be around long after.  No it&amp;#8217;s not scrum that&amp;#8217;s to blame.  The culprits remain the same as they ever were: us.&lt;/p&gt;


	&lt;p&gt;Of course it&amp;#8217;s true that a two day certification course is neither necessary nor sufficient to create a good software leader.  It&amp;#8217;s also true that the certificate you get for attending a &lt;span class="caps"&gt;CSM&lt;/span&gt; course is good for little more than showing that you paid to attend a two day &lt;span class="caps"&gt;CSM&lt;/span&gt; course.  It&amp;#8217;s also true that scrum leaves a lot to be desired when it comes to engineering practices.  But it is neither the purpose of scrum nor of CSMs to make engineers out of us, or to instill the disciplines of craftsmanship within us.  That&amp;#8217;s &lt;em&gt;our&lt;/em&gt; job!&lt;/p&gt;


	&lt;p&gt;Some have implied that if all those scrum teams had adopted XP instead of scrum, they wouldn&amp;#8217;t be having all the technical debt they are seeing.  &lt;span class="caps"&gt;BALDERDASH&lt;/span&gt;!&lt;/p&gt;


	&lt;p&gt;Let me be more precise.  &lt;span class="caps"&gt;ASININE&lt;/span&gt;, INANE, &lt;span class="caps"&gt;ABSURDITY&lt;/span&gt;.  &lt;span class="caps"&gt;BALONEY&lt;/span&gt;.  &lt;span class="caps"&gt;DINGOES KIDNEYS&lt;/span&gt;.&lt;/p&gt;


	&lt;p&gt;Let me tell you all, here, now, and forevermore, it is quite possible to do XP badly.  It&amp;#8217;s easy to build technical debt while going through the motions of &lt;span class="caps"&gt;TDD&lt;/span&gt;.  It&amp;#8217;s a no brainer to create a wasteland of code with your pair partner.  And, believe me, you can such a Simple Design that You Aint Gonna Maintain It.  And I&amp;#8217;m not speaking metaphorically.&lt;/p&gt;


	&lt;p&gt;Do you want to know the real secret behind writing good software?  Do you want to know the process that will keep your code clean?  Do you want the magic bullet, the secret sauce, the once and for all one and only truth?&lt;/p&gt;


	&lt;p&gt;OK, here it is.  Are you ready?  The secret is&amp;#8230;&lt;/p&gt;


	&lt;p&gt;The secret is&amp;#8230;&lt;/p&gt;


	&lt;p&gt;Do a good job.&lt;/p&gt;


	&lt;p&gt;Oh, yeah, and stop blaming everything (and everybody) else for your own laziness.&lt;/p&gt;</description>
      <pubDate>Sun, 16 Nov 2008 06:50:14 -0600</pubDate>
      <guid isPermaLink="false">urn:uuid:ef432329-68a2-49a9-9ea3-004fca9caffa</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2008/11/16/dirty-rotten-scrumdrels</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Agile Methods</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Upcoming Speaking Engagements</title>
      <description>&lt;p&gt;I&amp;#8217;m speaking this Friday at &lt;a href="http://rubyconf.org/"&gt;RubyConf&lt;/a&gt; on &lt;a href="http://rubyconf.org/talks/46"&gt;Better Ruby Through Functional Programming&lt;/a&gt;. I&amp;#8217;ll introduce long-overlooked ideas from FP, why they are important for Ruby programmers, and how to use them in Ruby.&lt;/p&gt;


	&lt;p&gt;In two weeks, I&amp;#8217;m speaking on Wednesday, 11/19 at &lt;a href="http://qconsf.com/sf2008/"&gt;QCon San Francisco&lt;/a&gt; on &lt;a href="http://qconsf.com/sf2008/speaker/Dean+Wampler"&gt;Radical Simplification Through Polyglot and Poly-paradigm Programming&lt;/a&gt;. The idea of this talk is that combining the right languages and modularity paradigms (&lt;em&gt;i.e.,&lt;/em&gt; objects, functions, aspects) can simplify your code base and reduce the amount of code you have to write and manage, providing numerous benefits.&lt;/p&gt;


	&lt;p&gt;Back in Chicago, I&amp;#8217;m speaking at the &lt;a href="http://polyglotprogrammers.com/"&gt;Polyglot Programmer&amp;#8217;s&lt;/a&gt; meeting on &lt;a href="http://polyglotprogrammers.com/usa/illinois/chicago/"&gt;The Seductions of Scala&lt;/a&gt;, 11/13. It&amp;#8217;s an intro to the Scala language, which could become the language of choice for the &lt;span class="caps"&gt;JVM&lt;/span&gt;. I&amp;#8217;m repeating this talk at the &lt;a href="http://www.cjug.org/Wiki.jsp?page=2008.12.16.downtown"&gt;Chicago Java User&amp;#8217;s Group&lt;/a&gt; on 12/16. I&amp;#8217;m co-writing a book on Scala with &lt;a href="http://twitter.com/al3x"&gt;Alex Payne&lt;/a&gt;. O&amp;#8217;Reilly will be the publisher.&lt;/p&gt;


	&lt;p&gt;Incidently, Bob Martin is also speaking in Chicago on 11/13 at the &lt;a href="http://www.aplnchicago.org/"&gt;&lt;span class="caps"&gt;APLN&lt;/span&gt; Chicago&lt;/a&gt; meeting on &lt;a href="http://www.aplnchicago.org/Calendar.php"&gt;Software Professionalism&lt;/a&gt;.&lt;/p&gt;</description>
      <pubDate>Mon, 03 Nov 2008 18:13:00 -0600</pubDate>
      <guid isPermaLink="false">urn:uuid:4d0b05fe-743b-46a8-b236-625089da6095</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2008/11/03/upcoming-speaking-engagements</link>
      <category>Dean's Deprecations</category>
      <category>Public Speaking Engagements</category>
      <category>Agile Methods</category>
      <category>Clean Code</category>
      <category>talks</category>
      <category>RubyConf</category>
      <category>APLN</category>
      <category>Polyglot_Programmers</category>
      <category>Scala</category>
      <category>QCon</category>
    </item>
    <item>
      <title>A Scala-style &amp;quot;with&amp;quot; Construct for Ruby</title>
      <description>&lt;p&gt;Scala has a &amp;#8220;mixin&amp;#8221; construct called &lt;em&gt;traits&lt;/em&gt;, which are roughly analogous to Ruby &lt;em&gt;modules&lt;/em&gt;. They allow you to create reusable, modular bits of state and behavior and use them to compose classes and other traits or modules.&lt;/p&gt;


	&lt;p&gt;The syntax for using Scala traits is quite elegant. It&amp;#8217;s straightforward to implement the same syntax in Ruby and doing so has a few useful advantages.&lt;/p&gt;


	&lt;p&gt;For example, here is a Scala example that uses a trait to trace calls to a &lt;code&gt;Worker.work&lt;/code&gt; method.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
// run with "scala example.scala" 

class Worker {
    def work() = "work" 
}

trait WorkerTracer extends Worker {
    override def work() = "Before, " + super.work() + ", After" 
}

val worker = new Worker with WorkerTracer

println(worker.work())        // =&amp;gt; Before, work, After
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Note that &lt;code&gt;WorkerTracer&lt;/code&gt; extends &lt;code&gt;Worker&lt;/code&gt; so it can override the &lt;code&gt;work&lt;/code&gt; method. Since Scala is statically typed, you can&amp;#8217;t just define an &lt;code&gt;override&lt;/code&gt; method and call &lt;code&gt;super&lt;/code&gt; unless the compiler knows there really is a &amp;#8220;super&amp;#8221; method!&lt;/p&gt;


	&lt;p&gt;Here&amp;#8217;s a Ruby equivalent.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
# run with "ruby example.rb" 

module WorkerTracer
    def work; "Before, #{super}, After"; end
end

class Worker 
    def work; "work"; end
end

class TracedWorker &amp;lt; Worker 
  include WorkerTracer
end

worker = TracedWorker.new

puts worker.work          # =&amp;gt; Before, work, After
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Note that we have to create a subclass, which isn&amp;#8217;t required for the Scala case (but can be done when desired).&lt;/p&gt;


	&lt;p&gt;If you know that you will always want to trace calls to &lt;code&gt;work&lt;/code&gt; in the Ruby case, you might be tempted to dispense with the subclass and just add &lt;code&gt;include WorkerTracer&lt;/code&gt; in &lt;code&gt;Worker&lt;/code&gt;. Unfortunately, this won&amp;#8217;t work. Due to the way that Ruby resolves methods, the version of &lt;code&gt;work&lt;/code&gt; in the module will not be found before the version defined in &lt;code&gt;Worker&lt;/code&gt; itself. Hence the subclass seems to be the only option.&lt;/p&gt;


	&lt;p&gt;However, we can work around this using metaprogramming. We can use &lt;code&gt;WorkerTracer#append_features(...)&lt;/code&gt;. What goes in the argument list? If we pass &lt;code&gt;Worker&lt;/code&gt;, then all instances of &lt;code&gt;Worker&lt;/code&gt; will be effected, but actually we&amp;#8217;ll still have the problem with the method resolution rules.&lt;/p&gt;


	&lt;p&gt;If we just want to affect one object &lt;em&gt;and&lt;/em&gt; work around the method resolution roles, then we need to pass the &lt;em&gt;singleton class&lt;/em&gt; (or &lt;em&gt;eigenclass&lt;/em&gt; or &lt;em&gt;metaclass&lt;/em&gt; ...) for the object, which you can get with the following expression.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
metaclass = class &amp;lt;&amp;lt; worker; self; end
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;So, to encapsulate all this and to get back to the original goal of implementing &lt;code&gt;with&lt;/code&gt;-style semantics, here is an implementation that adds a &lt;code&gt;with&lt;/code&gt; method to &lt;code&gt;Object&lt;/code&gt;, wrapped in an &lt;a href="http://rspec.info"&gt;rspec&lt;/a&gt; example.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
# run with "spec ruby_with_spec.rb" 

require 'rubygems'
require 'spec'

# Warning, monkeypatching Object, especially with a name
# that might be commonly used is fraught with peril!!

class Object
  def with *modules
    metaclass = class &amp;lt;&amp;lt; self; self; end
    modules.flatten.each do |m|
      m.send :append_features, metaclass
    end
    self
  end
end

module WorkerTracer
    def work; "Before, #{super}, After"; end
end

module WorkerTracer1
    def work; "Before1, #{super}, After1"; end
end

class Worker 
    def work; "work"; end
end

describe "Object#with" do
  it "should make no changes to an object if no modules are specified" do
    worker = Worker.new.with
    worker.work.should == "work" 
  end

  it "should override any methods with a module's methods of the same name" do
    worker = Worker.new.with WorkerTracer
    worker.work.should == "Before, work, After" 
  end

  it "should stack overrides for multiple modules" do
    worker = Worker.new.with(WorkerTracer).with(WorkerTracer1)
    worker.work.should == "Before1, Before, work, After, After1" 
  end

  it "should stack overrides for a list of modules" do
    worker = Worker.new.with WorkerTracer, WorkerTracer1
    worker.work.should == "Before1, Before, work, After, After1" 
  end

  it "should stack overrides for an array of modules" do
    worker = Worker.new.with [WorkerTracer, WorkerTracer1]
    worker.work.should == "Before1, Before, work, After, After1" 
  end
end
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;You should carefully consider the warning about monkeypatching &lt;code&gt;Object&lt;/code&gt;!  Also, note that &lt;code&gt;Module.append_features&lt;/code&gt; is actually private, so I had to use &lt;code&gt;m.send :append_features, ...&lt;/code&gt; instead.&lt;/p&gt;


	&lt;p&gt;The syntax is reasonably intuitive and it eliminates the need for an explicit subclass. You can pass a single module, or a list or array of them. Because &lt;code&gt;with&lt;/code&gt; returns the object, you can also chain &lt;code&gt;with&lt;/code&gt; calls.&lt;/p&gt;


	&lt;p&gt;A final note; many developers steer clear of metaprogramming and reflection features in their languages, out of fear. While prudence is &lt;em&gt;definitely&lt;/em&gt; wise, the power of these tools can dramatically accelerate your productivity. &lt;em&gt;Metaprogramming is just programming.&lt;/em&gt; Every developer should master it.&lt;/p&gt;</description>
      <pubDate>Mon, 29 Sep 2008 22:41:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:b54295c4-67e0-4acb-a9f6-ea098a3a29e2</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2008/09/29/a-scala-style-_with_-construct-for-ruby</link>
      <category>Dean's Deprecations</category>
      <category>Dynamic Languages</category>
      <category>Design Principles</category>
      <category>Clean Code</category>
      <category>Ruby</category>
      <category>Scala</category>
      <category>with</category>
      <category>mixins</category>
      <category>design</category>
      <category>Metaprogramming</category>
    </item>
    <item>
      <title>Traits vs. Aspects in Scala</title>
      <description>&lt;p&gt;Scala &lt;em&gt;traits&lt;/em&gt; provide a mixin composition mechanism that has been missing in Java. Roughly speaking, you can think of &lt;em&gt;traits&lt;/em&gt; as analogous to Java interfaces, but with implementations.&lt;/p&gt;


	&lt;p&gt;&lt;em&gt;Aspects&lt;/em&gt;, &lt;em&gt;e.g.,&lt;/em&gt; those written in &lt;a href="http://aspectj.org"&gt;AspectJ&lt;/a&gt;, are another mechanism for mixin composition in Java. How do &lt;em&gt;aspects&lt;/em&gt; and &lt;em&gt;traits&lt;/em&gt; compare?&lt;/p&gt;


	&lt;p&gt;Let&amp;#8217;s look at an example trait first, then re-implement the same behavior using an AspectJ aspect, and finally compare the two approaches.&lt;/p&gt;


	&lt;h3&gt;Observing with Traits&lt;/h3&gt;


	&lt;p&gt;In a previous &lt;a href="http://blog.objectmentor.com/articles/2008/08/14/the-seductions-of-scala-part-iii-concurrent-programming"&gt;post on Scala&lt;/a&gt;, I gave an example of the &lt;em&gt;Observer Pattern&lt;/em&gt; implemented using a trait. Chris Shorrock and &lt;a href="http://james-iry.blogspot.com/"&gt;James Iry&lt;/a&gt; provided improved versions in the comments. I&amp;#8217;ll use James&amp;#8217; example here.&lt;/p&gt;


	&lt;p&gt;To keep things as simple as possible, let&amp;#8217;s observe a simple &lt;code&gt;Counter&lt;/code&gt;, which increments an internal count variable by the number input to an &lt;code&gt;add&lt;/code&gt; method.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
package example

class Counter {
    var count = 0
    def add(i: Int) = count += i
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;The &lt;code&gt;count&lt;/code&gt; field is actually public, but I will only write to it through &lt;code&gt;add&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;Here is James&amp;#8217; &lt;em&gt;Subject&lt;/em&gt; trait that implements the &lt;em&gt;Observer Pattern&lt;/em&gt;.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
package example

trait Subject {
  type Observer = { def receiveUpdate(subject:Any) }

  private var observers = List[Observer]()
  def addObserver(observer:Observer) = observers ::= observer
  def notifyObservers = observers foreach (_.receiveUpdate(this))
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Effectively, this says that we can use any object as an &lt;code&gt;Observer&lt;/code&gt; as long as it matches the &lt;em&gt;structural type&lt;/em&gt; &lt;code&gt;{ def receiveUpdate(subject:Any) }&lt;/code&gt;. Think of structural types as anonymous interfaces. Here, a valid observer is one that has a &lt;code&gt;receiveUpdate&lt;/code&gt; method taking an argument of &lt;code&gt;Any&lt;/code&gt; type.&lt;/p&gt;


	&lt;p&gt;The rest of the trait manages a list of observers and defines a &lt;code&gt;notifyObservers&lt;/code&gt; method. The expression &lt;code&gt;observers ::= observer&lt;/code&gt; uses the &lt;code&gt;List&lt;/code&gt; &lt;code&gt;::&lt;/code&gt; (&amp;#8220;cons&amp;#8221;) operator to &lt;em&gt;prepend&lt;/em&gt; an item to the list. (Note, I am using the default immutable &lt;code&gt;List&lt;/code&gt;, so a new copy is created everytime.)&lt;/p&gt;


	&lt;p&gt;The &lt;code&gt;notifyObservers&lt;/code&gt; method iterates through the observers, calling &lt;code&gt;receiveUpdate&lt;/code&gt; on each one. The &lt;code&gt;_&lt;/code&gt; that gets replaced with each observer during the iteration.&lt;/p&gt;


	&lt;p&gt;Finally, here is a &lt;a href="http://code.google.com/p/specs"&gt;specs&lt;/a&gt; file that exercises the code.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
package example

import org.specs._

object CounterObserverSpec extends Specification {
    "A Counter Observer" should {
        "observe counter increments" in {
            class CounterObserver {
                var updates = 0
                def receiveUpdate(subject:Any) = updates += 1
            }
            class WatchedCounter extends Counter with Subject {
                override def add(i: Int) = { 
                    super.add(i)
                    notifyObservers
                }
            }
            var watchedCounter = new WatchedCounter
            var counterObserver = new CounterObserver
            watchedCounter.addObserver(counterObserver)
            for (i &amp;lt;- 1 to 3) watchedCounter.add(i)
            counterObserver.updates must_== 3
            watchedCounter.count must_== 6
    }
  }
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;The &lt;em&gt;specs&lt;/em&gt; library is a &lt;span class="caps"&gt;BDD&lt;/span&gt; tool inspired by &lt;a href="http://rspec.info"&gt;rspec&lt;/a&gt; in Rubyland.&lt;/p&gt;


	&lt;p&gt;I won&amp;#8217;t discuss it all the specs-specific details here, but hopefully you&amp;#8217;ll get the general idea of what it&amp;#8217;s doing.&lt;/p&gt;


	&lt;p&gt;Inside the &lt;code&gt;"observe counter increments" in {...}&lt;/code&gt;, I start by declaring two classes, &lt;code&gt;CounterObserver&lt;/code&gt; and &lt;code&gt;WatchedCounter&lt;/code&gt;. &lt;code&gt;CounterObserver&lt;/code&gt; satisfies our required &lt;em&gt;structural type&lt;/em&gt;, &lt;em&gt;i.e.,&lt;/em&gt; it provides a &lt;code&gt;receiveUpdate&lt;/code&gt; method.&lt;/p&gt;


	&lt;p&gt;&lt;code&gt;WatchedCounter&lt;/code&gt; subclasses &lt;code&gt;Counter&lt;/code&gt; and mixes in the &lt;code&gt;Subject&lt;/code&gt; trait. It overrides the &lt;code&gt;add&lt;/code&gt; method, where it calls &lt;code&gt;Counter&lt;/code&gt;&amp;#8217;s &lt;code&gt;add&lt;/code&gt; first, then notifies the observers. No parentheses are used in the invocation of &lt;code&gt;notifyObservers&lt;/code&gt; because the method was not defined to take any!&lt;/p&gt;


	&lt;p&gt;Next, I create an instance of each class, add the observer to the &lt;code&gt;WatchedCounter&lt;/code&gt;, and make 3 calls to &lt;code&gt;watchedCounter.add&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;Finally, I use the &amp;#8220;&lt;code&gt;actual must_== expected&lt;/code&gt;&amp;#8221; idiom to test the results. The observer should have seen 3 updates, while the counter should have a total of 6.&lt;/p&gt;


	&lt;p&gt;The following simple bash shell script will build and run the code.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
SCALA_HOME=...
SCALA_SPECS_HOME=...
CP=$SCALA_HOME/lib/scala-library.jar:$SCALA_SPECS_HOME/specs-1.3.1.jar:bin
rm -rf bin
mkdir -p bin
scalac -d bin -cp $CP src/example/*.scala
scala -cp $CP example/CounterObserverSpec
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Note that I put all the sources in a &lt;code&gt;src/example&lt;/code&gt; directory. Also, I&amp;#8217;m using v1.3.1 of &lt;em&gt;specs&lt;/em&gt;, as well as v2.7.1 of Scala. You should get the following output.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
Specification "CounterObserverSpec" 
  A Counter Observer should
  + observe counter increments

Total for specification "CounterObserverSpec":
Finished in 0 second, 60 ms
1 example, 2 assertions, 0 failure, 0 error
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;h3&gt;Observing with Aspects&lt;/h3&gt;


	&lt;p&gt;Because Scala compiles to Java byte code, I can use AspectJ to advice Scala code! For this to work, you have to be aware of how Scala represents its concepts in byte code. For example, object declarations, &lt;em&gt;e.g.,&lt;/em&gt; &lt;code&gt;object Foo {...}&lt;/code&gt; become static final classes. Also, method names like &lt;code&gt;+&lt;/code&gt; become &lt;code&gt;$plus&lt;/code&gt; in byte code.&lt;/p&gt;


	&lt;p&gt;However, most Scala type, method, and variable names can be used as is in AspectJ. This is true for my example.&lt;/p&gt;


	&lt;p&gt;Here is an aspect that observes calls to &lt;code&gt;Counter.add&lt;/code&gt;.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
package example

public aspect CounterObserver {
    after(Object counter, int value): 
        call(void *.add(int)) &amp;#38;&amp;#38; target(counter) &amp;#38;&amp;#38; args(value) {

        RecordedObservations.record("adding "+value);
    }
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;You can read this aspect as follows, &lt;em&gt;after calling &lt;code&gt;Counter.add&lt;/code&gt; (and keeping track of the Counter object that was called, and the value passed to the method), call the static method &lt;code&gt;record&lt;/code&gt; on the &lt;code&gt;RecordedObservations&lt;/code&gt;.&lt;/em&gt;&lt;/p&gt;


	&lt;p&gt;I&amp;#8217;m using a separate Scala object &lt;code&gt;RecordedObservations&lt;/code&gt;&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
package example

object RecordedObservations {
    private var messages = List[String]()
    def record(message: String):Unit = messages ::= message
    def count() = messages.length
    def reset():Unit = messages = Nil
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Recall that this is effectively a static final Java class. I need this separate object, rather than keeping information in the aspect itself, because of the simple-minded way I&amp;#8217;m building the code. ;) However, it&amp;#8217;s generally a good idea with aspects to delegate most of the work to Java or Scala code anyway.&lt;/p&gt;


	&lt;p&gt;Now, the &amp;#8220;spec&amp;#8221; file is:&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
package example

import org.specs._

object CounterObserverSpec extends Specification {
    "A Counter Observer" should {
        "observe counter increments" in {
            RecordedObservations.reset()
            var counter = new Counter
            for (i &amp;lt;- 1 to 3) counter.add(i)
            RecordedObservations.count() must_== 3
            counter.count must_== 6
    }
  }
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;This time, I don&amp;#8217;t need two more classes for the adding a mixin trait or defining an observer. Also, I call &lt;code&gt;RecordedObservations.count&lt;/code&gt; to ensure it was called 3 times.&lt;/p&gt;


	&lt;p&gt;The build script is also slightly different to add the AspectJ compilation.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
SCALA_HOME=...
SCALA_SPECS_HOME=...
ASPECTJ_HOME=...
CP=$SCALA_HOME/lib/scala-library.jar:$SCALA_SPECS_HOME/specs-1.3.1.jar:$ASPECTJ_HOME/lib/aspectjrt.jar:bin
rm -rf bin app.jar
mkdir -p bin
scalac -d bin -cp $CP src/example/*.scala 
ajc -1.5 -outjar app.jar -cp $CP -inpath bin src/example/CounterObserver.aj
aj -cp $ASPECTJ_HOME/lib/aspectjweaver.jar:app.jar:$CP example.CounterObserverSpec
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;The &lt;code&gt;ajc&lt;/code&gt; command not only compiles the aspect, but it &amp;#8220;weaves&amp;#8221; into the compiled Scala classes in the &lt;code&gt;bin&lt;/code&gt; directory. Actually, it only affects the &lt;code&gt;Counter&lt;/code&gt; class. Then it writes all the woven and unmodified class files to &lt;code&gt;app.jar&lt;/code&gt;, which is used to execute the test. Note that for production use, you might prefer &lt;a href="http://www.eclipse.org/aspectj/doc/released/devguide/ltw.html"&gt;load-time weaving&lt;/a&gt;.&lt;/p&gt;


	&lt;p&gt;The output is the same as before (except for the milliseconds), so I won&amp;#8217;t show it here.&lt;/p&gt;


	&lt;h3&gt;Comparing Traits with Aspects&lt;/h3&gt;


	&lt;p&gt;So far, both approaches are equally viable. The traits approach obviously doesn&amp;#8217;t require a separate language and corresponding tool set.&lt;/p&gt;


	&lt;p&gt;However, traits have one important limitation with respect to aspects. Aspects let you define &lt;em&gt;pointcuts&lt;/em&gt; that are queries over all possible points where new behavior or modifications might be desired. These points are called &lt;em&gt;join points&lt;/em&gt; in aspect terminology. The aspect I showed above has a simple pointcut that selects one join point, calls to the &lt;code&gt;Counter.add&lt;/code&gt; method.&lt;/p&gt;


	&lt;p&gt;However, what if I wanted to observe all state changes in all classes in a package? Defining traits for each case would be tedious and error prone, since it would be easy to overlook some cases. With an aspect framework like AspectJ, I can implement observation at all the points I care about in a &lt;em&gt;modular&lt;/em&gt; way.&lt;/p&gt;


	&lt;p&gt;Aspect frameworks support this by providing wildcard mechanisms. I won&amp;#8217;t go into the details here, but the &lt;code&gt;*&lt;/code&gt; in the previous aspect is an example, matching any type. Also, one of the most powerful techniques for writing robust aspects is to use pointcuts that reference only annotations, a form of abstraction. As a final example, if I add an annotation &lt;code&gt;Adder&lt;/code&gt; to &lt;code&gt;Counter.add&lt;/code&gt;,&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
package example

class Counter {
    var count = 0
    @Adder def add(i: Int) = count += i
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Then I can rewrite the aspect as follows.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
package example

public aspect CounterObserver {
    after(Object counter, int value): 
        call(@Adder void *.*(int)) &amp;#38;&amp;#38; target(counter) &amp;#38;&amp;#38; args(value) {

        RecordedObservations.record("adding "+value);
    }
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Now, there are no type and method names in the pointcut. Any instance method on any visible type that takes one &lt;code&gt;int&lt;/code&gt; (or Scala &lt;code&gt;Int&lt;/code&gt;) argument and is annotated with &lt;code&gt;Adder&lt;/code&gt; will get matched.&lt;/p&gt;


	&lt;p&gt;Note: Scala requires that you create any custom annotations as normal Java annotations. Also, if you intend to use them with Aspects, use runtime retention policy, which will be necessary if you use &lt;a href="http://www.eclipse.org/aspectj/doc/released/devguide/ltw.html"&gt;load-time weaving&lt;/a&gt;.&lt;/p&gt;


	&lt;h3&gt;Conclusion&lt;/h3&gt;


	&lt;p&gt;If you need to mix in behavior in a specific, relatively-localized set of classes, Scala traits are probably all you need and you don&amp;#8217;t need another language. If you need more &amp;#8220;pervasive&amp;#8221; modifications (&lt;em&gt;e.g.,&lt;/em&gt; tracing, policy enforcement, security), consider using aspects.&lt;/p&gt;


	&lt;h4&gt;Acknowledgements&lt;/h4&gt;


	&lt;p&gt;Thanks to Ramnivas Laddad, whose forthcoming 2&lt;sup&gt;nd&lt;/sup&gt; Edition of &lt;cite&gt;AspectJ in Action&lt;/cite&gt; got me thinking about this topic.&lt;/p&gt;</description>
      <pubDate>Sat, 27 Sep 2008 22:33:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:8628eb5f-f195-4ebe-a10a-f3ee9d66d591</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2008/09/27/traits-vs-aspects-in-scala</link>
      <category>Dean's Deprecations</category>
      <category>Design Principles</category>
      <category>Clean Code</category>
      <category>Scala</category>
      <category>aspects</category>
      <category>AspectJ</category>
      <category>mixins</category>
    </item>
    <item>
      <title>Type Scum</title>
      <description>&lt;p&gt;Getting existing code under test is hard work, but it is fruitful.  Yes, you get code that is easier to change, but more importantly, you get knowledge &amp;#8211; you learn things about programming which make you better at avoiding common traps.  Sadly, many of these traps aren&amp;#8217;t well recognized yet.&lt;/p&gt;


	&lt;p&gt;The trap that I am going to write about today is one that I call &lt;i&gt;type scum&lt;/i&gt;.  It&amp;#8217;s most prevalent in C and C++ but it can attack in any of the traditional statically typed languages.&lt;/p&gt;


	&lt;p&gt;&lt;i&gt;Type Scum&lt;/i&gt; is the cruft in a code base which makes it impossible to compile a single file without an entire sub-stratum of defined types.  I&amp;#8217;m not talking about the primary, or even the secondary abstractions in your system, but rather the 200 or so basic types and structs that your abstractions depend upon.&lt;/p&gt;


	&lt;p&gt;Again, the problem is worst in C++ and C. At some point, every C or C++ developer feels the urge to isolate him or herself from the basic types of the language.  The &lt;i&gt;unsigned int&lt;/i&gt; type becomes &lt;i&gt;uint32&lt;/i&gt; and &lt;i&gt;unsigned char *&lt;/i&gt; becomes &lt;i&gt;uchar16_ptr&lt;/i&gt;. And, if that was all, it would be okay.  But no, people define &lt;i&gt;data transfer objects&lt;/i&gt; which aggregate these type pseudonyms together into large muddles. No file can compile without bringing in a world of types which cushion the code from dangerous things like the platform and testing harnesses.&lt;/p&gt;


	&lt;p&gt;No wait, testing harnesses are good. What can we do?&lt;/p&gt;


	&lt;p&gt;The unfortunate thing is that it is very hard to pull &lt;i&gt;type scum&lt;/i&gt; out of a system once it&amp;#8217;s been infected, but we can learn how to avoid it or at least manage it better:&lt;/p&gt;


&lt;ol&gt;
&lt;li&gt;If you must provide a sub-stratum of basic types in your system, do it in one place.  There should be a single library (and associated headers) that you include whenever you need it.  This library (and headers) should contain nothing else.
&lt;li&gt;If you must create &lt;span class="caps"&gt;DTO&lt;/span&gt; (Data Transfer Object) types, minimize them.  A good general purpose structure can carry a wide variety of different types of data and simplify testing.
&lt;li&gt;Push the DTOs to the edges.  There are some systems where you really do care whether an internal computation happens in &lt;i&gt;unsigned long int&lt;/i&gt; or &lt;i&gt;unsigned long long int&lt;/i&gt; but they are rare.  Basic data types and tolerances matter when two systems need to agree upon them, and that happens at component boundaries.  In many systems, the internal code can use platform types directly.
&lt;/ol&gt;

	&lt;p&gt;There you go.  &lt;i&gt;Type scum&lt;/i&gt; bad.&lt;/p&gt;


	&lt;p&gt;I&amp;#8217;m sure that some people reading this will say &amp;#8220;Hey, isn&amp;#8217;t this the exact opposite of the advice that people give for a system with the &lt;i&gt;primitive obsession&lt;/i&gt; code smell?&amp;#8221;  The answer is &amp;#8220;yes.&amp;#8221;  But, to me, &lt;i&gt;primitive obsession&lt;/i&gt; is a different problem.  It&amp;#8217;s something which is the result of a lack of real behavioral abstractions in a system, not the lack of larger data holders.&lt;/p&gt;


	&lt;p&gt;Different problem.&lt;/p&gt;


	&lt;p&gt;&lt;i&gt;Type scum&lt;/i&gt; bad.&lt;/p&gt;</description>
      <pubDate>Mon, 08 Sep 2008 17:43:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:71bb9d92-6aa0-4899-bbc0-e912321d06cc</guid>
      <author>Michael Feathers</author>
      <link>http://blog.objectmentor.com/articles/2008/09/08/type-scum</link>
      <category>Michaels Musings</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>The Open-Closed Principle for Languages with Open Classes</title>
      <description>&lt;p&gt;We&amp;#8217;ve been having a discussion inside Object Mentor World Design Headquarters about the meaning of the &lt;span class="caps"&gt;OCP&lt;/span&gt; for dynamic languages, like Ruby, with open classes.&lt;/p&gt;


	&lt;p&gt;For example, in Ruby it&amp;#8217;s normal to define a class or module, &lt;em&gt;e.g.,&lt;/em&gt;&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
# foo.rb
class Foo
    def method1 *args
        ...
    end
end
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;and later re-open the class and add (or redefine) methods,&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
# foo2.rb
class Foo
    def method2 *args
        ...
    end
end
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Users of &lt;code&gt;Foo&lt;/code&gt; see all the methods, as if &lt;code&gt;Foo&lt;/code&gt; had one definition.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
foo = Foo.new
foo.method1 :arg1, :arg2
foo.method2 :arg1, :arg2
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Do open classes violate the Open-Closed Principle? Bertrand Meyer articulated &lt;span class="caps"&gt;OCP&lt;/span&gt;. Here is his definition&lt;sup&gt;&lt;a href="#fn1"&gt;1&lt;/a&gt;&lt;/sup&gt;.&lt;/p&gt;


	&lt;blockquote&gt;
		&lt;p&gt;Software entities (classes, modules, functions, &lt;em&gt;etc.&lt;/em&gt;) should be open for extension, but closed for modification.&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;p&gt;He elaborated on it &lt;a href="http://se.ethz.ch/~meyer/publications/computer/implicitness.pdf"&gt;here&lt;/a&gt;.&lt;/p&gt;


	&lt;blockquote&gt;
		&lt;p&gt;... This is the open-closed principle, which in my opinion is one of the central innovations of object technology: the ability to use a software component as it is, while retaining the possibility of adding to it later through inheritance. Unlike the records or structures of other approaches, a class of object technology is both closed and open: closed because we can start using it for other components (its clients); open because we can at any time add new properties without invalidating its existing clients.&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;blockquote&gt;
		&lt;p&gt;&lt;a href="http://se.ethz.ch/~meyer/publications/computer/implicitness.pdf"&gt;Tell Less, Say More: The Power of Implicitness&lt;/a&gt;&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;p&gt;So, if one client &lt;code&gt;require&lt;/code&gt;&amp;#8217;s only &lt;code&gt;foo.rb&lt;/code&gt; and only uses &lt;code&gt;method1&lt;/code&gt;, that client doesn&amp;#8217;t care what &lt;code&gt;foo2.rb&lt;/code&gt; does. However, if the client also &lt;code&gt;require&lt;/code&gt;&amp;#8217;s &lt;code&gt;foo2.rb&lt;/code&gt;, perhaps indirectly through another &lt;code&gt;require&lt;/code&gt;, problems will ensue unless the client is unaffected by what &lt;code&gt;foo2.rb&lt;/code&gt; does.  This looks a lot like the way &amp;#8220;good&amp;#8221; inheritance should behave.&lt;/p&gt;


	&lt;p&gt;So, the answer is &lt;em&gt;no&lt;/em&gt;, we aren&amp;#8217;t violating &lt;span class="caps"&gt;OCP&lt;/span&gt;, as long as we extend a re-opened class following the same rules we would use when inheriting from it.&lt;/p&gt;


	&lt;p&gt;If we use inheritance instead:&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
# foo.rb
class Foo
    def method1 *args
        ...
    end
end
...
class DerivedFoo &amp;lt; Foo
    def method2 *args
        ...
    end
end
...
foo = SubFoo.new    # Instantiate different class...
foo.method1 :arg1, :arg2
foo.method2 :arg1, :arg2
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;One notable difference is that we have to instantiate a different class. This is an important difference. While you can often just use inheritance, and maybe you should prefer it, inheritance only works if you have full control over what types get instantiated and &lt;em&gt;it&amp;#8217;s easy to change which types you use&lt;/em&gt;. Of course, inheritance is also the best approach when you need all behavioral variants &lt;em&gt;simulateneously&lt;/em&gt;, &lt;em&gt;i.e.,&lt;/em&gt; each variant in one or more objects.&lt;/p&gt;


	&lt;p&gt;Sometimes you want to affect the behavior of all instances transparently, without changing the types that are instantiated. A slightly better example, logging method calls, illustrates the point. Here we use the &amp;#8220;famous&amp;#8221; &lt;code&gt;alias_method&lt;/code&gt; in Ruby.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
# foo.rb
class Foo
    def method1 *args
        ...
    end
end
# logging_foo.rb
class Foo
    alias_method :old_method1, :method1
    def method1 *args
        p "Inside method1(#{args.inspect})" 
        old_method1 *args
    end
end
...
foo = Foo.new
foo.method1 :arg1, :arg2
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;&lt;code&gt;Foo.method1&lt;/code&gt; behaves like a subclass override, with extended behavior that still obeys the &lt;a href="http://www.objectmentor.com/resources/articles/lsp.pdf"&gt;Liskov-Substitution Principle&lt;/a&gt; (LSP).&lt;/p&gt;


	&lt;p&gt;So, I think the &lt;span class="caps"&gt;OCP&lt;/span&gt; can be reworded slightly.&lt;/p&gt;


	&lt;blockquote&gt;
		&lt;p&gt;Software entities (classes, modules, functions, &lt;em&gt;etc.&lt;/em&gt;) should be open for extension, but closed for &lt;strong&gt;source&lt;/strong&gt; modification.&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;p&gt;We should not re-open the original source, but adding functionality through a separate source file is okay.&lt;/p&gt;


	&lt;p&gt;Actually, I prefer a slightly different wording.&lt;/p&gt;


	&lt;blockquote&gt;
		&lt;p&gt;Software entities (classes, modules, functions, &lt;em&gt;etc.&lt;/em&gt;) should be open for extension, but closed for &lt;strong&gt;source and contract&lt;/strong&gt; modification.&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;p&gt;The extra &lt;strong&gt;and contract&lt;/strong&gt; is redundant with &lt;span class="caps"&gt;LSP&lt;/span&gt;. I don&amp;#8217;t think this kind of redundancy is necessarily bad. ;) The &lt;em&gt;contract&lt;/em&gt; is the set of &lt;em&gt;behavioral expectations&lt;/em&gt; between the &amp;#8220;entity&amp;#8221; and its client(s). Just as it is &lt;a href="http://blog.objectmentor.com/articles/2007/02/17/liskov-substitution-principle-and-the-ruby-core-libraries"&gt;bad to break the contract with inheritance&lt;/a&gt;, it is also bad to break it through open classes.&lt;/p&gt;


	&lt;p&gt;&lt;span class="caps"&gt;OCP&lt;/span&gt; and &lt;span class="caps"&gt;LSP&lt;/span&gt; together are our most important design principles for effective organization of similar &lt;em&gt;vs.&lt;/em&gt; variant behaviors. Inheritance is one way we do this. Open classes provide another way. Aspects provide a third way and are subject to the same &lt;a href="http://www.aosd.net/2007/program/industry/I6-AspectDesignPrinciples.pdf"&gt;design issues&lt;/a&gt;.&lt;/p&gt;


	&lt;p id="fn1"&gt;&lt;sup&gt;1&lt;/sup&gt; Meyer, Bertrand (1988). Object-Oriented Software Construction. Prentice Hall. &lt;span class="caps"&gt;ISBN 0136290493&lt;/span&gt;.&lt;/p&gt;</description>
      <pubDate>Thu, 04 Sep 2008 21:42:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:8045ef44-c256-4c10-9edf-7f9fde4a26bd</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2008/09/04/the-open-closed-principle-for-languages-with-open-classes</link>
      <category>Dean's Deprecations</category>
      <category>Dynamic Languages</category>
      <category>Design Principles</category>
      <category>Clean Code</category>
      <category>OCP</category>
      <category>languages</category>
      <category>Ruby</category>
    </item>
    <item>
      <title>There will be code</title>
      <description>&lt;p&gt;During the last three decades, several things about software development have changed, and several other things have not.  The things that have changed are startling.  The things that have not are even more startling.&lt;/p&gt;


	&lt;p&gt;What has changed?  Three decades have seen a 1000 fold increase in speed, another 1000 fold increase in memory. Yet another 1000 fold decrease in size (by volume), and yet another 1000 fold decrease in power consumption.  Adding up all those zeros implies that the resources we have to play with have increased by twelve orders of magnitude.  Even if I have over estimated by five orders of magnitude the remaining seven are still and astounding increase.&lt;/p&gt;


	&lt;p&gt;I remember building &lt;span class="caps"&gt;RSX&lt;/span&gt;-11M on a &lt;span class="caps"&gt;PDP&lt;/span&gt;-11/60 from source.  It took several hours.  Nowadays I can build huge java applications in a matter of seconds.  I remember that compiling small C programs required dozens of minutes.  Now much larger programs compile in a eyeblink.  I remember painstakingly editing assembly language on punch cards.  Now I use refactorings in huge java programs without thinking about it.   I remember when 10,000 lines of code was five boxes of cards that weighed 50 pounds.  Now, such a program is considered trivial.&lt;/p&gt;


	&lt;p&gt;Nowadays we have &lt;em&gt;tools&lt;/em&gt;!  We have editors that compile our code while we type, and complete our thoughts for us.  We have analyzers that will find code duplication in huge systems, and identify flaws and weaknesses.  We have code coverage tools that will tell us each line of code that our unit tests fail to execute.  We have refactoring browsers that allow us to manipulate our code with unprecedented power and convenience.&lt;/p&gt;


	&lt;p&gt;But in the face of all this massive change, this rampant growth, this almost unlimited wealth of resources, there is something that hasn&amp;#8217;t changed much at all.  Code.&lt;/p&gt;


	&lt;p&gt;Fortran, Algol, and Lisp are over fifty years old.  These language are the clear progenitors of the static and dynamic languages we use today.  The roots of C++, Java, and C# clearly lie in Algol and Fortan.  The connection between Lisp, and Ruby, Python, and smalltalk may be less obvious, but only slightly so.  Today&amp;#8217;s modern language may be rich with features and power, but they are not 12 orders of magnitude better than their ancestors.  Indeed, it&amp;#8217;s hard to say that they are even &lt;span class="caps"&gt;ONE&lt;/span&gt; order of magnitude better.&lt;/p&gt;


	&lt;p&gt;When it comes down to it.  We still write programs made out of calculations, &amp;#8216;if&amp;#8217; statements, and &amp;#8216;for&amp;#8217; loops.  We still assign values into variables and pass arguments into functions.  Programmers from 30 years ago might be surprised that we use lower case letters in our programs, but little else would startle them about the code we write.&lt;/p&gt;


	&lt;p&gt;We are like carpenters who started out using hammers and saws, and have progressed to using air-hammers and power saws.  These power tools help a lot; but in the end we are still cutting wood and nailing it together.  And we probably will be for the next 30 years.&lt;/p&gt;


	&lt;p&gt;Looking back we see that &lt;em&gt;what&lt;/em&gt; we do hasn&amp;#8217;t changed all that much.  What has changed are the tools and resources we can apply to the task.  Looking forward I anticipate that the current trend will continue.  The tools will get better, but the code will still be code.  We may see some &amp;#8220;minor&amp;#8221; improvements in languages and frameworks, but we will still be slinging code.&lt;/p&gt;


	&lt;p&gt;Some folks have put a great deal of hope in technologies like &lt;span class="caps"&gt;MDA&lt;/span&gt;.  I don&amp;#8217;t.  The reason is that I don&amp;#8217;t see &lt;span class="caps"&gt;MDA&lt;/span&gt; as anything more than a different kind of computer language.  To be effective it will still need &amp;#8216;if&amp;#8217; and &amp;#8216;for&amp;#8217; statements of some kind.  And &amp;#8216;programmers&amp;#8217; will still need to write programs in that language, because details will still need to be managed.  There is no language that can eliminate the programming step, because the programming step is the translation from requirements to systems irrespective of language.  &lt;span class="caps"&gt;MDA&lt;/span&gt; does not change this.&lt;/p&gt;


	&lt;p&gt;Some folks have speculated that we&amp;#8217;ll have &amp;#8220;intelligent agents&amp;#8221; based on some kind of AI technology, and that these agents will be able to write portions of our programs for us.  The problem with this is that we already have intelligent agents that write programs for us.  They are called programmers.  It&amp;#8217;s difficult to imagine a program that is able to communicate to a customer and write a program better than a human programmer.&lt;/p&gt;


	&lt;p&gt;So, for the foreseeable future I think software will remain the art of crafting code to meet the requirements of our customers.&lt;/p&gt;


	&lt;p&gt;There is something else that &lt;em&gt;needs&lt;/em&gt; to change, however.  And I believe it &lt;em&gt;is&lt;/em&gt; changing.  Our professionalism.&lt;/p&gt;


	&lt;p&gt;In some ways our &amp;#8220;profession&amp;#8221; has paralleled that of medicine.  300 years ago there were a few thinkers, and far too many practitioners.  There were no standards, no common rituals or behaviors, no common disciplines.  If you got sick you might go to a barber, or a healer.  Perhaps he&amp;#8217;d let out some blood, or ask you to wear some garlic.  Over time, however, the few thinkers gained knowledge, discipline, and skill.  They adopted standards and rituals.  They set up a system for policing and maintaining those standards, and for training and accepting new members.&lt;/p&gt;


	&lt;p&gt;&lt;span class="caps"&gt;THIS&lt;/span&gt; is the change that I hope the next thirty years holds for software development.&lt;/p&gt;</description>
      <pubDate>Thu, 28 Aug 2008 21:02:45 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:9b767ed1-f4cb-4e8e-a628-e0fc044496a6</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2008/08/28/there-will-be-code</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Baubles in Orbit</title>
      <description>&lt;p&gt;I have put together a nice little demonstration of the Bauble concept.  You may recall that I first wrote about it &lt;a href="http://blog.objectmentor.com/articles/2008/07/20/bauble-bauble"&gt;here&lt;/a&gt;.  Baubles are a simple component scheme for Ruby, good for when you want a component, but don&amp;#8217;t need something as heavy as a gem.&lt;/p&gt;


	&lt;p&gt;&lt;a href="http://fitnesse.org/files/unclebob/orbit.zip"&gt;orbit.zip&lt;/a&gt; contains all the files for this demonstration.  I suggest you download and unpack it.&lt;/p&gt;


	&lt;p&gt;First you need to install the Bauble gem.  Don&amp;#8217;t worry, it won&amp;#8217;t hurt anything.  Just say &lt;code&gt;gem install orbit/bauble/Bauble-0.1.gem&lt;/code&gt; (You&amp;#8217;ll probably have to do it with &lt;code&gt;sudo&lt;/code&gt;.)  That should install Bauble.  From now on you only need to say &lt;code&gt;require 'bauble'&lt;/code&gt; in your ruby scripts that make use of it.&lt;/p&gt;


Now you should be able to run the orbital simulator.  Just type:
&lt;pre&gt;&lt;code&gt;
cd orbit/MultipleBodyOrbit/lib
jruby multiple_body_orbit.rb
&lt;/code&gt;&lt;/pre&gt;
A swing window should pop up and you should be able to watch an orbital simulation.  Every run shows a different random scenario, so you can kill a lot of time by watching worlds in collision.

	&lt;p&gt;The thing to note, if you are a ruby programmer, is the use of the term &lt;code&gt;Bauble::use(-some_directory-)&lt;/code&gt;.  If you look in the &lt;code&gt;multiple_body_orbit.rb&lt;/code&gt; file you&amp;#8217;ll see I use two Baubles, the &lt;code&gt;Physics&lt;/code&gt; bauble does the raw calculation for all the gravity, forces, collisions, etc.  The &lt;code&gt;cellular_automaton&lt;/code&gt; bauble provides a very simple Swing framework for drawing dots on a screen. (Yes, this is jruby).&lt;/p&gt;


	&lt;p&gt;If you look in either of the two Baubles, you&amp;#8217;ll see that the &lt;code&gt;require&lt;/code&gt; statements within them do not know (or care) about the directory they live in.  There is none of that horrible &lt;code&gt;__FILE__&lt;/code&gt; nonsense that pollutes so many ruby scripts.  This is because the &lt;code&gt;Bauble::use&lt;/code&gt; function puts the directory path in the &lt;code&gt;LOAD_PATH&lt;/code&gt; so that subsquent &lt;code&gt;require&lt;/code&gt; statements can simply eliminate the directory spec.&lt;/p&gt;


	&lt;p&gt;Take a look at the Bauble source code.  It&amp;#8217;s no great shakes.&lt;/p&gt;


	&lt;p&gt;Also take a look at the two baubles.  They show a pretty nice way to decouple business rules from gui.  You might recognize the &lt;span class="caps"&gt;MVP&lt;/span&gt; pattern.  The &lt;code&gt;multiple_body_orbit.rb&lt;/code&gt; file contains the presenter.  Clearly the &lt;code&gt;Physics&lt;/code&gt; module is the model.  And the &lt;code&gt;cellular_automaton&lt;/code&gt; module is the view. (There is no controller, because there is no input.)&lt;/p&gt;</description>
      <pubDate>Tue, 19 Aug 2008 01:29:32 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:f2909460-a819-4cd3-93db-ec5b15b1a8cb</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2008/08/19/baubles-in-orbit</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Dynamic Languages</category>
      <category>Design Principles</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Quintessence: The fifth element for the Agile Manifesto</title>
      <description>&lt;p&gt;&amp;#8220;Quintessence&amp;#8221; was the name of the keynote I gave at the banquet of Agile 2008.  Though the talk covered a lot of ground, the upshot was that we need an addition to the agile manifesto&amp;#8230;&lt;/p&gt;


	&lt;p&gt;As you know the Agile Manifesto is composed of four balanced value statements.  Here they are:&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;Individuals and interactions over processes and tools&lt;/li&gt;
		&lt;li&gt;Working software over comprehensive documentation&lt;/li&gt;
		&lt;li&gt;Customer collaboration over contract negotiation&lt;/li&gt;
		&lt;li&gt;Responding to change over following a plan&lt;/li&gt;
	&lt;/ul&gt;


&lt;p/&gt;

	&lt;p&gt;In my talk I proposed the following addition&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;Craftsmanship over Crap.&lt;/li&gt;
	&lt;/ul&gt;


&lt;p/&gt;

	&lt;p&gt;From this you can probably tell that my talk was primarily about behaving professionally, and writing clean code.  This should not be a big surprise since I just finished writing a book entitled &lt;a href="http://tinyurl.com/5se8bk"&gt;Clean Code&lt;/a&gt; .&lt;/p&gt;


	&lt;p&gt;The problem with my proposal is that it is not a balanced value statement.  In the other four statements we &lt;em&gt;value&lt;/em&gt; the second item.  We just value the first item more.  But in my proposed addition, we simply don&amp;#8217;t value crap at all.&lt;/p&gt;


	&lt;p&gt;So I hereby change my original proposal, which was made for dramatic effect, to:&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;Craftsmanship over Execution&lt;/li&gt;
	&lt;/ul&gt;


&lt;p/&gt;

	&lt;p&gt;Most software development teams &lt;em&gt;execute&lt;/em&gt;, but they don&amp;#8217;t take &lt;em&gt;care&lt;/em&gt;.  We value execution, but we value craftsmanship more.&lt;/p&gt;


	&lt;p&gt;Comments?  Anyone have a better word?&lt;/p&gt;


	&lt;p&gt;(BTW, I used a wonderful web tool named &lt;a href="http://www.visualthesaurus.com"&gt;Visual Thesaurus&lt;/a&gt; to find the word &amp;#8220;execute&amp;#8221;.  Check it out!)&lt;/p&gt;</description>
      <pubDate>Thu, 14 Aug 2008 19:01:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:0b385642-e7db-489a-8751-d4d7b019ce8c</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2008/08/14/quintessence-the-fifth-element-for-the-agile-manifesto</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>The Seductions of Scala, Part II - Functional Programming</title>
      <description>&lt;p&gt;&lt;em&gt;A Functional Programming Language for the &lt;span class="caps"&gt;JVM&lt;/span&gt;&lt;/em&gt;&lt;/p&gt;


	&lt;p&gt;In my &lt;a href="http://blog.objectmentor.com/articles/2008/08/03/the-seductions-of-scala-part-i"&gt;last blog post&lt;/a&gt;, I discussed Scala&amp;#8217;s support for &lt;span class="caps"&gt;OOP&lt;/span&gt; and general improvements compared to Java. In this post, which I&amp;#8217;m posting from &lt;a href="http://www.agile2008.org/"&gt;Agile 2008&lt;/a&gt;, I discuss Scala&amp;#8217;s support for &lt;a href="http://en.wikipedia.org/wiki/Functional_programming"&gt;functional programming&lt;/a&gt; (FP) and why it should be of interest to OO developers.&lt;/p&gt;


	&lt;h3&gt;A Brief Overview of Functional Programming&lt;/h3&gt;


	&lt;p&gt;You might ask, don&amp;#8217;t most programming languages have functions? FP uses the term in the mathematical sense of the word. I hate to bring up bad memories, but you might recall from your school days that when you solved a function like&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
y = sin(x)
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;for &lt;code&gt;y&lt;/code&gt;, given a value of &lt;code&gt;x&lt;/code&gt;, you could input the same value of &lt;code&gt;x&lt;/code&gt; an arbitrary number of times and you would get the same value of &lt;code&gt;y&lt;/code&gt;. This means that &lt;code&gt;sin(x)&lt;/code&gt; has no &lt;em&gt;side effects&lt;/em&gt;. In other words, unlike our &lt;em&gt;imperative&lt;/em&gt; OO or &lt;em&gt;procedural&lt;/em&gt; code, no global or object state gets changed. All the work that a mathematical function does has to be returned in the result.&lt;/p&gt;


	&lt;p&gt;Similarly, the idea of a &lt;em&gt;variable&lt;/em&gt; is a little different than what we&amp;#8217;re used to in &lt;em&gt;imperative&lt;/em&gt; code. While the value of &lt;code&gt;y&lt;/code&gt; will vary with the value of &lt;code&gt;x&lt;/code&gt;, once you have fixed &lt;code&gt;x&lt;/code&gt;, you have also fixed &lt;code&gt;y&lt;/code&gt;. The implication for FP is that &amp;#8220;variables&amp;#8221; are immutable; once assigned, they cannot be changed. I&amp;#8217;ll call such immutable variables &lt;em&gt;value objects&lt;/em&gt;.&lt;/p&gt;


	&lt;p&gt;Now, it would actually be hard for a &amp;#8220;pure&amp;#8221; FP language to have no side effects, ever. I/O would be rather difficult, for example, since the state of the input or output stream changes with each operation. So, in practice, all &amp;#8220;pure&amp;#8221; FP languages provide some mechanisms for breaking the rules in a controlled way.&lt;/p&gt;


	&lt;p&gt;Functions are first-class objects in FP. You can create named or anonymous functions (&lt;em&gt;e.g.&lt;/em&gt;, &lt;em&gt;closures&lt;/em&gt; or &lt;em&gt;blocks&lt;/em&gt;), assign them to variables, pass them as arguments to other functions, &lt;em&gt;etc.&lt;/em&gt; Java doesn&amp;#8217;t support this. You have to create objects that wrap the methods you want to invoke.&lt;/p&gt;


	&lt;p&gt;Functional programs tend to be much more declarative in nature than imperative programs. This is perhaps more obvious in pure FP languages, like Erlang and Haskell, than it is in Scala.&lt;/p&gt;


	&lt;p&gt;For example, the definition of Fibonacci numbers is the following.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
F(n) = F(n-1) + F(n-2) where F(1)=1 and F(2)=1
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;An here is a complete implementation in Haskell.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
module Main where 
-- Function f returns the n'th Fibonacci number. 
-- It uses binary recursion. 
f n | n &amp;lt;= 2 = 1 
    | n &amp;gt;  2 = f (n-1) + f (n-2) 
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Without understanding the intricacies of Haskell syntax, you can see that the code closely matches the &amp;#8220;specification&amp;#8221; above it. The &lt;code&gt;f n | ...&lt;/code&gt; syntax defines the function &lt;code&gt;f&lt;/code&gt; taking an argument &lt;code&gt;n&lt;/code&gt; and the two cases of &lt;code&gt;n&lt;/code&gt; values are shown on separate lines, where one case is for &lt;code&gt;n &amp;lt;= 2&lt;/code&gt; and the other case if for &lt;code&gt;n &amp;gt; 2&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;The code uses the recursive relationship between different values of the function and the special-case values when &lt;code&gt;n = 1&lt;/code&gt; and &lt;code&gt;n = 2&lt;/code&gt;. The Haskell runtime does the rest of the work.&lt;/p&gt;


	&lt;p&gt;It&amp;#8217;s interesting that most &lt;a href="http://www.martinfowler.com/bliki/DomainSpecificLanguage.html"&gt;domain-specific languages&lt;/a&gt; are also declarative in nature. Think of how JMock, EasyMock or Rails&amp;#8217; ActiveRecord code look. The code is more succinct and it lets the &amp;#8220;system&amp;#8221; do most of the heavy lifting.&lt;/p&gt;


	&lt;h3&gt;Functional Programming&amp;#8217;s Benefits for You&lt;/h3&gt;


	&lt;h4&gt;Value Objects and Side-Effect Free Functions&lt;/h4&gt;


	&lt;p&gt;It&amp;#8217;s the immutable variables and side-effect free functions that help solve the &lt;a href="http://www.technologyreview.com/Infotech/17682/page1/"&gt;multicore problem&lt;/a&gt;. Synchronized access to shared state is not required if there is no state to manage. This makes robust concurrent programs far easier to write.&lt;/p&gt;


	&lt;p&gt;I&amp;#8217;ll discuss concurrency in Scala in my third post. For now, let&amp;#8217;s discuss other ways that FP in Scala helps to improve code, concurrent or not.&lt;/p&gt;


	&lt;p&gt;Value objects are beneficial because you can pass one around without worrying that someone will change it in a way that breaks other users of the object. Value objects aren&amp;#8217;t unique to FP, of course. They have been promoted in &lt;a href="http://domaindrivendesign.org/"&gt;Domain Driven Design&lt;/a&gt; (DDD), for example.&lt;/p&gt;


	&lt;p&gt;Similarly, side-effect free functions are safer to use. There is less risk that a caller will change some state inappropriately. The caller doesn&amp;#8217;t have to worry as much about calling a function. There are fewer surprises and everything of &amp;#8220;consequence&amp;#8221; that the function does is returned to the caller. It&amp;#8217;s easier to keep to the &lt;a href="http://www.objectmentor.com/resources/articles/srp.pdf"&gt;Single Responsibility Principle&lt;/a&gt; when writing side-effect free functions.&lt;/p&gt;


	&lt;p&gt;Of course, you can write side-effect free methods and immutable variables in Java code, but it&amp;#8217;s mostly a matter of discipline; the language doesn&amp;#8217;t give you any enforcement mechanisms.&lt;/p&gt;


	&lt;p&gt;Scala gives you a helpful enforcement mechanism; the ability to declare variables as &lt;code&gt;val&lt;/code&gt;&amp;#8217;s (&lt;em&gt;i.e.,&lt;/em&gt; &amp;#8220;values&amp;#8221;) &lt;em&gt;vs.&lt;/em&gt; &lt;code&gt;var&lt;/code&gt;&amp;#8217;s (&lt;em&gt;i.e.,&lt;/em&gt; &amp;#8220;variables&amp;#8221;, um&amp;#8230; back to the imperative programming sense of the word&amp;#8230;). In fact, &lt;code&gt;val&lt;/code&gt; is the default, where neither is required by the language. Also, the Scala library contains both immutable and mutable collections and it &amp;#8220;encourages&amp;#8221; you to use the immutable collections.&lt;/p&gt;


	&lt;p&gt;However, because Scala combines both &lt;span class="caps"&gt;OOP&lt;/span&gt; and FP, it doesn&amp;#8217;t force FP purity. The upside is that you get to use the approach that best fits the problem you&amp;#8217;re trying to solve. It&amp;#8217;s interesting that some of the Scala library classes expose FP-style interfaces, immutability and side-effect free functions, while using more traditional imperative code to implement them!&lt;/p&gt;


	&lt;h4&gt;Closures and First-Class Functions&lt;/h4&gt;


	&lt;p&gt;True to its functional side, Scala gives you true closures and first-class functions. If you&amp;#8217;re a Groovy or Ruby programmer, you&amp;#8217;re used to the following kind of code.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
class ExpensiveResource {
    def open(worker: () =&amp;gt; Unit) = {
        try {
            println("Doing expensive initialization")
            worker()
        } finally {
            close()
        }
    }
    def close() = {
        println("Doing expensive cleanup")
    }
}
// Example use:
try {
    (new ExpensiveResource()) open { () =&amp;gt;        // 1
        println("Using Resource")                 // 2
        throw new Exception("Thrown exception")   // 3
    }                                             // 4
} catch {
    case ex: Throwable =&amp;gt; println("Exception caught: "+ex)
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Running this code will yield:&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
Doing expensive initialization
Using Resource
Doing expensive cleanup
Exception caught: java.lang.Exception: Thrown exception
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;The &lt;code&gt;ExpensiveResource.open&lt;/code&gt; method invokes the user-specified &lt;code&gt;worker&lt;/code&gt; function. The syntax &lt;code&gt;worker: () =&amp;gt; Unit&lt;/code&gt; defines the &lt;code&gt;worker&lt;/code&gt; parameter as a function that takes no arguments and returns nothing (recall that &lt;code&gt;Unit&lt;/code&gt; is the equivalent of &lt;code&gt;void&lt;/code&gt;).&lt;/p&gt;


	&lt;p&gt;&lt;code&gt;ExpensiveResource.open&lt;/code&gt; handles the details of initializing the resource, invoking the worker, and doing the necessary cleanup.&lt;/p&gt;


	&lt;p&gt;The example marked with the comment &lt;code&gt;// 1&lt;/code&gt; creates a new &lt;code&gt;ExpensiveResource&lt;/code&gt;, then calls &lt;code&gt;open&lt;/code&gt;, passing it an anonymous function, called a &lt;em&gt;function literal&lt;/em&gt; in Scala terminology. The function literal is of the form &lt;code&gt;(arg_list_) =&amp;gt; function body&lt;/code&gt; or &lt;code&gt;() =&amp;gt; println(...) ...&lt;/code&gt;, in our case.&lt;/p&gt;


	&lt;p&gt;A special syntax trick is used on this line; if a method takes one argument, you can change expressions of the form &lt;code&gt;object.method(arg)&lt;/code&gt; to &lt;code&gt;object method {arg}&lt;/code&gt;. This syntax is supported to allow user-defined methods to read like control structures (think &lt;code&gt;for&lt;/code&gt; statements &amp;#8211; see the next section). If you&amp;#8217;re familiar with Ruby, the four commented lines read a lot like Ruby syntax for passing blocks to methods.&lt;/p&gt;


	&lt;p&gt;Idioms like this are very important. A library writer can encapsulate all complex, error-prone logic and allow the user to specify only the unique work required in a given situation. For example, How many times have you written code that opened an I/O stream or a database connection, used it, then cleaned up. How many times did you get the idiom &lt;a href="http://blog.objectmentor.com/articles/2008/07/31/always-close-in-a-finally-block"&gt;wrong&lt;/a&gt;, especially the proper cleanup when an exception is thrown? First-class functions allow writers of I/O, database and other resource libraries to do the correct implementation &lt;em&gt;once&lt;/em&gt;, eliminating user error and duplication. Here&amp;#8217;s a rhetorical question I always ask myself:&lt;/p&gt;


	&lt;blockquote&gt;
		&lt;p&gt;How can I make it &lt;strong&gt;impossible&lt;/strong&gt; for the user of this &lt;span class="caps"&gt;API&lt;/span&gt; to fail?&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;h4&gt;Iterations&lt;/h4&gt;


	&lt;p&gt;Iteration through collections, &lt;code&gt;Lists&lt;/code&gt; in particular, is even more common in FP than in imperative languages. Hence, iteration is highly evolved. Consider this example:&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
object RequireWordsStartingWithPrefix {
    def main(args: Array[String]) = {
        val prefix = args(0)
        for {
            i &amp;lt;- 1 to (args.length - 1)   // no semicolon
            if args(i).startsWith(prefix)
        } println("args("+i+"): "+args(i))
    }
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Compiling this code with &lt;code&gt;scalac&lt;/code&gt; and then running it on the command line with the command&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
scala RequireWordsStartingWithPrefix xx xy1 xx1 yy1 xx2 xy2
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;produces the result&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
args(2): xx1
args(5): xx2
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;The for loop assigns a loop variable &lt;code&gt;i&lt;/code&gt; with each argument, but only if the &lt;code&gt;if&lt;/code&gt; statement is true. Instead of curly braces, the for loop argument list could also be parenthesized, but then each line as shown would have to be separated by a semi-colon, like we&amp;#8217;re used to seeing with Java for loops.&lt;/p&gt;


	&lt;p&gt;We can have an arbitrary number of assignments and conditionals. In fact, it&amp;#8217;s quite common to filter lists:&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
object RequireWordsStartingWithPrefix2 {
    def main(args: Array[String]) = {
        val prefix = args(0)
        args.slice(1, args.length)
            .filter((arg: String) =&amp;gt; arg.startsWith(prefix))
            .foreach((arg: String) =&amp;gt; println("arg: "+arg))
    }
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;This version yields the same result. In this case, the args array is sliced (loping off the search prefix), the resulting array is filtered using a function literal and the filtered array is iterated over to print out the matching arguments, again using a function literal.  This version of the algorithm should look familiar to Ruby programmers.&lt;/p&gt;


	&lt;h4&gt;Rolling Your Own &lt;em&gt;Function Objects&lt;/em&gt;&lt;/h4&gt;


	&lt;p&gt;Scala still has to support the constraints of the &lt;span class="caps"&gt;JVM&lt;/span&gt;. As a comment to the first blog post said, the Scala compiler wraps closures and &amp;#8220;bare&amp;#8221; functions in &lt;code&gt;Function&lt;/code&gt; objects. You can also make other objects behave like functions. If your object implements the &lt;code&gt;apply&lt;/code&gt; method, that method will be invoked if you put parentheses with an matching argument list on the object, as in the following example.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
class HelloFunction {
    def apply() = "hello" 
    def apply(name: String) = "hello "+name
}
val hello = new HelloFunction
println(hello())        // =&amp;gt; "hello" 
println(hello("Dean"))  // =&amp;gt; "hello Dean" 
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;h4&gt;Option, None, Some&amp;#8230;&lt;/h4&gt;


	&lt;p&gt;Null pointer exceptions suck. You can still get them in Scala code, because Scala runs on the &lt;span class="caps"&gt;JVM&lt;/span&gt; and interoperates with Java libraries, but Scala offers a better way.&lt;/p&gt;


	&lt;p&gt;Typically, a reference might be null when there is nothing appropriate to assign to it. Following the conventions in some FP languages, Scala has an &lt;code&gt;Option&lt;/code&gt; type with two subtypes, &lt;code&gt;Some&lt;/code&gt;, which wraps a value, and &lt;code&gt;None&lt;/code&gt;, which is used instead of &lt;code&gt;null&lt;/code&gt;. The following example, which also demonstrates Scala&amp;#8217;s &lt;code&gt;Map&lt;/code&gt; support, shows these types in action.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
val hotLangs = Map(
    "Scala" -&amp;gt; "Rocks", 
    "Haskell" -&amp;gt; "Ethereal", 
    "Java" -&amp;gt; null)
println(hotLangs.get("Scala"))          // =&amp;gt; Some(Rocks)
println(hotLangs.get("Java"))           // =&amp;gt; Some(null)
println(hotLangs.get("C++"))            // =&amp;gt; None
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Note that &lt;code&gt;Map&lt;/code&gt; stores values in &lt;code&gt;Options&lt;/code&gt; objects, as shown by the &lt;code&gt;println&lt;/code&gt; statements.&lt;/p&gt;


	&lt;p&gt;By the way, those &lt;code&gt;-&amp;gt;&lt;/code&gt; aren&amp;#8217;t special operators; they&amp;#8217;re methods. Like &lt;code&gt;::&lt;/code&gt;, valid method names aren&amp;#8217;t limited to alphanumerics, &lt;code&gt;_&lt;/code&gt;, and &lt;code&gt;$&lt;/code&gt;.&lt;/p&gt;


	&lt;h4&gt;Pattern Matching&lt;/h4&gt;


	&lt;p&gt;The last FP feature I&amp;#8217;ll discuss in this post is pattern matching, which is exploited more fully in FP languages than in imperative languages.&lt;/p&gt;


	&lt;p&gt;Using our previous definition of &lt;code&gt;hotLangs&lt;/code&gt;, here&amp;#8217;s how you might use matching.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
def show(key: String) = {
    val value: Option[String] = hotLangs.get(key)
    value match {
        case Some(x) =&amp;gt; x
        case None =&amp;gt; "No hotness found" 
    }
}
println(show("Scala"))  // =&amp;gt; "Rocks" 
println(show("Java"))   // =&amp;gt; "null" 
println(show("C++"))    // =&amp;gt; "No hotness found" 
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;The first &lt;code&gt;case&lt;/code&gt; statement, &lt;code&gt;case Some(x) =&amp;gt; x&lt;/code&gt;, says &amp;#8220;if the &lt;code&gt;value&lt;/code&gt; I&amp;#8217;m matching against is a &lt;code&gt;Some&lt;/code&gt; that could be constructed with the &lt;code&gt;Some[+String](x: A)&lt;/code&gt; constructor, then return the &lt;code&gt;x&lt;/code&gt;, the thing the &lt;code&gt;Some&lt;/code&gt; contains.&amp;#8221; Okay, there&amp;#8217;s a lot going on here, so more background information is in order.&lt;/p&gt;


	&lt;p&gt;In Scala, like Ruby and other languages, the last value computed in a function is returned by it. Also, almost everything returns a value, including &lt;code&gt;match&lt;/code&gt; statements, so when the &lt;code&gt;Some(x) =&amp;gt; x&lt;/code&gt; case is chosen, &lt;code&gt;x&lt;/code&gt; is returned by the &lt;code&gt;match&lt;/code&gt; and hence by the function.&lt;/p&gt;


	&lt;p&gt;&lt;code&gt;Some&lt;/code&gt; is a generic class and the &lt;code&gt;show&lt;/code&gt; function returns a &lt;code&gt;String&lt;/code&gt;, so the match is to &lt;code&gt;Some[+String]&lt;/code&gt;. The &lt;code&gt;+&lt;/code&gt; in the &lt;code&gt;+String&lt;/code&gt; expression is analogous to Java&amp;#8217;s &lt;code&gt;extends&lt;/code&gt;, &lt;em&gt;i.e.,&lt;/em&gt; &lt;code&gt;&amp;lt;? extends String&amp;gt;&lt;/code&gt;. Capiche?&lt;/p&gt;


	&lt;p&gt;Idioms like &lt;code&gt;case Some(x) =&amp;gt; x&lt;/code&gt; are called &lt;em&gt;extractors&lt;/em&gt; in Scala and are used a lot in Scala, as well as in FP, in general. Here&amp;#8217;s another example using Lists and our friend &lt;code&gt;::&lt;/code&gt;, the &amp;#8220;cons&amp;#8221; operator.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
def countScalas(list: List[String]): Int = {
    list match {
        case "Scala" :: tail =&amp;gt; countScalas(tail) + 1
        case _ :: tail       =&amp;gt; countScalas(tail)
        case Nil             =&amp;gt; 0
    }
}
val langs = List("Scala", "Java", "C++", "Scala", "Python", "Ruby")
val count = countScalas(langs)
println(count)    // =&amp;gt; 2
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;We&amp;#8217;re counting the number of occurrences of &amp;#8220;Scala&amp;#8221; in a list of strings, using matching and recursion and no explicit iteration.  An expression of the form &lt;code&gt;head :: tail&lt;/code&gt; applied to a list returns the first element set as the &lt;code&gt;head&lt;/code&gt; variable and the rest of the list set as the &lt;code&gt;tail&lt;/code&gt; variable. In our case, the first &lt;code&gt;case&lt;/code&gt; statement looks for the particular case where the head equals &lt;code&gt;Scala&lt;/code&gt;. The second &lt;code&gt;case&lt;/code&gt; matches all lists, except for the empty list (&lt;code&gt;Nil&lt;/code&gt;). Since matches are eager, the first &lt;code&gt;case&lt;/code&gt; will always pick out the &lt;code&gt;List("Scala", ...)&lt;/code&gt; case first. Note that in the second &lt;code&gt;case&lt;/code&gt;, we don&amp;#8217;t actually care about the value, so we use the placeholder &lt;code&gt;_&lt;/code&gt;. Both the first and second &lt;code&gt;case&lt;/code&gt;&amp;#8217;s call &lt;code&gt;countScalas&lt;/code&gt; recursively.&lt;/p&gt;


	&lt;p&gt;Pattern matching like this is powerful, yet succinct and elegant. We&amp;#8217;ll see more examples of matching in the next blog post on concurrency using message passing.&lt;/p&gt;


	&lt;h2&gt;Recap of Scala&amp;#8217;s Functional Programming&lt;/h2&gt;


	&lt;p&gt;I&amp;#8217;ve just touched the tip of the iceberg concerning functional programming (and I hope I got all the details right!). Hopefully, you can begin to see why we&amp;#8217;ve overlooked FP for too long!&lt;/p&gt;


	&lt;p&gt;In my last post, I&amp;#8217;ll wrap up with a look at Scala&amp;#8217;s approach to concurrency, the Actor model of message passing.&lt;/p&gt;</description>
      <pubDate>Tue, 05 Aug 2008 20:32:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:e80aea1f-2ab7-41fa-b431-8d7a5a29c6ed</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2008/08/05/the-seductions-of-scala-part-ii-functional-programming</link>
      <category>Dean's Deprecations</category>
      <category>Design Principles</category>
      <category>Clean Code</category>
      <category>functional</category>
      <category>objects</category>
      <category>FP</category>
      <category>OOP</category>
      <category>Scala</category>
      <category>Java</category>
    </item>
    <item>
      <title>Bauble, Bauble...</title>
      <description>&lt;p&gt;In Ruby, I hate require statements that look like this:&lt;/p&gt;


&lt;code&gt;
require File.dirname(__FILE__)+"myComponent/component.rb" 
&lt;/code&gt;

	&lt;p&gt;So I decided to do something about it.&lt;/p&gt;


	&lt;p&gt;This all started when my Son, Micah, told me about his &lt;a href="http://limelight.8thlight.com/"&gt;Limelight&lt;/a&gt; project.  Limelight is a jruby/swing &lt;span class="caps"&gt;GUI&lt;/span&gt; framework.  If you want to build a fancy &lt;span class="caps"&gt;GUI&lt;/span&gt; in Ruby, consider this tool.&lt;/p&gt;


	&lt;p&gt;I have neither the time nor inclination to write a framework like this; but my curiosity was piqued.  So in order to see what it was like to do Swing in JRuby I spent a few hours cobbling together an implementation of &lt;a href="http://en.wikipedia.org/wiki/Langton's_ant"&gt;Langton&amp;#8217;s Ant&lt;/a&gt;.   This turned out to be quite simple.&lt;/p&gt;


	&lt;p&gt;The result, however, was a mess.  There was swing code mixed up with &amp;#8220;ant&amp;#8221; code, in the classic &lt;span class="caps"&gt;GUI&lt;/span&gt;/Business-rule goulash that we &amp;#8220;clean-coders&amp;#8221; hate so much.  Despite the fact that this was throw-away code, I could not leave it in that state &amp;#8211; the moral outrage was just too great.  So I spent some more time separating the program into two modules.&lt;/p&gt;


	&lt;p&gt;The first module knew all about Langton&amp;#8217;s ant, but nothing about Swing.  The second module was a tiny framework for implementing cellular automata in Swing.  (Here are all the &lt;a href="http://www.fitnesse.org/files/unclebob/BaubleBlog.tz"&gt;files&lt;/a&gt;).&lt;/p&gt;


	&lt;p&gt;I was quite happy with the separation, but did not like the horrible &lt;code&gt;require&lt;/code&gt; statements that I had to use.  The cellular_automaton component had two classes, in two separate files.  In order to get the &lt;code&gt;require&lt;/code&gt; right, I had to either use absolute directory paths, or the horrible &lt;code&gt;File.dirname(__FILE__)...&lt;/code&gt; structure.&lt;/p&gt;


	&lt;p&gt;What I wanted was for cellular_automaton to behave like a &lt;a href="http://www.rubygems.org"&gt;gem&lt;/a&gt;.  But I didn&amp;#8217;t want to make it into a gem.  Gem&amp;#8217;s are kind of &amp;#8220;heavy&amp;#8221; for a dumb little thing like &amp;#8220;cellular_automaton&amp;#8221;.&lt;/p&gt;


	&lt;p&gt;So I created a module named &amp;#8220;Bauble&amp;#8221; which gave me some gem-like behaviors.  Here it is:&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;
module Bauble
  def self.use(bauble)
    bauble_name = File.basename(bauble)
    ensure_in_path "#{bauble}/lib" 
    require bauble_name
  end

  def self.ensure_in_path(path)
    $LOAD_PATH &amp;lt;&amp;lt; path unless $LOAD_PATH.include? path
  end
end
&lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;This is no great shakes, but it solved my problem.  Now, in my langton&amp;#8217;s ant program all I need to do is this:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
require 'bauble'
Bauble.use('../cellular_automaton')
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;All the ugly requires are gone.&lt;/p&gt;


	&lt;p&gt;I&amp;#8217;m thinking about turning Bauble into a rubyforge project, and making a publicly available gem out of it in order to give folks a standard way to avoid those horrible &lt;code&gt;__FILE__&lt;/code&gt; requires.  I think there are several other utilities that could be placed in Bauble such as &lt;code&gt;require_relative&lt;/code&gt; etc.&lt;/p&gt;


	&lt;p&gt;Anyway, what do you think?&lt;/p&gt;</description>
      <pubDate>Sun, 20 Jul 2008 15:42:29 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:23960702-3bfc-4787-92b6-4dd489cd5f24</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2008/07/20/bauble-bauble</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Dynamic Languages</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Now 'and' for something completely different.</title>
      <description>&lt;p&gt;My son Justin is working as a Ruby apprentice for my son Micah at &lt;a href="http://www.8thlight.com"&gt;8th light&lt;/a&gt;. We were sitting at the kitchen table, and he showed me a function he was writing.  In the midst of the function I saw this:&lt;/p&gt;


&lt;code&gt;handle_batch(item) and display_batch(item) while items_remaining?&lt;/code&gt;
&lt;br&gt;&lt;br&gt;
I looked hard at this and then I said: &amp;#8220;Justin, I don&amp;#8217;t think you understand what &lt;code&gt;and&lt;/code&gt; does.   

	&lt;p&gt;He said: &amp;#8220;I think I do.&amp;#8221; and he pointed me to a &lt;a href="http://www.rubyinside.com/21-ruby-tricks-902.html"&gt;website&lt;/a&gt; which showed 21 Ruby tricks &amp;#8220;you &lt;em&gt;should&lt;/em&gt; be using in your own code.&amp;#8221;&lt;/p&gt;


	&lt;p&gt;Trick #9 was the use of the &lt;code&gt;and&lt;/code&gt; keyword to couple statements together to make &amp;#8220;one liners&amp;#8221;.  It was billed as a trick that &lt;em&gt;[cough]&lt;/em&gt; &amp;#8220;more confident&amp;#8221; Ruby programmers use.&lt;/p&gt;


	&lt;p&gt;So I got the pickaxe book out and looked up the &lt;code&gt;and&lt;/code&gt; keyword.  I showed Justin where it said that the second clause won&amp;#8217;t be executed if the first clause is &lt;code&gt;false&lt;/code&gt; &lt;em&gt;(or &lt;code&gt;nil&lt;/code&gt;!)&lt;/em&gt;  So if &lt;code&gt;handle_batch&lt;/code&gt; ever returned &lt;code&gt;nil&lt;/code&gt;, then &lt;code&gt;display_batch&lt;/code&gt; would never be called.&lt;/p&gt;


	&lt;p&gt;Warning bells were going off in my head.  This was clearly an unintended use of the &lt;code&gt;and&lt;/code&gt; keyword that could have rather nasty repercussions.  I thought it was somewhat irresponsible for a website that boasted expertise in programming to tell people they should be using a dangerous stunt like this.&lt;/p&gt;


	&lt;p&gt;However, &lt;code&gt;handle_batch&lt;/code&gt; did &lt;em&gt;not&lt;/em&gt; return &lt;code&gt;nil&lt;/code&gt;, so the &lt;code&gt;and&lt;/code&gt; worked well enough in this case; and we had more to do.  So I made my point to Justin and then we kept working, leaving the &lt;code&gt;and&lt;/code&gt; in place.&lt;/p&gt;


	&lt;p&gt;An hour later we were making changes to a function.  Suddenly a whole bunch of our tests broke. (You know what I&amp;#8217;m going to say, don&amp;#8217;t you?)  The failure mode didn&amp;#8217;t make any sense.  Suddenly a whole bunch of processing simply wasn&amp;#8217;t getting done.&lt;/p&gt;


	&lt;p&gt;It was Justin who said: &amp;#8220;Wow, I&amp;#8217;ll bet it&amp;#8217;s that &lt;code&gt;and&lt;/code&gt;.  And it was.  The change we had made had indirectly caused &lt;code&gt;handle_batch&lt;/code&gt; to return a &lt;code&gt;nil&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;OK, this was a fun little story.  You might think the moral is &amp;#8220;don&amp;#8217;t use and for one-liners&amp;#8221; or &amp;#8220;don&amp;#8217;t trust websites that claim expertise&amp;#8221;.  Yes, those would be good conclusions to draw.  But I&amp;#8217;m concerned about something else.&lt;/p&gt;


	&lt;p&gt;The &amp;#8220;and trick&amp;#8221; is &lt;em&gt;clever&lt;/em&gt;.  In programming, &lt;em&gt;clever&lt;/em&gt; != &lt;em&gt;smart&lt;/em&gt;.  (OK, sorry, that was clever&amp;#8230;)  Using a keyword like &lt;code&gt;and&lt;/code&gt; in a manner for which it was not intended, and in a way that is not guaranteed to work in all cases, is risky. It bothers me.&lt;/p&gt;


	&lt;p&gt;By the same token it bothers me that so many Ruby programmers use the &lt;code&gt;||=&lt;/code&gt; trick for lazy initialization.  I know it works.  I know it&amp;#8217;s a standard idiom.  I&amp;#8217;m not trying to stop people from doing it.  Hell, I use it too because it&amp;#8217;s become a standard idiom. But it bothers me nonetheless because it entered our vocabulary of idioms because it was clever trick; and clever little tricks have a way of turning into nasty little surprises.&lt;/p&gt;


	&lt;p&gt;Ruby is a fun and powerful language.  But that doesn&amp;#8217;t mean we should go out of our way to be clever.  We shouldn&amp;#8217;t be eager to adopt quirky little idioms and erudite little stunts just because they are cute, or neat, or nifty.   Code is hard enough to understand without having to think sideways through the next novel application of the ?: operator.&lt;/p&gt;


	&lt;p&gt;Professionals write clear and clean code.  They use their language well.  They use their language efficiently.  But they don&amp;#8217;t aspire to be master tricksters.  Rather, they prove their professionalism by writing code that &lt;em&gt;needs no explanation&lt;/em&gt;.&lt;/p&gt;</description>
      <pubDate>Thu, 26 Jun 2008 13:16:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:44ccdb8f-f0b0-43dc-9695-d7bcd97e6b4f</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2008/06/26/now-and-for-something-completely-different</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Dynamic Languages</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>So...  You want your code to be maintainable.</title>
      <description>&lt;p&gt;We know that maintenance is 90% of the software lifecycle, and 90% of the cost.  We know that our systems need to be flexible, reusable, and maintainable.  Indeed, that&amp;#8217;s why we spend so much of our time trying to get the design and architecture just right.  Because we all know that good design and architecture is the key to flexibility, reusability, and maintainability&amp;#8230;right?&lt;/p&gt;


	&lt;p&gt;Of course.  Good design and architecture is what makes software easy to change.  Good design and architecture separates the things that change for one reason from the things that change for another reason (The Single Responsibility Principle).  Good design allows us to add new features without changing a lot of old code (Open Closed Principle).  Good design makes sure that high level policy does not depend on low level detail (Dependency Inversion Principle), etc. etc.&lt;/p&gt;


	&lt;p&gt;So how do we get good design?  Well, that&amp;#8217;s tricky.  Oh it&amp;#8217;s not too tricky to get a good design in place at first.  The tricky part is to keep the design good.   That&amp;#8217;s the problem, you see.  It&amp;#8217;s not that the design starts out so bad (although sometimes&amp;#8230;) rather it is that the design degrades over time as the system changes.&lt;/p&gt;


	&lt;p&gt;Systems change. Often they change in ways that thwart the original intent of the design.  Unfortunately, changing the design to align to these changes is &lt;em&gt;hard&lt;/em&gt;.  So we wind up hacking the new features into the system and thwarting the design.  And that&amp;#8217;s how even the best designed systems rot.&lt;/p&gt;


	&lt;p&gt;So how do we keep the design from rotting?  How do we make sure we can migrate the design as the system changes?  Simple.  Tests.&lt;/p&gt;


	&lt;p&gt;When you have a suite of tests that covers &amp;gt;90% of the code in the system, you are not afraid to make changes.  Every time you make a little change you run those tests, and you &lt;em&gt;know&lt;/em&gt; that you have not broken anything.  This gives you the confidence to make the next change, and the next, and the next.  &lt;em&gt;It gives you the confidence to change the design!&lt;/em&gt;&lt;/p&gt;


	&lt;p&gt;Nothing makes a system more flexible than a suite of tests.  Nothing.  Good architecture and design are important; but the affect of a robust suite of tests is an order of magnitude greater.  It&amp;#8217;s so much greater because those tests enable you to improve the design.&lt;/p&gt;


	&lt;p&gt;This can&amp;#8217;t be overstated.  If you want your systems to be flexible, write tests.  If you want your systems to be reusable, write tests.  If you want your systems to be maintainable, write tests.&lt;/p&gt;


	&lt;p&gt;And write your tests using the &lt;a href="http://blog.briandicroce.com/2008/03/14/three-index-cards-to-easily-remember-the-essence-of-test-driven-development/"&gt;Three Laws of &lt;span class="caps"&gt;TDD&lt;/span&gt;&lt;/a&gt;.&lt;/p&gt;</description>
      <pubDate>Tue, 24 Jun 2008 23:07:46 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:cb887e07-ff3c-4fe1-af2c-11151049fe41</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2008/06/24/so-you-want-your-code-to-be-maintainable</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Agile Methods</category>
      <category>Design Principles</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title> What We Can Learn from the Ojibwe Language</title>
      <description>&lt;p&gt;Ojibwe (sometimes spelled Ojibwa; the last syllable is pronounced &amp;#8220;way&amp;#8221;) is one of the few Native American languages that isn&amp;#8217;t immediately threatened with extinction. It is spoken by about 10,000 people around the Great Lakes region. Brothers David and Anton Treuer are helping to keep it alive, as they discussed in a recent &lt;a href="http://www.npr.org/templates/story/story.php?storyId=89851668"&gt;Fresh Air interview&lt;/a&gt;.&lt;/p&gt;


	&lt;p&gt;Ojibwe is a language that is optimized for an aboriginal people whose lives and livelihoods depend on an intimate awareness of their environment, especially the weather and water conditions. They have many nouns and verbs for fine gradations of rain, snow, ice conditions, the way water waves look and sound, &lt;em&gt;etc&lt;/em&gt;. You would want this clarity of detail if you ventured out on a lake every day to fish for dinner.&lt;/p&gt;


	&lt;p&gt;In the past, speaking languages like Ojibwe was actively suppressed by the government, in an attempt to assimilate Native Americans. Today, the threat of extinction is more from the sheer ubiquity of English. I think there is another force at play, too. People living a modern, so-called &amp;#8220;developed&amp;#8221; lifestyle just don&amp;#8217;t need to be so aware of their environment anymore. In fact, most of us are pretty &amp;#8220;tone deaf&amp;#8221; to the nuances of weather and water, which is sad in a way. We just don&amp;#8217;t perceive the need for the richness of an Ojibwe to communicate what&amp;#8217;s important to us, like sports trivia and fashion tips.&lt;/p&gt;


	&lt;p&gt;So, what does Ojibwe have to do with programming languages? Our language choices inform the way we frame problem solving and design. I was reminded of this recently while reading Ted Neward&amp;#8217;s &lt;a href="http://www.ibm.com/developerworks/views/java/libraryview.jsp?search_by=scala+neward"&gt;series of articles on Scala&lt;/a&gt;. Scala is a &lt;span class="caps"&gt;JVM&lt;/span&gt; language that provides first-class support for &lt;a href="http://en.wikipedia.org/wiki/Functional_programming"&gt;functional programming&lt;/a&gt; and object-oriented design refinements like &lt;a href="http://www.iam.unibe.ch/~scg/Research/Traits/"&gt;traits&lt;/a&gt;, which provide &lt;a href="http://c2.com/cgi/wiki?MixIn"&gt;mixin&lt;/a&gt; behavior.&lt;/p&gt;


	&lt;p&gt;While you can write Java-like code in Scala, Neward demonstrates how exploiting Scala features can result in very different code for many problems. The Scala examples are simpler, but sometimes that simplicity only becomes apparent after you grasp the underlying design principle in use, like closures or functional idioms.&lt;/p&gt;


	&lt;p&gt;One of the best pieces of advice in the &lt;a href="http://www.pragprog.com/the-pragmatic-programmer"&gt;Pragmatic Programmer&lt;/a&gt; is to learn a new language every year. You should pick a language that is very different from what you know already, not one that is fundamentally similar. Even if you won&amp;#8217;t use that language in your professional work, understanding its principles, patterns, and idioms will inform your work in whatever languages you actually use.&lt;/p&gt;


	&lt;p&gt;For example, there is a lot of &lt;a href="http://www.technologyreview.com/Infotech/17682/page1/"&gt;fretting&lt;/a&gt; these days about concurrent programming, given the rise of multi-core CPUs and multiprocessor computers.  We know &lt;a href="http://www.javaconcurrencyinpractice.com/"&gt;how to write concurrent programs&lt;/a&gt; in our most popular &lt;em&gt;imperative&lt;/em&gt; languages, like Java and C++, but that knowledge is somewhat specialized and not widely known in the community. This is the main reason that &lt;a href="http://en.wikipedia.org/wiki/Functional_programming"&gt;functional programming&lt;/a&gt; is suddenly interesting again. It is inherently easier to write concurrent applications using side-effect-free code. I expect that we will fail to meet the concurrency challenge if we rely exclusively on the mechanisms in our imperative languages.&lt;/p&gt;


	&lt;p&gt;So, you could adopt a functional language for all or part of your concurrent application. Or, if you can&amp;#8217;t use Scala (or Haskell or Erlang or &amp;#8230;) you could at least apply functional idioms, like  side-effect-free functions, avoidance of mutable objects, &lt;em&gt;etc.&lt;/em&gt; in your current imperative language. However, even that won&amp;#8217;t be an option unless you understand those principles in the first place.&lt;/p&gt;


	&lt;p&gt;Learning a new language is more than learning a new vocabulary. It&amp;#8217;s even more than learning new design techniques. It&amp;#8217;s also learning to see common things from a fresh perspective, with greater clarity.&lt;/p&gt;</description>
      <pubDate>Sat, 03 May 2008 09:48:57 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:d5cda248-84da-418d-81ae-5419241465a0</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2008/05/03/what-we-can-learn-from-the-ojibwe-language</link>
      <category>Dean's Deprecations</category>
      <category>Design Principles</category>
      <category>Clean Code</category>
      <category>languages</category>
      <category>polyglot</category>
      <category>programming</category>
      <category>multilingual</category>
      <category>design</category>
    </item>
    <item>
      <title>Clean Code.  Whew!</title>
      <description>&lt;p&gt;I&amp;#8217;ve been working on this book for several years now.  After a flurry of effort (you might have noticed I&amp;#8217;ve been quiet lately) I&amp;#8217;m very pleased to say that I&amp;#8217;m done with the writing and am preparing the manuscript for production. See &lt;a href="http://www.pearsonhighered.com/educator/academic/product/1,3110,0132350882,00.html"&gt;The Prentice Hall Listing&lt;/a&gt;&lt;/p&gt;


	&lt;p&gt;&lt;img src="http://vig-fp.prenhall.com/bigcovers/0132350882.jpg" alt="" /&gt;&lt;/p&gt;


&lt;pre&gt;Table of Contents

Clean Code    1
    There Will Be Code    1
    Bad Code    2
    The Total Cost of Owning a Mess.    3
    Schools of Thought.    11
    We are Authors.    12
    The Boy Scout Rule    13
    Prequel and Principles    14
    Conclusion    14
    Bibliography    15
Meaningful Names by Tim Ottinger    17
    Introduction    17
    Use Intention-revealing Names    17
    Avoid Disinformation    19
    Make Meaningful Distinctions    20
    Use Pronounceable Names    21
    Use Searchable Names    22
    Avoid Encodings    23
    Avoid Mental Mapping    24
    Class Names    25
    Method Names    25
    Don't Be Cute    25
    Pick One Word Per Concept    26
    Don't Pun    26
    Use Solution Domain Names    27
    Use Problem Domain Names    27
    Add Meaningful Context    27
    Don't add Gratuitous Context    29
    Final Words ...    30
Functions    31
    Small!    34
    Do one thing.    35
    One level of abstraction per function.    36
    Switch Statements.    37
    Use descriptive names.    39
    Function Arguments.    39
    Have no side-effects.    43
    Command Query Separation    44
    Prefer exceptions to returning error codes.    45
    Don't Repeat Yourself.    47
    Structured Programming    48
    How do you write functions like this?    48
    Conclusion    49
    SetupTeardownIncluder    49
    Bibliography    52
Comments    53
    Comments do not make up for bad code.    55
    Explain yourself in code.    55
    Good Comments    55
    Bad Comments    59
    Example    71
    Bibliography    74
Formatting    75
    The Purpose of Formatting    76
    Vertical Formatting    76
    Horizontal Formatting    84
    Team Rules    89
    Uncle Bob's Formatting Rules.    90
Objects and Data Structures    93
    Data Abstraction    93
    Data/Object anti-symmetry.    95
    The Law of Demeter    97
    Data Transfer Objects    99
    Conclusion    101
    Bibliography    101
Error Handling by Michael Feathers    103
    Use Exceptions Rather than Return Codes    103
    Write Your Try-Catch-Finally Statement First    105
    Use Unchecked Exceptions    106
    Provide Context with Exceptions    107
    Define Exception Classes In Terms of a Caller's Needs.    107
    Define the Normal Flow    109
    Don't Return Null    110
    Don't Pass Null    111
    Conclusion    112
    Bibliography    112
Boundaries by James Grenning    113
    Bibliography    119
Unit Tests    121
    The Three Laws of TDD    122
    Keeping Tests Clean    123
    Clean Tests    124
    One Assert per Test    129
    F.I.R.S.T.    132
    Conclusion    132
    Bibliography    133
Classes    135
    Class Organization    135
    Classes should be Small!    136
    Organizing for Change    146
    Bibliography    150
Systems    By Dean Wampler 151
    How would you build a city?    151
    Separate constructing a system from using it    152
    Scaling Up    155
    Java Proxies    158
    Pure Java AOP Frameworks    160
    AspectJ Aspects    163
    Test-drive the system architecture    164
    Optimize decision making    165
    Use standards wisely, when they add demonstrable value    165
    Systems need Domain-Specific Languages    166
    Conclusion    166
    Bibliography    167
Emergence By Jeff Langr    169
    Getting Clean via Emergent Design    169
    Simple Design Rule 1: Runs all the tests    170
    Simple Design Rules 2-4: Refactoring    170
    No Duplication    170
    Expressive    173
    Minimal Classes and Methods    174
    Conclusion    174
    Bibliography    174
Concurrency    by Brett Schuchert 175
    Why Concurrency?    176
    Challenges    177
    Concurrency Defense Principles    178
    Know Your Library    180
    Know Your Execution Models    181
    Beware Dependencies between Syncrhonized Methods    182
    Keep Synchronized Sections Small    183
    Writing Correct Shut-Down Code is Hard    183
    Testing Threaded Code    184
    Conclusion    188
    Bibliography    189
Successive Refinement    191
    Args Implementation    192
    Args: the rough draft.    198
    String Arguments    212
     Conclusion    246
JUnit Internals    249
    Conclusion    262
Refactoring SerialDate    263
    Conclusion    280
    Bibliography    281
Smells and Heuristics    283
    Comments    283
    Environment    284
    Functions    285
    General    285
    Java    304
    Names    306
    Tests    310
    Conclusion    311
    Bibliography    312
Concurrency II    by Brett Schuchert 313
    Client/Server Example    313
    Possible Paths of Execution    317
    Knowing Your Library    322
    Dependencies between methods can break concurrent code    325
    Increasing Throughput    329
    Deadlock    331
    Testing Multi-Threaded Code    335
    Tool Support for Testing Thread-Based Code    337
    Conclusion    338
    Tutorial: Full Code Examples    339
org.jfree.date.SerialDate    345
Cross References of Heuristics    406
&lt;/pre&gt;</description>
      <pubDate>Tue, 08 Apr 2008 00:10:16 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:0280362f-4830-42b9-84db-edaa724b41b1</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2008/04/08/clean-code-whew</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Clean Code.  Whew!</title>
      <description>&lt;p&gt;I&amp;#8217;ve been working on this book for several years now.  After a flurry of effort (you might have noticed I&amp;#8217;ve been quiet lately) I&amp;#8217;m very pleased to say that I&amp;#8217;m done with the writing and am preparing the manuscript for production. See &lt;a href="http://www.pearsonhighered.com/educator/academic/product/1,3110,0132350882,00.html"&gt;The Prentice Hall Listing&lt;/a&gt;&lt;/p&gt;


	&lt;p&gt;&lt;img src="http://vig-fp.prenhall.com/bigcovers/0132350882.jpg" alt="" /&gt;&lt;/p&gt;


&lt;pre&gt;Table of Contents

Clean Code    1
    There Will Be Code    1
    Bad Code    2
    The Total Cost of Owning a Mess.    3
    Schools of Thought.    11
    We are Authors.    12
    The Boy Scout Rule    13
    Prequel and Principles    14
    Conclusion    14
    Bibliography    15
Meaningful Names by Tim Ottinger    17
    Introduction    17
    Use Intention-revealing Names    17
    Avoid Disinformation    19
    Make Meaningful Distinctions    20
    Use Pronounceable Names    21
    Use Searchable Names    22
    Avoid Encodings    23
    Avoid Mental Mapping    24
    Class Names    25
    Method Names    25
    Don't Be Cute    25
    Pick One Word Per Concept    26
    Don't Pun    26
    Use Solution Domain Names    27
    Use Problem Domain Names    27
    Add Meaningful Context    27
    Don't add Gratuitous Context    29
    Final Words ...    30
Functions    31
    Small!    34
    Do one thing.    35
    One level of abstraction per function.    36
    Switch Statements.    37
    Use descriptive names.    39
    Function Arguments.    39
    Have no side-effects.    43
    Command Query Separation    44
    Prefer exceptions to returning error codes.    45
    Don't Repeat Yourself.    47
    Structured Programming    48
    How do you write functions like this?    48
    Conclusion    49
    SetupTeardownIncluder    49
    Bibliography    52
Comments    53
    Comments do not make up for bad code.    55
    Explain yourself in code.    55
    Good Comments    55
    Bad Comments    59
    Example    71
    Bibliography    74
Formatting    75
    The Purpose of Formatting    76
    Vertical Formatting    76
    Horizontal Formatting    84
    Team Rules    89
    Uncle Bob's Formatting Rules.    90
Objects and Data Structures    93
    Data Abstraction    93
    Data/Object anti-symmetry.    95
    The Law of Demeter    97
    Data Transfer Objects    99
    Conclusion    101
    Bibliography    101
Error Handling by Michael Feathers    103
    Use Exceptions Rather than Return Codes    103
    Write Your Try-Catch-Finally Statement First    105
    Use Unchecked Exceptions    106
    Provide Context with Exceptions    107
    Define Exception Classes In Terms of a Caller's Needs.    107
    Define the Normal Flow    109
    Don't Return Null    110
    Don't Pass Null    111
    Conclusion    112
    Bibliography    112
Boundaries by James Grenning    113
    Bibliography    119
Unit Tests    121
    The Three Laws of TDD    122
    Keeping Tests Clean    123
    Clean Tests    124
    One Assert per Test    129
    F.I.R.S.T.    132
    Conclusion    132
    Bibliography    133
Classes    135
    Class Organization    135
    Classes should be Small!    136
    Organizing for Change    146
    Bibliography    150
Systems    By Dean Wampler 151
    How would you build a city?    151
    Separate constructing a system from using it    152
    Scaling Up    155
    Java Proxies    158
    Pure Java AOP Frameworks    160
    AspectJ Aspects    163
    Test-drive the system architecture    164
    Optimize decision making    165
    Use standards wisely, when they add demonstrable value    165
    Systems need Domain-Specific Languages    166
    Conclusion    166
    Bibliography    167
Emergence By Jeff Langr    169
    Getting Clean via Emergent Design    169
    Simple Design Rule 1: Runs all the tests    170
    Simple Design Rules 2-4: Refactoring    170
    No Duplication    170
    Expressive    173
    Minimal Classes and Methods    174
    Conclusion    174
    Bibliography    174
Concurrency    by Brett Schuchert 175
    Why Concurrency?    176
    Challenges    177
    Concurrency Defense Principles    178
    Know Your Library    180
    Know Your Execution Models    181
    Beware Dependencies between Syncrhonized Methods    182
    Keep Synchronized Sections Small    183
    Writing Correct Shut-Down Code is Hard    183
    Testing Threaded Code    184
    Conclusion    188
    Bibliography    189
Successive Refinement    191
    Args Implementation    192
    Args: the rough draft.    198
    String Arguments    212
     Conclusion    246
JUnit Internals    249
    Conclusion    262
Refactoring SerialDate    263
    Conclusion    280
    Bibliography    281
Smells and Heuristics    283
    Comments    283
    Environment    284
    Functions    285
    General    285
    Java    304
    Names    306
    Tests    310
    Conclusion    311
    Bibliography    312
Concurrency II    by Brett Schuchert 313
    Client/Server Example    313
    Possible Paths of Execution    317
    Knowing Your Library    322
    Dependencies between methods can break concurrent code    325
    Increasing Throughput    329
    Deadlock    331
    Testing Multi-Threaded Code    335
    Tool Support for Testing Thread-Based Code    337
    Conclusion    338
    Tutorial: Full Code Examples    339
org.jfree.date.SerialDate    345
Cross References of Heuristics    406
&lt;/pre&gt;</description>
      <pubDate>Tue, 08 Apr 2008 00:10:16 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:0280362f-4830-42b9-84db-edaa724b41b1</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2008/04/08/clean-code-whew</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Clean Code.  Whew!</title>
      <description>&lt;p&gt;I&amp;#8217;ve been working on this book for several years now.  After a flurry of effort (you might have noticed I&amp;#8217;ve been quiet lately) I&amp;#8217;m very pleased to say that I&amp;#8217;m done with the writing and am preparing the manuscript for production. See &lt;a href="http://www.pearsonhighered.com/educator/academic/product/1,3110,0132350882,00.html"&gt;The Prentice Hall Listing&lt;/a&gt;&lt;/p&gt;


	&lt;p&gt;&lt;img src="http://vig-fp.prenhall.com/bigcovers/0132350882.jpg" alt="" /&gt;&lt;/p&gt;


&lt;pre&gt;Table of Contents

Clean Code    1
    There Will Be Code    1
    Bad Code    2
    The Total Cost of Owning a Mess.    3
    Schools of Thought.    11
    We are Authors.    12
    The Boy Scout Rule    13
    Prequel and Principles    14
    Conclusion    14
    Bibliography    15
Meaningful Names by Tim Ottinger    17
    Introduction    17
    Use Intention-revealing Names    17
    Avoid Disinformation    19
    Make Meaningful Distinctions    20
    Use Pronounceable Names    21
    Use Searchable Names    22
    Avoid Encodings    23
    Avoid Mental Mapping    24
    Class Names    25
    Method Names    25
    Don't Be Cute    25
    Pick One Word Per Concept    26
    Don't Pun    26
    Use Solution Domain Names    27
    Use Problem Domain Names    27
    Add Meaningful Context    27
    Don't add Gratuitous Context    29
    Final Words ...    30
Functions    31
    Small!    34
    Do one thing.    35
    One level of abstraction per function.    36
    Switch Statements.    37
    Use descriptive names.    39
    Function Arguments.    39
    Have no side-effects.    43
    Command Query Separation    44
    Prefer exceptions to returning error codes.    45
    Don't Repeat Yourself.    47
    Structured Programming    48
    How do you write functions like this?    48
    Conclusion    49
    SetupTeardownIncluder    49
    Bibliography    52
Comments    53
    Comments do not make up for bad code.    55
    Explain yourself in code.    55
    Good Comments    55
    Bad Comments    59
    Example    71
    Bibliography    74
Formatting    75
    The Purpose of Formatting    76
    Vertical Formatting    76
    Horizontal Formatting    84
    Team Rules    89
    Uncle Bob's Formatting Rules.    90
Objects and Data Structures    93
    Data Abstraction    93
    Data/Object anti-symmetry.    95
    The Law of Demeter    97
    Data Transfer Objects    99
    Conclusion    101
    Bibliography    101
Error Handling by Michael Feathers    103
    Use Exceptions Rather than Return Codes    103
    Write Your Try-Catch-Finally Statement First    105
    Use Unchecked Exceptions    106
    Provide Context with Exceptions    107
    Define Exception Classes In Terms of a Caller's Needs.    107
    Define the Normal Flow    109
    Don't Return Null    110
    Don't Pass Null    111
    Conclusion    112
    Bibliography    112
Boundaries by James Grenning    113
    Bibliography    119
Unit Tests    121
    The Three Laws of TDD    122
    Keeping Tests Clean    123
    Clean Tests    124
    One Assert per Test    129
    F.I.R.S.T.    132
    Conclusion    132
    Bibliography    133
Classes    135
    Class Organization    135
    Classes should be Small!    136
    Organizing for Change    146
    Bibliography    150
Systems    By Dean Wampler 151
    How would you build a city?    151
    Separate constructing a system from using it    152
    Scaling Up    155
    Java Proxies    158
    Pure Java AOP Frameworks    160
    AspectJ Aspects    163
    Test-drive the system architecture    164
    Optimize decision making    165
    Use standards wisely, when they add demonstrable value    165
    Systems need Domain-Specific Languages    166
    Conclusion    166
    Bibliography    167
Emergence By Jeff Langr    169
    Getting Clean via Emergent Design    169
    Simple Design Rule 1: Runs all the tests    170
    Simple Design Rules 2-4: Refactoring    170
    No Duplication    170
    Expressive    173
    Minimal Classes and Methods    174
    Conclusion    174
    Bibliography    174
Concurrency    by Brett Schuchert 175
    Why Concurrency?    176
    Challenges    177
    Concurrency Defense Principles    178
    Know Your Library    180
    Know Your Execution Models    181
    Beware Dependencies between Syncrhonized Methods    182
    Keep Synchronized Sections Small    183
    Writing Correct Shut-Down Code is Hard    183
    Testing Threaded Code    184
    Conclusion    188
    Bibliography    189
Successive Refinement    191
    Args Implementation    192
    Args: the rough draft.    198
    String Arguments    212
     Conclusion    246
JUnit Internals    249
    Conclusion    262
Refactoring SerialDate    263
    Conclusion    280
    Bibliography    281
Smells and Heuristics    283
    Comments    283
    Environment    284
    Functions    285
    General    285
    Java    304
    Names    306
    Tests    310
    Conclusion    311
    Bibliography    312
Concurrency II    by Brett Schuchert 313
    Client/Server Example    313
    Possible Paths of Execution    317
    Knowing Your Library    322
    Dependencies between methods can break concurrent code    325
    Increasing Throughput    329
    Deadlock    331
    Testing Multi-Threaded Code    335
    Tool Support for Testing Thread-Based Code    337
    Conclusion    338
    Tutorial: Full Code Examples    339
org.jfree.date.SerialDate    345
Cross References of Heuristics    406
&lt;/pre&gt;</description>
      <pubDate>Tue, 08 Apr 2008 00:10:16 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:0280362f-4830-42b9-84db-edaa724b41b1</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2008/04/08/clean-code-whew</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Clean Code.  Whew!</title>
      <description>&lt;p&gt;I&amp;#8217;ve been working on this book for several years now.  After a flurry of effort (you might have noticed I&amp;#8217;ve been quiet lately) I&amp;#8217;m very pleased to say that I&amp;#8217;m done with the writing and am preparing the manuscript for production. See &lt;a href="http://www.pearsonhighered.com/educator/academic/product/1,3110,0132350882,00.html"&gt;The Prentice Hall Listing&lt;/a&gt;&lt;/p&gt;


	&lt;p&gt;&lt;img src="http://vig-fp.prenhall.com/bigcovers/0132350882.jpg" alt="" /&gt;&lt;/p&gt;


&lt;pre&gt;Table of Contents

Clean Code    1
    There Will Be Code    1
    Bad Code    2
    The Total Cost of Owning a Mess.    3
    Schools of Thought.    11
    We are Authors.    12
    The Boy Scout Rule    13
    Prequel and Principles    14
    Conclusion    14
    Bibliography    15
Meaningful Names by Tim Ottinger    17
    Introduction    17
    Use Intention-revealing Names    17
    Avoid Disinformation    19
    Make Meaningful Distinctions    20
    Use Pronounceable Names    21
    Use Searchable Names    22
    Avoid Encodings    23
    Avoid Mental Mapping    24
    Class Names    25
    Method Names    25
    Don't Be Cute    25
    Pick One Word Per Concept    26
    Don't Pun    26
    Use Solution Domain Names    27
    Use Problem Domain Names    27
    Add Meaningful Context    27
    Don't add Gratuitous Context    29
    Final Words ...    30
Functions    31
    Small!    34
    Do one thing.    35
    One level of abstraction per function.    36
    Switch Statements.    37
    Use descriptive names.    39
    Function Arguments.    39
    Have no side-effects.    43
    Command Query Separation    44
    Prefer exceptions to returning error codes.    45
    Don't Repeat Yourself.    47
    Structured Programming    48
    How do you write functions like this?    48
    Conclusion    49
    SetupTeardownIncluder    49
    Bibliography    52
Comments    53
    Comments do not make up for bad code.    55
    Explain yourself in code.    55
    Good Comments    55
    Bad Comments    59
    Example    71
    Bibliography    74
Formatting    75
    The Purpose of Formatting    76
    Vertical Formatting    76
    Horizontal Formatting    84
    Team Rules    89
    Uncle Bob's Formatting Rules.    90
Objects and Data Structures    93
    Data Abstraction    93
    Data/Object anti-symmetry.    95
    The Law of Demeter    97
    Data Transfer Objects    99
    Conclusion    101
    Bibliography    101
Error Handling by Michael Feathers    103
    Use Exceptions Rather than Return Codes    103
    Write Your Try-Catch-Finally Statement First    105
    Use Unchecked Exceptions    106
    Provide Context with Exceptions    107
    Define Exception Classes In Terms of a Caller's Needs.    107
    Define the Normal Flow    109
    Don't Return Null    110
    Don't Pass Null    111
    Conclusion    112
    Bibliography    112
Boundaries by James Grenning    113
    Bibliography    119
Unit Tests    121
    The Three Laws of TDD    122
    Keeping Tests Clean    123
    Clean Tests    124
    One Assert per Test    129
    F.I.R.S.T.    132
    Conclusion    132
    Bibliography    133
Classes    135
    Class Organization    135
    Classes should be Small!    136
    Organizing for Change    146
    Bibliography    150
Systems    By Dean Wampler 151
    How would you build a city?    151
    Separate constructing a system from using it    152
    Scaling Up    155
    Java Proxies    158
    Pure Java AOP Frameworks    160
    AspectJ Aspects    163
    Test-drive the system architecture    164
    Optimize decision making    165
    Use standards wisely, when they add demonstrable value    165
    Systems need Domain-Specific Languages    166
    Conclusion    166
    Bibliography    167
Emergence By Jeff Langr    169
    Getting Clean via Emergent Design    169
    Simple Design Rule 1: Runs all the tests    170
    Simple Design Rules 2-4: Refactoring    170
    No Duplication    170
    Expressive    173
    Minimal Classes and Methods    174
    Conclusion    174
    Bibliography    174
Concurrency    by Brett Schuchert 175
    Why Concurrency?    176
    Challenges    177
    Concurrency Defense Principles    178
    Know Your Library    180
    Know Your Execution Models    181
    Beware Dependencies between Syncrhonized Methods    182
    Keep Synchronized Sections Small    183
    Writing Correct Shut-Down Code is Hard    183
    Testing Threaded Code    184
    Conclusion    188
    Bibliography    189
Successive Refinement    191
    Args Implementation    192
    Args: the rough draft.    198
    String Arguments    212
     Conclusion    246
JUnit Internals    249
    Conclusion    262
Refactoring SerialDate    263
    Conclusion    280
    Bibliography    281
Smells and Heuristics    283
    Comments    283
    Environment    284
    Functions    285
    General    285
    Java    304
    Names    306
    Tests    310
    Conclusion    311
    Bibliography    312
Concurrency II    by Brett Schuchert 313
    Client/Server Example    313
    Possible Paths of Execution    317
    Knowing Your Library    322
    Dependencies between methods can break concurrent code    325
    Increasing Throughput    329
    Deadlock    331
    Testing Multi-Threaded Code    335
    Tool Support for Testing Thread-Based Code    337
    Conclusion    338
    Tutorial: Full Code Examples    339
org.jfree.date.SerialDate    345
Cross References of Heuristics    406
&lt;/pre&gt;</description>
      <pubDate>Tue, 08 Apr 2008 00:10:16 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:0280362f-4830-42b9-84db-edaa724b41b1</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2008/04/08/clean-code-whew</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Business software is Messy and Ugly.</title>
      <description>&lt;p&gt;I was at a client recently.  They are a successful startup who have gone through a huge growth spurt.  Their software grew rapidly, through a significant hack-and-slash program.  Now they have a mess, and it is slowing them way down.  Defects are high.  Unintended consequences of change are high.  Productivity is low.&lt;/p&gt;


	&lt;p&gt;I spent two days advising them how to adopt &lt;span class="caps"&gt;TDD&lt;/span&gt; and Clean Code techniques to improve their code-base and their situation.  We discussed strategies for gradual clean up, and the notion that big refactoring projects and big redesign projects have a high risk of failure.  We talked about ways to clean things up over time, while incrementally insinuating tests into the existing code base.&lt;/p&gt;


	&lt;p&gt;During the sessions they told me of a software manager who is famed for having said:&lt;/p&gt;


	&lt;blockquote&gt;
		&lt;p&gt;&amp;#8220;There&amp;#8217;s a clean way to do this, and a quick-and-dirty way to do this.  I want you to do it the quick-and-dirty way.&amp;#8221;&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;p&gt;The attitude engendered by this statement has spread throughout the company and has become a significant part of their culture.  If hack-and-slash is what management wants, then that&amp;#8217;s what they get!  I spent a long time with these folks countering that attitude and trying to engender an attitude of craftsmanship and professionalism.&lt;/p&gt;


	&lt;p&gt;The developers responded to my message with enthusiasm.  They &lt;em&gt;want&lt;/em&gt; to do a good job (of course!)  They just didn&amp;#8217;t know they were authorized to do good work.  They thought they had to make messes.  But I told them that the only way to get things done quickly, and keep getting things done quickly, is to create the cleanest code they can, to work as well as possible, and keep the quality very high.  I told them that quick-and-dirty is an oxymoron.  Dirty &lt;em&gt;always&lt;/em&gt; means slow.&lt;/p&gt;


	&lt;p&gt;On the last day of my visit the infamous manager (now the &lt;span class="caps"&gt;CTO&lt;/span&gt;) stopped into our conference room.  We talked over the issues.  He was constantly trying to find a quick way out.  He was manipulative and cajoling.  &amp;#8220;What if we did this?&amp;#8221; or &amp;#8220;What if we did that?&amp;#8221;  He&amp;#8217;d set up straw man after straw man, trying to convince his folks that there was a &lt;em&gt;time and place&lt;/em&gt; for good code, but this was not it.&lt;/p&gt;


	&lt;p&gt;I wanted to hit him.&lt;/p&gt;


	&lt;p&gt;Then he made the dumbest, most profoundly irresponsible statement I&amp;#8217;ve (all too often) heard come out of a CTOs mouth.  He said:&lt;/p&gt;


	&lt;blockquote&gt;
		&lt;p&gt;&amp;#8220;Business software is messy and ugly.&amp;#8221;&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;p&gt;&lt;em&gt;No, it&amp;#8217;s not!&lt;/em&gt;  The rules can be complicated, arbitrary, and ad-hoc; but the code does not need to be messy and ugly.  Indeed, the more arbitrary, complex, and ad-hoc the business rules are, the cleaner the code needs to be.  You cannot manage the mess of the rules if they are contained by another mess! The only way to get a handle on the messy rules is to express them in the cleanest and clearest code you can.&lt;/p&gt;


	&lt;p&gt;In the end, he backed down.  At least while I was there. But I have no doubt he&amp;#8217;ll continue his manipulations.  I hope the developers have the will to resist.&lt;/p&gt;


	&lt;p&gt;One of the developers asked the question point blank: &amp;#8220;What do you do when your managers tell you to make a mess?&amp;#8221;  I responded: &amp;#8220;You don&amp;#8217;t take it.  Behave like a doctor who&amp;#8217;s hospital administrator has just told him that hand-washing is too expensive, and he should stop doing it.&amp;#8221;&lt;/p&gt;</description>
      <pubDate>Thu, 13 Dec 2007 09:41:00 -0600</pubDate>
      <guid isPermaLink="false">urn:uuid:3184c0e9-cf3c-48f1-a801-cc8ed8720ab9</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2007/12/13/business-software-is-messy-and-mgly</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Active Record vs Objects</title>
      <description>&lt;p&gt;Active Record is a well known data persistence pattern.  It has been adopted by Rails, Hibernate, and many other &lt;span class="caps"&gt;ORM&lt;/span&gt; tools.  It has proven it&amp;#8217;s usefulness over and over again.  And yet I have a philosophical problem with it.&lt;/p&gt;


The Active Record pattern is a way to map database rows to objects.  For example, let&amp;#8217;s say we have an Employee object with name and address fields:
&lt;pre&gt;&lt;code&gt;public class Employee extends ActiveRecord {
  private String name;
  private String address;
  ...
} &lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;We should be able to fetch a given employee from the database by using a call like:&lt;/p&gt;


&lt;code&gt;Employee bob = Employee.findByName("Bob Martin");&lt;/code&gt;

	&lt;p&gt;We should also be able to modify that employee and save it as follows:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;bob.setName("Robert C. Martin");
bob.save();
&lt;/code&gt;&lt;/pre&gt;
In short, every column of the Employee table becomes a field of the Employee class.  There are static methods (or some magical reflection) on the ActiveRecord class that allow you to find instances.  There are also methods that provide &lt;span class="caps"&gt;CRUD&lt;/span&gt; functions.

	&lt;p&gt;Even shorter:  There is a 1:1 correspondence between tables and classes, columns and fields.  (Or very nearly so).&lt;/p&gt;


	&lt;p&gt;It is this 1:1 correspondence that bothers me.  Indeed, it bothers me about all &lt;span class="caps"&gt;ORM&lt;/span&gt; tools.  Why?  Because this mapping presumes that tables and objects are isomorphic.&lt;/p&gt;


	&lt;h2&gt;The Difference between Objects and Data Structures&lt;/h2&gt;


	&lt;p&gt;From the beginning of OO we learned that the data in an object should be hidden, and the public interface should be methods.  In other words: objects export behavior, not data.  An object has hidden data and exposed behavior.&lt;/p&gt;


	&lt;p&gt;Data structures, on the other hand, have exposed data, and no behavior.  In languages like C++ and C# the &lt;code&gt;struct&lt;/code&gt; keyword is used to describe a data structure with public fields.  If there are any methods, they are typically navigational.  They don&amp;#8217;t contain business rules.&lt;/p&gt;


	&lt;p&gt;Thus, data structures and objects are diametrically opposed.  They are virtual opposites.  One exposes behavior and hides data, the other exposes data and has no behavior.  But that&amp;#8217;s not the only thing that is opposite about them.&lt;/p&gt;


	&lt;p&gt;Algorithms that deal with objects have the luxury of not needing to know the kind of object they are dealing with.  The old example: &lt;code&gt;shape.draw();&lt;/code&gt; makes the point. The caller has no idea what kind of shape is being drawn.  Indeed, if I add new types of shapes, the algorithms that call &lt;code&gt;draw()&lt;/code&gt; are not aware of the change, and do not need to be rebuilt, retested, or redeployed.  In short, algorithms that employ objects are immune to the addition of new types.&lt;/p&gt;


	&lt;p&gt;By the same token, if I add new methods to the shape class, then all derivatives of shape must be modified.  So objects are &lt;em&gt;not&lt;/em&gt; immune to the addition of new functions.&lt;/p&gt;


Now consider an algorithm that uses a data structure.  
&lt;pre&gt;&lt;code&gt;
switch(s.type) {
  case SQUARE: Shape.drawSquare((Square)s); break;
  case CIRCLE: Shape.drawCircle((Circle)s); break;
}&lt;/code&gt;&lt;/pre&gt;
We usually sneer at code like this because it is not OO.  But that disparagement might be a bit over-confident.  Consider what happens if we add a new set of functions, such as &lt;code&gt;Shape.eraseXXX()&lt;/code&gt;.  None of the existing code is effected.  Indeed, it does not need to be recompiled, retested, or redeployed.  Algorithms that use data structures are immune to the addition of new functions.

	&lt;p&gt;By the same token if I add a new type of shape, I must find every algorithm and add the new shape to the corresponding switch statement.  So algorithms that employ data structures are &lt;em&gt;not&lt;/em&gt; immune to the addition of new types.&lt;/p&gt;


	&lt;p&gt;Again, note the almost diametrical opposition.  Objects and Data structures convey nearly opposite immunities and vulnerabilities.&lt;/p&gt;


	&lt;p&gt;Good designers uses this opposition to construct systems that are appropriately immune to the various forces that impinge upon them.  Those portions of the system that are likely to be subject to new types, should be oriented around objects.  On the other hand, any part of the system that is likely to need new functions ought to be oriented around data structures.  Indeed, much of good design is about how to mix and match the different vulnerabilities and immunities of the different styles.&lt;/p&gt;


	&lt;h2&gt;Active Record Confusion&lt;/h2&gt;


	&lt;p&gt;The problem I have with Active Record is that it creates confusion about these two very different styles of programming.  A database table is a data structure.  It has exposed data and no behavior.  But an Active Record appears to be an object.  It has &amp;#8220;hidden&amp;#8221; data, and exposed behavior.  I put the word &amp;#8220;hidden&amp;#8221; in quotes because the data is, in fact, not hidden.  Almost all ActiveRecord derivatives export the database columns through accessors and mutators.  Indeed, the Active Record is meant to be used like a data structure.&lt;/p&gt;


	&lt;p&gt;On the other hand, many people put business rule methods in their Active Record classes; which makes them appear to be objects.  This leads to a dilemma.  On which side of the line does the Active Record really fall?  Is it an object?  Or is it a data structure?&lt;/p&gt;


	&lt;p&gt;This dilemma is the basis for the oft-cited &lt;em&gt;impedance mismatch&lt;/em&gt; between relational databases and object oriented languages.  Tables are data structures, &lt;em&gt;not&lt;/em&gt; classes.  Objects are encapsulated behavior, &lt;em&gt;not&lt;/em&gt; database rows.&lt;/p&gt;


	&lt;p&gt;At this point you might be saying: &amp;#8220;So what Uncle Bob?  Active Record works great.  So what&amp;#8217;s the problem if I mix data structures and objects?&amp;#8221;  Good question.&lt;/p&gt;


	&lt;h2&gt;Missed Opportunity&lt;/h2&gt;


	&lt;p&gt;The problem is that Active Records &lt;em&gt;are&lt;/em&gt; data structures.  Putting business rule methods in them doesn&amp;#8217;t turn them into true objects.  In the end, the algorithms that employ Active Records are vulnerable to changes in schema, and changes in type.  They are not immune to changes in type, the way algorithms that use objects are.&lt;/p&gt;


	&lt;p&gt;You can prove this to yourself by realizing how difficult it is to implement an polymorphic hierarchy in a relational database.  It&amp;#8217;s not impossible of course, but every trick for doing it is a hack.  The end result is that few database schemae, and therefore few uses of Active Record, employ the kind of polymorphism that conveys the immunity of changes to type.&lt;/p&gt;


	&lt;p&gt;So applications built around ActiveRecord are applications built around data structures.  And applications that are built around data structures are &lt;em&gt;procedural&lt;/em&gt;&amp;#8212;they are not object oriented.  The opportunity we miss when we structure our applications around Active Record is the opportunity to use object oriented design.&lt;/p&gt;


	&lt;h2&gt;No, I haven&amp;#8217;t gone off the deep end.&lt;/h2&gt;


	&lt;p&gt;I am not recommending against the use of Active Record.  As I said in the first part of this blog I think the pattern is very useful.  What I &lt;em&gt;am&lt;/em&gt; advocating is a separation between the application and Active Record.&lt;/p&gt;


	&lt;p&gt;Active Record belongs in the layer that separates the database from the application.  It makes a very convenient halfway-house between the hard data structures of database tables, and the behavior exposing objects in the application.&lt;/p&gt;


	&lt;p&gt;Applications should be designed and structured around &lt;em&gt;objects&lt;/em&gt;, not data structures.  Those objects should expose business behaviors, and hide any vestige of the database.  The fact that we have Employee tables in the database, &lt;em&gt;does not&lt;/em&gt; mean that we must have Employee classes in the application proper.  We may have Active Records that hold Employee rows in the database interface layer, but by the time that information gets to the application, it may be in very different kinds of objects.&lt;/p&gt;


	&lt;h2&gt;Conclusion&lt;/h2&gt;


	&lt;p&gt;So, in the end, I am not against the use of Active Record.  I just don&amp;#8217;t want Active Record to be the organizing principle of the application.  It makes a fine transport mechanism between the database and the application; but I don&amp;#8217;t want the application knowing about Active Records.  I want the application oriented around objects that expose behavior and hide data.  I generally want the application immune to type changes; and I want to structure the application so that new features can be added by adding new types.  (See: &lt;a href="http://www.objectmentor.com/resources/articles/ocp.pdf"&gt;The Open Closed Principle&lt;/a&gt;)&lt;/p&gt;</description>
      <pubDate>Fri, 02 Nov 2007 11:29:31 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:e278f630-f65c-415b-bf56-73de1706db94</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2007/11/02/active-record-vs-objects</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Dynamic Languages</category>
      <category>Agile Methods</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Architecture is a Second Order Effect</title>
      <description>&lt;p&gt;We often argue that in order to achieve flexibility, maintainability, and reusability, it is important to have a good software architecture.  This is certainly true.  Without a well ordered architecture, software systems become masses of tangled modules and code.  However, the effect of architecture on the &amp;#8216;ilities is secondary to the effect that a good, fast, suite of tests has.&lt;/p&gt;


	&lt;p&gt;Why don&amp;#8217;t we clean our code?  When we see an ugly mass of code that we know is going to cause of problems, our first reaction is &amp;#8220;This needs to be cleaned up.&amp;#8221;  Our second reaction is: &amp;#8220;If I touch this code I&amp;#8217;ll be spending the next two weeks trying to get it to work again.&amp;#8221;  We don&amp;#8217;t clean code because we are afraid we&amp;#8217;ll break it.&lt;/p&gt;


	&lt;p&gt;In this way bad code hooks itself into our systems and refuses to go away.  Nothing stops clean code from going bad, but once it&amp;#8217;s bad, we seldom have the time, energy, or nerve to clean it.  In that sense, bad code is &lt;em&gt;permanent&lt;/em&gt;.&lt;/p&gt;


	&lt;p&gt;What if you had a button?  If you push this button a little light &lt;em&gt;instantly&lt;/em&gt; turns red or green.  Green means your system works.  Red means it&amp;#8217;s broken. If you had a button like this, you could make small changes to the system, and prove that they didn&amp;#8217;t break anything.  If you saw a batch of tangled messy code, you could &lt;em&gt;start&lt;/em&gt; to clean it.  You&amp;#8217;d simply make a tiny improvement and then push the button.  If the light was green you&amp;#8217;d make the next tiny change, and the next, and the next.&lt;/p&gt;


	&lt;p&gt;I have a button like that!  It&amp;#8217;s called a test suite.  I can run it any time I like, and within seconds it tells me, with very high certainty, that my system works.&lt;/p&gt;


	&lt;p&gt;Of course, to be effective, that test suite has to cover all the code in the system.  And, indeed, that&amp;#8217;s what I have.  My code coverage tools tell me that 89% of the 45,000 lines in my system are covered by my test suite.  (89% is pretty good number given that my coverage tool counts un-executable lines like interfaces.)&lt;/p&gt;


	&lt;p&gt;Can I be absolutely sure that the green light means that the system works?  Certainly not.  But given the coverage of my test suite, I am &lt;em&gt;reasonably&lt;/em&gt; sure that the changes I make are not introducing any bugs. And that reasonable surety is enough for me to be fearless about making changes.&lt;/p&gt;


	&lt;p&gt;This fearlessness is something that needs to be experienced to understand.  I feel no reluctance at all about cleaning up the code in my system.  I frequently take whole classes and restructure them.  I change the names of classes, variables, and functions on a whim.  I extract super-classes and derivatives any time I like.&lt;/p&gt;


	&lt;p&gt;In short, the test suite makes it easy to make changes to my code. It makes my code flexible and easy to maintain.&lt;/p&gt;


	&lt;p&gt;So does my architecture of course.  The design and structure of my system is very easy to deal with, and allows me to make changes without undue impact.  The reason my architecture is so friendly, is that I&amp;#8217;ve been fearless about changing it.  And that&amp;#8217;s because I have a test suite that runs in seconds, and that I trust!&lt;/p&gt;


	&lt;p&gt;So the clean architecture of my system is a &lt;em&gt;result&lt;/em&gt; of on-going efforts supported by the test suite.  I can keep the architecture clean and relevant because I have tests.  I can improve the architecture when I see a better approach because I have tests.  It is the tests that enable architectural improvement.&lt;/p&gt;


	&lt;p&gt;Yes, architecture enables flexibility, maintainability, and reusability; but test suites enable architecture.  Architecture is a second order effect.&lt;/p&gt;</description>
      <pubDate>Sat, 20 Oct 2007 01:58:29 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:2b06de7f-540e-411f-97e4-c77a040f3b4a</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2007/10/20/architecture-is-a-second-order-effect</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Clean Code</category>
    </item>
  </channel>
</rss>

