Factories, Builders and Fluent Interfaces

Last week I started working on very short proof of concept with a team that I am currently coaching at a short term insurance company.  We hit a very common design decision: when do we use a factory pattern and when do we use a builder pattern.
In the problem at hand, we needed to describe an item that will appear in an insurance policy that must be covered for fire damage.  It turns out that these items are not trivial in their structure, and many things influence the premium that will paid by the policy holder for fire insurance.  So, the first bit of code (in Java) in the test looked something like this.

FireItem fireItem = new FireItem();
fireItem.setIndustry("Building Construction");
fireItem.setOccupationCode("Workshop");
// the postal/zip code for the location of the insured item
fireItem.setAreaCode(7800);
// ignore the number, we actually created a Money class
fireItem.setSumInsured(200000.00);
fireItem.setRoofing("Non-Standard");

 

After the test passed, we refactored and I sneaked in a factory method which will be used to honor default values and at the same time threw in a fluent interface (the term coined by Eric Evans and Martin Fowler.  After all, I was also quietly introducing Domain Driven Design without actually saying that).

The code looked like this.

FireItem fireItem = FireItem.create()
                      .inIndustry("Building Construction")
                      .withOccupation("Workshop")
                      .InAreaWithPostalCode(7800)
                      .forSumInsured(200000.00)
                      .havingRoofing("Non-Standard");

The FireItem class looked like this:

public class FireItem {
    String industry;
    String occupation;
    // other properties ...

   private FireItem() { }
   public static FireItem create() {
       return new FireItem();
   }
   public FireItem inIndustry(String industry) {
      this.industry = industry;
      return this;
   }
   // other chained methods follow a similar style returning "this" ...
}

Nice! Much more readable. But, we then realised that it’s easy for someone to miss one of the methods in the chain.  That will result in the item having an incomplete structure.  Not good!  

One of the things I tend to do as a coach, is to let the team I am working with, experience the problem, solution and any rewards and smells as well.  Sometimes I even throw in red herring for sake of experience ;-).  So, the third pass at refactoring was to introduce a validate() method on the item which throws an exception if everything was not in place.

try {
  FireItem fireItem = FireItem.create()
                       .inIndustry("Building Construction")
                       .withOccupation("Workshop")
                       .InAreaWithPostalCode(7800)
                       .forSumInsured(200000.00)
                       .havingRoofing("Non-Standard")
                       .validate();
} catch (FireItemException e) {
  // handle the exception
}

Now the user of this class needs to know that the validate() method must be called before they really want to use an item object.  Yuck, that’s smelly!  So, for the fourth design refactoring, I introduced a builder and moved the fluent interface to the builder, still using method chaining but introduced a build() method that did the work of the previous validate() method before returning the well structured item.  The FireItem class now needs the traditional bunch of getters and setters (rant – the framework goodies need them anyway!!)

import static insurance.FireItemBuilder.fireItem;
// ...
try {
  FireItem fireItem = fireItem().inIndustry("Building Construction")
                         .withOccupation("Workshop")
                         .InAreaWithPostalCode(7800)
                         .forSumInsured(200000)
                         .havingRoofing("Non-Standard")
                         .build();
} catch (FireItemException e) {
   // handle the exception
}

Much better!  Note the use of the static import which gives us the liberty to use the static method without specifying the class in code body.  The FireItemBuilder class looked like this.

public class FireItemBuilder {
   private final FireItem fireItem;
   private FireItemBuilder() { 
      fireItem = new FireItem();
   }
   public static FireItemBuilder fireItem() {
       return new FireItemBuilder();
   }
   public FireItemBuilder inIndustry(String industry) {
      fireItem.setIndustry(industry);
      return this;
   }
   // other chained methods follow a similar style returning "this" ...
   public FireItem build() throws FireItemBuilderException {
      validate();
      return fireItem;
   }
   private void validate() throws FireItemBuilderException {
     // do all validations on the fire item itself and throw an exception if something fails
   }
}

Sure, we can improve the bubbling of the exception from validate() to build() and we could do with a better name for validate().  And perhaps, validate() should be on the FireItem class.  But let’s stick to factories and builders and fluent interfaces.  I think these three things work nicely “together”, when used for the right purpose.

In a nutshell, factories are great for creating objects where defaults and invariants are easily honored during the simple call to the factory.  However, if the structure of the object is more complex which makes long argument lists ugly, and some form of validation is necessary  before we can use an object then a builder works beautifully.

Also, note that the fluent interface was used to improve readability and kick off a tiny little DSL for describing insurance items.

An alternative is to allow the object to have an invalid structure but you track it with an invalid state, perhaps using a state pattern.  This is not exactly what the state pattern was meant for, but it will work nonetheless.

The last time I was with this team was in August 2006, and it is really great to work with them again.  So, much more for me to learn from them.

Introduction to BDD

I will be giving a short introduction to behavior driven development (BDD) at the XP forum on 13 August 2008.  As usual, I’m using the opportunity to subtly throw in some other practices such as coding for readability and designing good messages.  I will also touch on mocking in tests as well.

I’ve been having immense fun putting together some code examples for this talk and I hope to demo BDD using JUnitJBehaveRSpec (using the rbehave story runner on JRuby to test Java) and JTestR (which looks like a really exciting little project).

Come along and enjoy the fun.  Details and registration is on the JCSE web site.

Update 1: The Source Code for BDD Presentation is now available.

Update 2: The presentation is now available for download here.  It’s a 5MB Quicktime movie file. It’s not a continuous play movie, so you need to click through to the next slide.

Testing is just a laborious pain in the rear

I thoroughly enjoyed Karen Greave’s talk on Agile Testing.  She had just about 100% coverage (pun intended, groan).  Yet, testing is really a pain in the rear.  Testing is execution, and Karen was dead-on right, that automation is the path to follow.  Computers are very good at testing.  A computer does what it is programmed to do, and it can test the way it was programmed to test.  It’s simple: if testing is your constraint, move that constraint away from testing by automating.

Now, you have to deal with the constraint that shifted to the next point: test authoring.  While testing (i.e. execution) is just a passive, laborious effort, test authoring is a very creative, active exercise.  It is actually an exercise in confirming a shared, common understanding.  Kristin Nygard said “To program is to understand” and test authoring is a programming exercise.  That’s why outside-in, behavior driven development style scenarios are actually tests, coded in a human language.  The act of authoring a scenario proves your understanding and the expected working of the software.

This is why I separate test execution (passive) from test authoring (active).  And Karen said that early feedback is good (right again), which is why I author my tests very early.  I’m extreme about this.  I test first.

Two Angles to Sustainable Pace

At the Scrum User Group South Africa meeting last night Marius de Beer did a really good talk about Software Development Practices.  It’s been a long while since I saw anyone attempt to draw so much from such widely spread corners of wisdom.  In one slide Marius mentioned the practice of Sustainable Pace.  Many take the view that this is about cutting back on working overtime and that it supports the principles of energised work, and work-life balance.  Marius did make the same point, and it is correct.
But there is another angle to Sustainable Pace.  As a developer, you need to build a rhythm, or flow.  It’s a cadence that you establish as you are writing code.  It’s a cadence that TDD helps you establish itself.  This cadence is also sustainable pace.  And one thing that kills this cadence and your pace in a flash is a mid-stream meeting.

In the panel discussion afterwards, there was a question at the end regarding ways to reduce the number of meetings which I just glossed over.  If you schedule meetings with developers for only the first hour in the morning, you not only reduce the number of meetings but, also, you don’t destroy the sustainable pace built up from the morning.

So, don’t think about pace as just working 7 hours a day, it’s about what you do in the 7 hours that matters.  Get the rhythm going and be anal about things that can kill your flow mid-stream; especially meetings.