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.

8th Aug, 2008

Øredev 2008

I’ve mentioned it in bits and pieces before but now that the nice folk at Oredev have more or less finalised their program, I can put the down the talks I will be giving in November 2008.

I certainly did not expect to be doing 4 sessions!  It’s going to be a busy conference but also immense fun.  I hope that I get the time to attend the other talks and learn from some amazing people.  I certainly will be catching up with old friends as well

30th Jul, 2008

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.

Fortunately, there is always a balance in the universe. The people that balance out the power oriented architects are some of the true leaders in society, past and present. These are the people that live a value system intrinsically and that just becomes pervasive in the teams or groups with whom they work. They lead and they coach, they teach and are taught. After all, building software is a social exercise more than a technical exercise.

Here are some people that I think would have been fantastic agile coaches (in no particular order).

  • Mahatma Ghandi stopped ethnic violence between Hindus and Muslims by believing in the equality of everyone. There is one quote of his that stays with me when designing software: “The only solution is that which is just for everyone”. Ok, I may have got the exact wording wrong, but you know what I mean.
  • Bruce Lee was a man that sought perfection through serious introspection. He found meaning through the martial arts and when he found it, he realized it was not about the power but the subtleties of understanding yourself.  Again, something from Bruce Lee that helps me find build simpler solutions: “In building a statue, a sculptor doesn’t keep adding clay to his subject. Actually, he keeps chiselling away at the unessentials until the truth of its creation is revealed without obstructions”
  • Nelson Mandela forgave those that incarcerated him, completely and selflessly. And in doing that, he taught 45 million people that change is possible. He has an amazing ability to make everyone feel at ease with his humility. There is no private face nor public face. There is just him. So, for the toughest bits in every design, I turn to this great man: “It always seems impossible until its done.

Happy 90th Birthday, Madiba!

I just wish you could code as well as you coach :-)

I have been working on a project for the last 2 years.  It’s been 2 long years.  Those of you that know me personally will know the client.  The project has been technically challenging in the rather abstract domain of data and metadata.  Fascinating stuff, incredibly fun, bordering on pure research in a commercial environment.  We also committed to being agile in this project … with the client being agile, development being agile, project management being agile, everything agile.  It could not have been a better beginning.

It has been a spectacular mess!  It is a textbook on agile gone wrong.  It is a textbook on architecture gone wrong. It is a textbook on how not to write good code.  There are many lessons to be learnt and that has been the most valuable outcome of this project.  I will be speaking on some of these agile lessons at Oredev in November this year.  For now, I just want to reflect on one single thing that popped into my head during dinner with Chris Naidoo from Psybergate last night.

Here goes!  The project has failed because of power brokering.  Too many people are fighting for power.  Power gives control and control gives more power.  The fundamental value system of the entire team (client included) has been compromised because of the desire for power and control.

The net result is personal conflict.  Personal conflict is not healthy.  Conflict in driving at solving a problem is healthy.  If there is battle for power, there is always personal conflict because politicking will happen. Teams get fractured in power alliances and off-line caucusing occurs.  Egos are reinforced and confidences are destroyed.  One person posturing superior than the other, forever trying to be top dog for the sake of being top dog.  There is never a winner in a power battle and everyone loses.

At an architecture level, as designs emerged, they were shot down like moving tin ducks at a carnival game.  The power player won and the architecture and design that went into production was that of the person that had power at the time.  It was not the team’s architecture.  So there was not sense of responsibility in the team that resulted in no pride in work delivered.  Sensible and rational thinking is lost when a leader is blinded by power and the team exists without purpose.

So we had a power oriented architecture.  We also had a power oriented methodology.  And a power oriented value system.  And power oriented development.  I am not innocent.  I did my own bit of power grabbing as well.  I destroyed myself and violated my value system … a bit.  I did realise that if I stopped fighting against power, there will be no fight for power.

I have only 3 people from the original team, me included.  One of the power brokers has moved on to a position of greater power but has less direct influence on the team.  There is a new power player in the wings.  The team is fresh, new, no power battle scars.  So we won’t fight the battle.  Too many lives have been lost.  This is not Ghandi’s passive resistance.  To resist, even passively, is to take a position in the battle.  Instead, we will resort to a value system that treats people equally, responsibly and give each person the dignity they deserve.  I wish could give that dignity back to those that have left, fallen in battle.  You know who you are.  I wish I could have done more.

Architecturally, we have resurrected one of the tin ducks that was shot down about 18 months ago.  Not by me, but by someone else who came to the same solution independently.  But it’s not a “I told you so” situation … that will start the power battles again.  So BDUF has returned, TDD has returned.  The agile practices that we cherish and shout out will be implemented again, through natural and progressive adoption, each person adopting agile practices at their own pace, guided by a value system shared by all.

Power oriented architectures and power based management does not work.  Agile embraces a simple philosophy:  think about the next person before you think about yourself.  Agile is not about loss or gain of control, it is about collective ownership.  Once you grok that and live that, then it does not matter how bad your architecture is, how unreadable your code is, or how late your are on the project. It is simple: because the team is still equally responsible for everything, moving forward out of the mess, in small steps is do-able.  There is no blame because there is no power battle.

This project has changed me to be a worse person and it has changed me to be a better person.  I hope the others on the project have the same carthatic realisation that I had with Chris Naidoo.  Chris just didn’t know that happened during our conversation.  Now he knows.

By the way, I now realised that there are many power oriented architects in many teams that I have worked with in the past.  I just did not know that it was always a power issue.  Drop me note if you have come across any power oriented architects that create power oriented architectures.

Categories