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.
Thanks, the builder works nice.
I like the simplicity and elegance of this approach – also, I think u presented in a nice and easy understanding way. I guess fluent interfaces encourages us to get rid of setters, and mutate an object in more OO manner.
My question is:
1. After the controlled build process, you are handing out an object reference to the FireItem object. This can then still be mutated independently of the builder, and as such, we risk invalidating the object again. Any ideas on how we get around this?
Hi, I found your blog on this new directory of WordPress Blogs at blackhatbootcamp.com/listofwordpressblogs. I dont know how your blog came up, must have been a typo, i duno. Anyways, I just clicked it and here I am. Your blog looks good. Have a nice day. James.
[…] feels more elegant. As a case in point about complexity, there’s an excellent example of fluent interface implementation in Java for an insurance application. Of course, this means I’m now going to explore the Builder […]