Use the Builder pattern to abstract code that performs a routine construction task, such as composing HTML or text for an email.
I've always found that code that constructs something is some of the most elegant code in a system. I suppose that's just because I spent a year writing a book on code generation, which is all about constructing code.
By the way, the book is Code Generation in Action (Manning). It_s still available and makes an excellent holiday gift for friends and family.
An example of construction code is the code that reads an XML document off the disk and constructs an in-memory representation of that structure. Another is a module of code that constructs an email message to tell a customer she is behind on her payments.
It's the late-payment mail that I want to focus on in this hack; but I'm going to do it with a twist. I'm going to use the Builder pattern so that the same code that creates a message in HTML can also create a message in XHTML or text format.
I'm going to have the code that writes the past-due notice use a
builder instead of just creating the string directly. This builder
object will have a set of methods, as shown in Figure 7-4. The
endBody() methods wrap the creation of the
addText() method adds some text, and the
addBreak() method adds a line break.
Figure 7-4. The ...