Tags: Expression builder
Inspiration: Martin Fowler
One of the problems with a FluentInterface is that it results in some odd looking methods. Consider this example:
customer.newOrder()
.with(6, "TAL")
.with(5, "HPK").skippable()
.with(3, "LGV")
.priorityRush();
Methods like with, skippable, and priorityRush don't sit well on the Order class. The naming works well in the context of the little DomainSpecificLanguage that the fluent interface provides, but we usually expect methods to make sense in their own right.
An Expression Builder is a solution to this problem. An expression builder is a separate object on which we define the fluent interface that then translates the fluent calls to the underlying regular API calls. So an expression builder for the order case would look something like this.
public class OrderBuilder {
private Order subject = new Order();
private OrderLine currentLine;
public OrderBuilder with(int quantity, String productCode) {
currentLine = new OrderLine(quantity, Product.find(productCode));
subject.addLine(currentLine);
return this;
}
public OrderBuilder skippable() {
currentLine.setSkippable(true);
return this;
}
public OrderBuilder priorityRush() {
subject.setRush(true);
return this;
}
public Order getSubject() {
return subject;
}
}
Last published: Thursday 26th January 2012
<<Previous Next>>