While every object-oriented system creates objects or object structures, the creation code is not always free of duplication, simple, intuitive, or as loosely coupled to client code as it could be. The six refactorings in this chapter target design problems in everything from constructors to overly complicated construction logic to unnecessary Singletons [ DP ]. While these refactorings don’t address every creational design problem you’ll likely encounter, they do address some of the most common problems.
If there are too many constructors on a class, clients will have a difficult time knowing which constructor to call. One solution is to reduce the number of constructors by applying such refactorings as Extract Class [ F ] or Extract Subclass [ F ]. If that isn’t possible or useful, you can clarify the intention of the constructors by applying Replace Constructors with Creation Methods (57) .
What is a Creation Method? It is simply a static or nonstatic method that creates and returns an object instance. For this book, I decided to define the Creation Method pattern to help distinguish it from the Factory Method [ DP ] pattern. A Factory Method is useful for polymorphic creation. Unlike a Creation Method, a Factory Method may not be static and must be implemented by at least two classes, typically a superclass and a subclass. If classes in a hierarchy implement a method similarly, except for an object creation step, you can likely remove duplicate code by first applying Introduce Polymorphic Creation with Factory Method (88) .
A class that is a Factory is one that implements one or more Creation Methods. If data and/or code used in object creation become sprawled across numerous classes, you’ll likely find yourself frequently updating code in numerous places, a sure sign of the smell Solution Sprawl (43) . Applying Move Creation Knowledge to Factory (68) will reduce creational sprawl by consolidating creation code and data under a single Factory.
Encapsulate Classes with Factory (80) is another useful refactoring that involves the Factory pattern. The two most common motivations for applying this refactoring are (1) to ensure that clients communicate with instances of classes via a common interface and (2) to reduce client knowledge of classes while making instances of the classes accessible via a Factory.
To simplify the construction of an object structure, there is no better pattern than Builder [ DP ]. Encapsulate Composite with Builder (96) shows how a Builder can provide a simpler, less error-prone way to construct a Composite [ DP ].
The final refactoring in this section is Inline Singleton (114) . It was a joy to write this refactoring, for I often encounter Singletons that do not need to exist. This refactoring, which shows you how to remove a Singleton from your code, features advice about Singletons from Ward Cunningham, Kent Beck, and Martin Fowler.
Replace Constructors with Creation Methods
Constructors on a class make it hard to decide which
constructor to call during development.
Replace the constructors with intention-revealing
Creation Methods that return object instances.
Motivation
Some languages allow you to name constructors any way you like, regardless of the name of the class. Other languages, such as Java and C++, don’t allow this; each constructor must be named after its class. If you have one simple constructor, this may not be a problem. On the other hand, if you have multiple constructors, programmers will have to choose which constructor to call by studying the expected parameters and/or poking around at the constructor code. What’s wrong with that? A lot.
Constructors simply don’t communicate intention efficiently or effectively. The more constructors you have, the easier it is for programmers to choose the wrong one. Having to choose which constructor to call slows down development, and the code that does call one of the many constructors often fails to sufficiently communicate the nature of the object being constructed.
If you need to add a new constructor to a class with the same signature as an existing constructor, you’re out of luck. Because they have to share the same name, you can’t add the new constructor—since it isn’t possible to have two constructors with the same signature in the same class, despite the fact that they would create different kinds of objects.
It’s common, particularly on mature systems, to find numerous constructors that are no longer being used yet continue to live on in the code. Why are these dead constructors still present? Most of the time it’s because programmers don’t know that the constructors have no caller. Either they haven’t checked for callers (perhaps because the search expression they’d need to formulate is too complicated) or they aren’t using a development environment that automatically highlights uncalled code. Whatever the reason, dead constructors only bloat a class and make it more complicated than it needs to be.
A Creation Method can help make these problems go away. A Creation Method is simply a static or nonstatic method on a class that instantiates new instances of the class. There are no name constraints on Creation Methods, so you can name them to clearly express what you are creating (e.g., createTermLoan() or createRevolver() ). This naming flexibility means that two differently named Creation Methods can accept the same number and type of arguments. And for programmers who lack modern development environments, it’s usually easier to find dead Creation Method code than it is to find dead constructor code because the search expressions on specifically named methods are easier to formulate than the search expressions on one of a group of constructors.
One liability of this refactoring is that it may introduce a nonstandard way to perform creation. If most of your classes are instantiated using new yet some are instantiated using a Creation Method, programmers will have to learn how creation gets done for each class. However, this nonstandard technique for creation may be a lesser evil than having classes with too many constructors.
After you have identified a class that has many constructors, it’s best to consider applying Extract Class [ F ] or Extract Subclass [ F ] before you decide to apply this refactoring. Extract Class is a good choice if the class in question is simply doing too much work (i.e., it has too many responsibilities). Extract Subclass is a good choice if instances of the class use only a small portion of the class’s instance variables.
Creation Methods and Factory Methods
What does our industry call a method that creates objects? Many programmers would answer “Factory Method,” after the name given to a creational pattern in Design Patterns [ DP ]. But are all methods that create objects true Factory Methods? Given a broad definition of the term (i.e., a method that simply creates objects), the answer would be an emphatic “yes!” But given the way the authors of the Factory Method pattern wrote it in 1995, it’s clear that not every method that creates objects offers the kind of loose coupling provided by a genuine Factory Method (e.g., see Introduce Polymorphic Creation with Factory Method , 88).
To help us be clear when discussing designs or refactorings related to object creation, I’m using the term Creation Method to refer to a static or nonstatic method that creates instances of a class. This means that every Factory Method is a Creation Method but not necessarily the reverse. It also means that you can substitute the term Creation Method wherever Martin Fowler uses the term “factory method” in Refactoring [ F ] and wherever Joshua Bloch uses the term “static factory method” in Effective Java [ Bloch ].
Benefits and Liabilities
+ Communicates what kinds of instances are available better than constructors.
+ Bypasses constructor limitations, such as the inability to have two constructors with the same number and type of arguments.
+ Makes it easier to find unused creation code.
– Makes creation nonstandard: some classes are instantiated using new, while others use Creation Methods .
Mechanics
Before beginning this refactoring, identify the catch-all constructor , a full-featured constructor to which other constructors delegate their work. If you don’t have a catch-all constructor, create one by applying Chain Constructors (340) .
1. Find a client that calls a class’s constructor in order to create a kind of instance. Apply Extract Method [ F ] on the constructor call to produce a public, static method. This new method is a creation method . Now apply Move Method [ F ] to move the creation method to the class containing the chosen constructor.
Compile and test.
2. Find all callers of the chosen constructor that instantiate the same kind of instance as the creation method and update them to call the creation method.
Compile and test.
3. If the chosen constructor is chained to another constructor, make the creation method call the chained constructor instead of the chosen constructor. You can do this by inlining the constructor, a refactoring that resembles Inline Method [ F ].
Compile and test.
4. Repeat steps 1–3 for every constructor on the class that you’d like to turn into a Creation Method.
5. If a constructor on the class has no callers outside the class, make it non-public.
Compile.
Example
This example is inspired from the banking domain and a certain loan risk calculator I spent several years writing, extending, and maintaining. The Loan class had numerous constructors, as shown in the following code.
public class Loan...
public Loan(double commitment, int riskRating, Date maturity) {
this(commitment, 0.00, riskRating, maturity, null);
}
public Loan(double commitment, int riskRating, Date maturity, Date expiry) {
this(commitment, 0.00, riskRating, maturity, expiry);
}
public Loan(double commitment, double outstanding,
int riskRating, Date maturity, Date expiry) {
this(null, commitment, outstanding, riskRating, maturity, expiry);
}
public Loan(CapitalStrategy capitalStrategy, double commitment,
int riskRating, Date maturity, Date expiry) {
this(capitalStrategy, commitment, 0.00, riskRating, maturity, expiry);
}
public Loan(CapitalStrategy capitalStrategy, double commitment,
double outstanding, int riskRating,
Date maturity, Date expiry) {
this.commitment = commitment;
this.outstanding = outstanding;
this.riskRating = riskRating;
this.maturity = maturity;
this.expiry = expiry;
this.capitalStrategy = capitalStrategy;
if (capitalStrategy == null) {
if (expiry == null)
this.capitalStrategy = new CapitalStrategyTermLoan();
else if (maturity == null)
this.capitalStrategy = new CapitalStrategyRevolver();
else
this.capitalStrategy = new CapitalStrategyRCTL();
}
}
Loan could be used to represent seven kinds of loans. I will discuss only three of them here. A term loan is a loan that must be fully paid by its maturity date. A revolver, which is like a credit card, is a loan that signifies “revolving credit”: you have a spending limit and an expiry date. A revolving credit term loan ( RCTL ) is a revolver that transforms into a term loan when the revolver expires.
Given that the calculator supported seven kinds of loans, you might wonder why Loan wasn’t an abstract superclass with a subclass for each kind of loan. After all, that would have cut down on the number of constructors needed for Loan and its subclasses. There were two reasons why this was not a good idea.
1. What distinguishes the different kinds of loans is not so much their fields but how numbers, like capital, income, and duration, are calculated. To support three different ways to calculate capital for a term loan, we wouldn’t want to create three different subclasses of Loan . It’s easier to support one Loan class and have three different Strategy classes for a term loan (see the example from Replace Conditional Logic with Strategy , 129 ).
2. The application that used Loan instances needed to transform loans from one kind of loan to another. This transformation was easier to do when it involved changing a few fields on a single Loan instance, rather than completely changing one instance of a Loan subclass into another.
If you look at the Loan source code presented earlier, you’ll see that it has five constructors, the last of which is its catch-all constructor (see Chain Constructors , 340 ). Without specialized knowledge, it is difficult to know which constructors create term loans, which ones create revolvers, and which ones create RCTLs.
I happen to know that an RCTL needs both an expiry date and a maturity date, so I know that to create an RCTL , I must call a constructor that lets me pass in both dates. Did you know that? Do you think the next programmer who reads this code will know it?
What else is embedded as implicit knowledge in the Loan constructors? Plenty. If you call the first constructor, which takes three parameters, you’ll get back a term loan. But if you want a revolver, you’ll need to call one of the constructors that take two dates and then supply null for the maturity date. I wonder if all users of this code will know this? Or will they just have to learn by encountering some ugly defects?
Let’s see what happens when I apply the Replace Constructors with Creation Methods refactoring.
1. My first step is to find a client that calls one of Loan ’s constructors. Here is one such caller that resides in a test case:
public class CapitalCalculationTests...
public void testTermLoanNoPayments() {
...
Loan termLoan = new Loan(commitment, riskRating, maturity);
...
}
In this case, a call to the above Loan constructor produces a term loan. I apply Extract Method [ F ] on that call to produce a public, static method called createTermLoan :
public class CapitalCalculationTests...
public void testTermLoanNoPayments() {
...
Loan termLoan = createTermLoan(commitment, riskRating, maturity) ;
...
}
public static Loan createTermLoan(double commitment, int riskRating, Date maturity) {
return new Loan(commitment, riskRating, maturity);
}
Next, I apply Move Method [ F ] on the creation method, createTermLoan , to move it to Loan . This produces the following changes:
public class Loan...
public static Loan createTermLoan(double commitment, int riskRating, Date maturity) {
return new Loan(commitment, riskRating, maturity);
}
public class CapitalCalculationTest...
public void testTermLoanNoPayments() {
...
Loan termLoan = Loan. createTermLoan(commitment, riskRating, maturity);
...
}
I compile and test to confirm that everything works.
2. Next, I find all callers on the constructor that createTermLoan calls, and I update them to call createTermLoan . For example:
public class CapitalCalculationTest...
public void testTermLoanOnePayment() {
...
Loan termLoan = new Loan(commitment, riskRating, maturity);
Loan termLoan = Loan.createTermLoan(commitment, riskRating, maturity);
...
}
Once again, I compile and test to confirm that everything is working.
3. The createTermLoan method is now the only caller on the constructor. Because this constructor is chained to another constructor, I can remove it by applying Inline Method [ F ] (which, in this case, is actually “inline constructor”). This leads to the following changes:
public class Loan...
public Loan(double commitment, int riskRating, Date maturity) {
this(commitment, 0.00, riskRating, maturity, null);
}
public static Loan createTermLoan(double commitment, int riskRating, Date maturity) {
return new Loan(commitment, 0.00, riskRating, maturity, null);
}
I compile and test to confirm that the change works.
4. Now I repeat steps 1–3 to produce additional creation methods on Loan . For example, here is some code that calls Loan ’s catch-all constructor:
public class CapitalCalculationTest...
public void testTermLoanWithRiskAdjustedCapitalStrategy() {
...
Loan termLoan = new Loan(riskAdjustedCapitalStrategy, commitment,
outstanding, riskRating, maturity, null);
...
}
Notice the null value that is passed in as the last parameter to the constructor. Passing in null values to a constructor is bad practice. It reduces the code’s readability. It usually happens because programmers can’t find the exact constructor they need, so instead of creating yet another constructor they call a more general-purpose one.
To refactor this code to use a creation method, I’ll follow steps 1 and 2. Step 1 leads to another createTermLoan method on Loan :
public class CapitalCalculationTest...
public void testTermLoanWithRiskAdjustedCapitalStrategy() {
...
Loan termLoan = Loan.createTermLoan (riskAdjustedCapitalStrategy, commitment,
outstanding, riskRating, maturity , null );
...
}
public class Loan...
public static Loan createTermLoan(double commitment, int riskRating, Date maturity) {
return new Loan(commitment, 0.00, riskRating, maturity, null);
}
public static Loan createTermLoan(CapitalStrategy riskAdjustedCapitalStrategy,
double commitment, double outstanding, int riskRating, Date maturity) {
return new Loan(riskAdjustedCapitalStrategy, commitment,
outstanding, riskRating, maturity, null);
}
Why did I choose to overload createTermLoan(…) instead of producing a creation method with a unique name, like createTermLoanWithStrategy(…) ? Because I felt that the presence of the CapitalStrategy parameter sufficiently communicated the difference between the two overloaded versions of createTermLoan(…) .
Now for step 2 of the refactoring. Because the new createTermLoan(…) calls Loan ’s catch-all constructor, I must find other clients that call the catch-all constructor to instantiate the same kind of Loan produced by createTermLoan(…) . This requires careful work because some callers of the catch-all constructor produce revolver or RCTL instances of Loan . So I update only the client code that produces term loan instances of Loan .
I don’t have to perform any work for step 3 because the catch-all constructor isn’t chained to any other constructors. I continue to implement step 4, which involves repeating steps 1–3. When I’m done, I end up with the following creation methods:
5. The last step is to change the visibility of the only remaining public constructor, which happens to be Loan ’s catch-all constructor. Since it has no subclasses and it now has no external callers, I make it private:
public class Loan...
private Loan(CapitalStrategy capitalStrategy, double commitment,
double outstanding, int riskRating,
Date maturity, Date expiry)...
I compile to confirm that everything still works. The refactoring is complete.
It’s now clear how to obtain different kinds of Loan instances. The ambiguities have been revealed and the implicit knowledge has been made explicit. What’s left to do? Well, because the creation methods take a fairly large number of parameters, it may make sense to apply Introduce Parameter Object [ F ].
Variations
Parameterized Creation Methods
As you consider implementing Replace Constructors with Creation Methods , you may calculate in your head that you’d need something on the order of 50 Creation Methods to account for every object configuration supported by your class. Writing 50 methods doesn’t sound like much fun, so you may decide not to apply this refactoring. Keep in mind that there are other ways to handle this situation. First, you need not produce a Creation Method for every object configuration: you can write Creation Methods for the most popular configurations and leave some public constructors around to handle the rest of the cases. It also makes sense to consider using parameters to cut down on the number of Creation Methods.
Extract Factory
Can too many Creation Methods on a class obscure its primary responsibility? This is really a matter of taste. Some folks find that when object creation begins to dominate the public interface of a class, the class no longer strongly communicates its main purpose. If you’re working with a class that has Creation Methods on it and you find that the Creation Methods distract you from the primary responsibilities of the class, you can refactor the related Creation Methods to a single Factory, like so:
It’s worth noting that LoanFactory is not an Abstract Factory [ DP ]. Abstract Factories can be substituted at runtime—you can define different Abstract Factory classes, each of which knows how to return a family of products, and you can outfit a system or client with a particular Abstract Factory instance. Factories tend to be less sophisticated. They are often implemented as a single class that is not part of any hierarchy.
Move Creation Knowledge to Factory
Data and code used to instantiate a class
is sprawled across numerous classes.
Move the creation knowledge into a single Factory class.
Motivation
When the knowledge for creating an object is spread out across numerous classes, you have creation sprawl : the placement of creational responsibilities in classes that ought not to be playing any role in an object’s creation. Creation sprawl, which is a case of the Solution Sprawl smell ( 43 ), tends to result from an earlier design problem. For example, a client needed to configure an object based on some preferences yet lacked access to the object’s creation code. If the client can’t easily access the object’s creation code, say, because it exists in a system layer far removed from the client, how can the client configure the object?
A typical answer is by using brute force. The client passes its configuration preferences to one object, which hands them off to another object, which holds onto them until the creation code, by means of still more objects, obtains the information for use in configuring the object. While this works, it spreads creation code and data far and wide.
The Factory pattern is helpful in this context. It uses one class to encapsulate both creation logic and a client’s instantiation/configuration preferences. A client can tell a Factory instance how to instantiate/configure an object, and then the same Factory instance may be used at runtime to perform the instantiation/configuration. For example, a NodeFactory creates StringNode instances and may be configured by clients to embellish those instances with a DecodingStringNode Decorator:
A Factory need not be implemented exclusively by a concrete class. You can use an interface to define a Factory and make an existing class implement that interface. This approach is useful when you want other areas of a system to communicate with an instance of the existing class exclusively through its Factory interface.
If the creation logic inside a Factory becomes too complex, perhaps due to supporting too many creation options, it may make sense to evolve it into an Abstract Factory [ DP ]. Once that’s done, clients can configure a system to use a particular ConcreteFactory (i.e., a concrete implementation of an Abstract Factory) or let the system use a default ConcreteFactory. While the above NodeFactory is certainly not complicated enough to merit such an evolution, the diagram on the next page shows what it would look like as an Abstract Factory.
What Is a Factory?
“Factory” is one of the most overused and imprecise words in our industry. Some use the term “Factory pattern” to refer to a Factory Method [ DP ], some use the term to refer to an Abstract Factory [ DP ], some use the term to refer to both patterns, and some use the term to refer to any code that creates objects.
Our lack of a commonly understood definition of “Factory” limits our ability to know when a design could benefit from a Factory. So I’ll offer my definition, which is both broad and bounded: A class that implements one or more Creation Methods is a Factory.
This is true if the Creation Methods are static or nonstatic; if the return type of the Creation Methods is an interface, abstract class, or concrete class; or if the class that implements the Creation Methods also implements noncreational responsibilities.
A Factory Method [ DP ] is a nonstatic method that returns a base class or interface type and that is implemented in a hierarchy to enable polymorphic creation (see Introduce Polymorphic Creation with Factory Method , 88). A Factory Method must be defined/implemented by a class and one or more subclasses of the class. The class and subclasses each act as Factories. However, we don’t say that a Factory Method is a Factory.
An Abstract Factory is “an interface for creating families of related or dependent objects without specifying their concrete classes” [ DP , 87]. Abstract Factories are designed to be substitutable at runtime, so a system may be configured to use a specific, concrete implementor of an Abstract Factory. Every Abstract Factory is a Factory, though not every Factory is an Abstract Factory. Classes that are Factories, not Abstract Factories, sometimes evolve into Abstract Factories when a need arises to support the creation of several families of related or dependent objects.
The next diagram, which uses bold lines to designate methods that create objects, illustrates common differences between sample Factory Method, Factory, and Abstract Factory structures.
I’ve seen numerous systems in which the Factory pattern was overused. For example, if every object in a system is created by using a Factory, instead of direct instantiation (e.g., new StringNode(…) ), the system probably has an overabundance of Factories. Overusing this pattern often occurs when people always decouple client code from code that chooses between which classes to instantiate or how to instantiate them. For example, the following createQuery() method makes a choice about which of two query classes to instantiate:
public class Query...
public void createQuery() throws QueryException...
if (usingSDVersion52()) {
query = new QuerySD52();
...
} else {
query = new QuerySD51();
...
}
To eliminate the conditional logic in the above code, some would refactor it to use a QueryFactory :
public class Query...
public void createQuery() throws QueryException...
query = queryFactory.createQuery();
...
QueryFactory now encapsulates the choice of what concrete query class to instantiate. Yet does QueryFactory improve the design of this code? It certainly doesn’t consolidate creation sprawl, and if it only decouples the Query class from the code that instantiates one of the two concrete queries, it most definitely does not add enough value to merit its existence. This illustrates the point that it’s best not to implement a Factory unless it really improves the design of your code or enables you to create/configure objects in a way that wasn’t possible with direct instantiation.
Benefits and Liabilities
+ Consolidates creation logic and instantiation/configuration preferences.
+ Decouples a client from creation logic.
– Complicates a design when direct instantiation would do.
Mechanics
These mechanics assume your Factory will be implemented as a class, rather than as an interface implemented by a class. If you need a Factory interface that is implemented by a class, you must make minor modifications to these mechanics.
1. An instantiator is a class that collaborates with other classes to instantiate a product (i.e., an instance of some class). If the instantiator doesn’t instantiate the product using a Creation Method, modify it and, if necessary, also modify the product ’s class, so the instantiation occurs through a Creation Method.
Compile and test.
2. Create a new class that will become your factory . Name your factory based on what it creates (e.g., NodeFactory , LoanFactory ).
Compile.
3. Apply Move Method [ F ] to move the Creation Method to the factory. If the Creation Method is static, you can make it nonstatic after moving it to the factory.
Compile.
4. Update the instantiator to instantiate the factory and call the factory to obtain an instance of the class.
Compile and test that the instantiator still functions correctly.
Repeat this step for any instantiators that could no longer compile because of changes made during step 3.
5. Data and methods from the other classes are still being used in the instantiation. Move whatever makes sense into the factory, so it handles as much of the creation work as possible. This may involve moving where the factory gets instantiated and who instantiates it.
Compile and test.
Example
This example comes from the HTML Parser project. As described in Move Embellishment to Decorator (144) , a user of the parser can instruct it to handle string parsing in different ways. If a user doesn’t want parsed strings to contain encoded characters, like & (which represents an ampersand, &) or < (which represents an opening angle bracket, <), the user can call the parser’s setStringNodeDecoding(shouldDecode: boolean) method, which turns the string decoding option on or off. As the sketch at the beginning of this Move Creation Knowledge to Factory refactoring illustrates, the parser’s StringParser actually creates StringNode objects, and when it does so, it configures them to decode or not decode, based on the value of the decoding field in Parser .
While this code worked, StringNode creation knowledge was now spread across the Parser , StringParser , and StringNode classes. This problem worsened as new string parsing options were added to the Parser . Each new option required the creation of a new Parser field with corresponding getters and setters, as well as new code in the StringParser and StringNode to handle the new option. The boldface code in the diagram on the following page illustrates some of the changes made to classes that resulted from adding an escape character (e.g., \n or \r ) removal option.
The fields, getters, and setters that were added to Parser to support different parsing options for StringNodes didn’t belong on the Parser class. Why? Because Parser has the responsibility of kicking off a parsing session, not controlling how StringNodes (which represent just one of numerous Node and Tag types) ought to be parsed. In addition, the StringNode class also had no good reason to know anything about decoding or escape character removal options, which have already been modeled using the Decorator pattern (see the example for Move Embellishment to Decorator , 144 ).
Based on my earlier definition, we can say that StringNode is already a Factory because it implements a Creation Method. The trouble is, StringNode isn’t helping consolidate all knowledge used in instantiating/configuring a StringNode , nor do we actually want it to because it is better to keep StringNode small and simple. A new Factory class will be better able to consolidate the instantiation/configuration, so I will refactor to one. For simplicity, the following code includes only one parsing option—the one for decoding nodes—and doesn’t include the option for escape character removal.
1. StringParser instantiates StringNode objects. The first step in this Move Creation Knowledge to Factory refactoring is to make StringParser perform its instantiation of StringNode objects by using a Creation Method. It already does this, as the following code shows.
public class StringParser...
public Node find(...) {
...
return StringNode.createStringNode(
textBuffer, textBegin, textEnd,
parser.shouldDecodeNodes()
);
}
public class StringNode...
public static Node createStringNode(
StringBuffer textBuffer, int textBegin, int textEnd, boolean shouldDecode) {
if (shouldDecode)
return new DecodingStringNode(
new StringNode(textBuffer, textBegin, textEnd)
);
return new StringNode(textBuffer, textBegin, textEnd);
}
2. Now I create a new class that will become a factory for StringNode objects. Because a StringNode is a type of Node , I name the class NodeFactory :
public class NodeFactory {
}
3. Next, I apply Move Method [ F ] to move StringNode ’s Creation Method to NodeFactory . I decide to make the moved method nonstatic because I don’t want client code statically bound to one Factory implementation. I also decide to delete the Creation Method in StringNode :
public class NodeFactory {
public static Node createStringNode(
StringBuffer textBuffer, int textBegin, int textEnd, boolean shouldDecode) {
if (shouldDecode)
return new DecodingStringNode(
new StringNode(textBuffer, textBegin, textEnd));
return new StringNode(textBuffer, textBegin, textEnd);
}
}
public class StringNode...
public static Node createStringNode(...
}
After this step, StringParser and other clients that used to call the StringNode ’s Creation Method no longer compile. I’ll fix that next.
4. Now I modify the StringParser to instantiate a NodeFactory and call it to create a StringNode :
public class StringParser...
public Node find(...) {
...
NodeFactory nodeFactory = new NodeFactory();
return nodeFactory .createStringNode(
textBuffer, textBegin, textEnd, parser.shouldDecodeNodes()
);
}
I perform a similar step for any other clients that no longer compile because of work done in step 3.
5. Now comes the fun part: eliminating or reducing creation sprawl by moving the appropriate creation code from other classes into the NodeFactory . In this case the other class is the Parser , which the StringParser calls to pass an argument to the NodeFactory during StringNode creation:
public class StringParser...
public Node find(...) {
...
NodeFactory nodeFactory = new NodeFactory();
return nodeFactory.createStringNode(
textBuffer, textBegin, textEnd, parser.shouldDecodeNodes()
);
}
I’d like to move the following Parser code to the NodeFactory :
public class Parser...
private boolean shouldDecodeNodes = false;
public void setNodeDecoding(boolean shouldDecodeNodes) {
this.shouldDecodeNodes = shouldDecodeNodes;
}
public boolean shouldDecodeNodes() {
return shouldDecodeNodes;
}
However, I can’t simply move this code into the NodeFactory because clients of this code are clients of the parser, which call Parser methods like setNodeDecoding(…) to configure the parser for a given parse. Meanwhile, NodeFactory is not even visible to parser clients: it is instantiated by StringParser , which itself is not visible to parser clients. This leads me to conclude that the NodeFactory instance must be accessible to both Parser clients and the StringParser . To make that happen, I take the following steps.
a. I first apply Extract Class [ F ] on the Parser code I want to eventually merge with the NodeFactory . This leads to the creation of the String-NodeParsingOption class:
public class StringNodeParsingOption {
private boolean decodeStringNodes;
public boolean shouldDecodeStringNodes() {
return decodeStringNodes;
}
public void setDecodeStringNodes(boolean decodeStringNodes) {
this.decodeStringNodes = decodeStringNodes;
}
}
This new class replaces the shouldDecodeNodes field, getter, and setter with a StringNodeParsingOption field and its getter and setter:
public class Parser....
private StringNodeParsingOption stringNodeParsingOption =
new StringNodeParsingOption();
private boolean shouldDecodeNodes = false;
public void setNodeDecoding(boolean shouldDecodeNodes) {
this.shouldDecodeNodes = shouldDecodeNodes;
}
public boolean shouldDecodeNodes() {
return shouldDecodeNodes;
}
public StringNodeParsingOption getStringNodeParsingOption() {
return stringNodeParsingOption;
}
public void setStringNodeParsingOption(StringNodeParsingOption option) {
stringNodeParsingOption = option;
}
Parser clients now turn StringNode decoding on by instantiating and configuring a StringNodeParsingOption instance and passing it to the parser:
class DecodingNodeTest...
public void testDecodeAmpersand() {
...
StringNodeParsingOption decodeNodes =
new StringNodeParsingOption();
decodeNodes.setDecodeStringNodes(true);
parser. setStringNodeParsingOption(decodeNodes);
parser.setNodeDecoding(true);
...
}
The StringParser now obtains the state of the StringNode decoding option by means of the new class:
public class StringParser...
...
public Node find(...) {
NodeFactory nodeFactory = new NodeFactory();
return nodeFactory.createStringNode(
textBuffer,
textBegin,
textEnd,
parser. getStringNodeParsingOption().shouldDecodeStringNodes()
);
}
b. Now I apply Inline Class [ F ] to merge NodeFactory with StringNodeParsing-Option . This leads to the following changes in StringParser :
public class StringParser...
public Node find(...) {
...
return parser. getStringNodeParsingOption() .createStringNode(
textBuffer, textBegin, textEnd ,
parser.getStringNodeParsingOption().shouldDecodeStringNodes()
);
}
And the following changes in StringNodeParsingOption :
public class StringNodeParsingOption...
private boolean decodeStringNodes;
public Node createStringNode(
StringBuffer textBuffer, int textBegin, int textEnd , boolean shouldDecode ) {
if (decodeStringNodes)
return new DecodingStringNode(
new StringNode(textBuffer, textBegin, textEnd));
return new StringNode(textBuffer, textBegin, textEnd);
}
}
c. The final step is to rename the class StringNodeParsingOption to NodeFactory and then perform a similar renaming on the NodeFactory field, getter, and setter in Parser :
public class StringNodeParsingOption NodeFactory ...
public class Parser...
private NodeFactory nodeFactory = new NodeFactory();
public NodeFactory getNodeFactory() {
return nodeFactory;
}
public void setNodeFactory(NodeFactory nodeFactory) {
this.nodeFactory = nodeFactory;
}
And that does it. NodeFactory has helped tame creation sprawl by handling the work associated with instantiating and configuring StringNode objects.
Encapsulate Classes with Factory
Clients directly instantiate classes that reside
in one package and implement a common interface.
Make the class constructors non-public and let clients
create instances of them using a Factory.
Motivation
A client’s ability to directly instantiate classes is useful so long as the client needs to know about the very existence of those classes. But what if the client doesn’t need that knowledge? What if the classes live in one package and implement one interface, and those conditions aren’t likely to change? In that case, the classes in the package could be hidden from clients outside the package by giving a Factory the responsibility of creating and returning instances that implement a common interface.
There are several motivations for doing this. First, it provides a way to rigorously apply the mantra “program to an interface, not an implementation” [ DP ] by ensuring that clients interact with classes via their common interface. Second, it provides a way to reduce the “conceptual weight” [ Bloch ] of a package by hiding classes that don’t need to be publicly visible outside their package (i.e., clients don’t need to know these classes exist). And third, it simplifies the construction of available kinds of instances by making the set available through a Factory’s intention-revealing Creation Methods.
The one major issue with this refactoring involves a dependency cycle: whenever you create a new subclass or add/modify an existing subclass constructor, you must add a new Creation Method to your Factory. If you don’t often add new subclasses or add/modify constructors to existing subclasses, this is not a problem. If you do, you may wish to avoid this refactoring or transition to a design that lets clients directly instantiate whichever subclasses they like. You can also consider a hybrid approach in which you produce a Factory for the most popular kinds of instances and don’t fully encapsulate all of the subclasses so that clients may instantiate classes as needed.
Programmers who make their code available to others as binary code, not source code, may also wish to avoid this refactoring because it doesn’t provide clients with the ability to modify encapsulated classes or the Factory’s Creation Methods.
This refactoring can yield a class that behaves as both a Factory and an implementation class (i.e., implementing non-creation-based methods). Some are comfortable with this mixture, while others aren’t. If you find that such a mixtures obscures the primary responsibility of a class, consider Extract Factory (66) .
The sketch at the start of this refactoring gives you a glimpse of some object-to-relational database mapping code. Before the refactoring was applied, programmers (including myself) occasionally instantiated the wrong subclass or the right subclass with incorrect arguments (e.g., we called a constructor that took a primitive Java int when we really needed to call the constructor that took Java’s Integer object). The refactoring reduced our defect count by encapsulating the knowledge about the subclasses and producing a single place to get a variety of well-named subclass instances.
Benefits and Liabilities
+ Simplifies the creation of kinds of instances by making the set available through intention-revealing methods.
+ Reduces the “conceptual weight” [ Bloch ] of a package by hiding classes that don’t need to be public.
+ Helps enforce the mantra “program to an interface, not an implementation” [ DP ].
– Requires new/updated Creation Methods when new kinds of instances must be created.
– Limits customization when clients can only access a Factory’s binary code, not its source code.
Mechanics
In general, you’ll want to apply this refactoring when your classes share a common public interface, share the same superclass, and reside in the same package.
1. Find a client that calls a class’s constructor in order to create a kind of instance. Apply Extract Method [ F ] on the constructor call to produce a public, static method. This new method is a creation method . Now apply Move Method [ F ] to move the creation method to the superclass of the class with the chosen constructor.
Compile and test.
2. Find all callers of the chosen constructor that instantiate the same kind of instance as the creation method and update them to call the creation method.
Compile and test.
3. Repeat steps 1 and 2 for any other kinds of instances that may be created by the class’s constructor.
4. Declare the class’s constructor to be non-public.
Compile.
5. Repeat steps 1–4 for all classes you would like to encapsulate.
Example
The following example is based on object-to-relational mapping code that is used to write and read objects to and from a relational database.
1. I begin with a small hierarchy of classes that reside in a package called descriptors . These classes assist in mapping database attributes to the instance variables of objects:
package descriptors;
public abstract class AttributeDescriptor...
protected AttributeDescriptor(...)
public class BooleanDescriptor extends AttributeDescriptor...
public BooleanDescriptor(...) {
super(...);
}
public class DefaultDescriptor extends AttributeDescriptor...
public DefaultDescriptor(...) {
super(...);
}
public class ReferenceDescriptor extends AttributeDescriptor...
public ReferenceDescriptor(...) {
super(...);
}
The abstract AttributeDescriptor constructor is protected, and the constructors for the three subclasses are public. While I’m showing only three subclasses of AttributeDescriptor , there are actually about ten in the real code.
I’ll focus on the DefaultDescriptor subclass. The first step is to identify a kind of instance that can be created by the DefaultDescriptor constructor. To do that, I look at some client code:
protected List createAttributeDescriptors() {
List result = new ArrayList();
result.add(new DefaultDescriptor("remoteId", getClass(), Integer.TYPE));
result.add(new DefaultDescriptor("createdDate", getClass(), Date.class));
result.add(new DefaultDescriptor("lastChangedDate", getClass(), Date.class));
result.add(new ReferenceDescriptor("createdBy", getClass(), User.class,
RemoteUser.class));
result.add(new ReferenceDescriptor("lastChangedBy", getClass(), User.class,
RemoteUser.class));
result.add(new DefaultDescriptor("optimisticLockVersion", getClass(), Integer.TYPE));
return result;
}
Here I see that DefaultDescriptor is being used to represent mappings for Integer and Date types. While it may also be used to map other types, I must focus on one kind of instance at a time. I decide to produce a creation method that will create attribute descriptors for Integer types. I begin by applying Extract Method [ F ] to produce a public, static creation method called forInteger(…) :
protected List createAttributeDescriptors()...
List result = new ArrayList();
result.add( forInteger("remoteId", getClass(), Integer.TYPE) );
...
public static DefaultDescriptor forInteger(...) {
return new DefaultDescriptor(...);
}
Because forInteger(…) always creates AttributeDescriptor objects for an Integer , there is no need to pass it the value Integer.TYPE :
protected List createAttributeDescriptors()...
List result = new ArrayList();
result.add(forInteger("remoteId", getClass() , Integer.TYPE ));
...
public static DefaultDescriptor forInteger(...) {
return new DefaultDescriptor(..., Integer.TYPE );
}
I also change the forInteger(…) method’s return type from DefaultDescriptor to AttributeDescriptor because I want clients to interact with all AttributeDescriptor subclasses via the AttributeDescriptor interface:
public static AttributeDescriptor DefaultDescriptor forInteger(...)...
Now I move forInteger(…) to the AttributeDescriptor class by applying Move Method [ F ]:
public abstract class AttributeDescriptor {
public static AttributeDescriptor forInteger(...) {
return new DefaultDescriptor(...);
}
The client code now looks like this:
protected List createAttributeDescriptors()...
List result = new ArrayList();
result.add( AttributeDescriptor.forInteger(...) );
...
I compile and test to confirm that everything works as expected.
2. Next, I search for all other callers to the DefaultDescriptor constructor that produce an AttributeDescriptor for an Integer , and I update them to call the new creation method:
protected List createAttributeDescriptors() {
List result = new ArrayList();
result.add(AttributeDescriptor.forInteger("remoteId", getClass()));
...
result.add( AttributeDescriptor.forInteger("optimisticLockVersion", getClass()) );
return result;
}
I compile and test. Everything is working.
3. Now I repeat steps 1 and 2 as I continue to produce creation methods for the remaining kinds of instances that the DefaultDescriptor constructor can create. This leads to two more creation methods:
public abstract class AttributeDescriptor {
public static AttributeDescriptor forInteger(...) {
return new DefaultDescriptor(...);
}
public static AttributeDescriptor forDate(...) {
return new DefaultDescriptor(...);
}
public static AttributeDescriptor forString(...) {
return new DefaultDescriptor(...);
}
4. I now declare the DefaultDescriptor constructor protected:
public class DefaultDescriptor extends AttributeDescriptor {
protected DefaultDescriptor(...) {
super(...);
}
I compile and everything goes according to plan.
5. I repeat steps 1–4 for the other AttributeDescriptor subclasses. When I’m done, the new code
• Gives access to AttributeDescriptor subclasses via their superclass.
• Ensures that clients obtain subclass instances via the AttributeDescriptor interface.
• Prevents clients from directly instantiating AttributeDescriptor subclasses.
• Communicates to other programmers that AttributeDescriptor subclasses aren’t meant to be public. Clients interact with subclass instances via their common interface.
Variations
Encapsulating Inner Classes
Java’s java.util.Collections class contains a remarkable example of what encapsulating classes with Creation Methods is all about. The class’s author, Joshua Bloch, needed to give programmers a way to make collections, lists, sets, and maps unmodifiable and/or synchronized. He wisely chose to implement this behavior using the protection form of the Proxy [ DP ] pattern. However, instead of creating public java.util Proxy classes (for handling synchronization and unmodifiabilty) and then expecting programmers to protect their own collections, he defined the proxies in the Collections class as non-public inner classes and then gave Collections a set of Creation Methods from which programmers could obtain the kinds of proxies they needed. The sketch on page 87 shows a few of the inner classes and Creation Methods specified by the Collections class.
Notice that java.util.Collections even contains small hierarchies of inner classes, all of which are non-public. Each inner class has a corresponding method that receives a collection, protects it, and then returns the protected instance, using a commonly defined interface type (such as List or Set ). This solution reduced the number of classes programmers needed to know about, while providing the necessary functionality. The java.util.Collections class is also an example of a Factory.
Introduce Polymorphic Creation with Factory Method
Classes in a hierarchy implement a method similarly,
except for an object creation step.
Make a single superclass version of the method that
calls a Factory Method to handle the instantiation.
Motivation
To form a Creation Method (see Replace Constructors with Creation Methods , 57 ), a class must implement a static or nonstatic method that instantiates and returns an object. On the other hand, if you wish to form a Factory Method [ DP ], you need the following:
• A type (defined by an interface, abstract class, or class) to identify the set of classes that Factory Method implementors may instantiate and return
• The set of classes that implement that type
• Several classes that implement the Factory Method, making local decisions about which of the set of classes to instantiate, initialize, and return
While that may sound like a tall order, Factory Methods are most common in object-oriented programs because they provide a way to make object creation polymorphic.
In practice, Factory Methods are usually implemented within a class hierarchy, though they may be implemented by classes that simply share a common interface. It is common for an abstract class to either declare a Factory Method and force subclasses to override it or to provide a default Factory Method implementation and let subclasses inherit or override that implementation.
Factory Methods are often designed into framework classes to make it easy for programmers to extend a framework’s functionality. Such extensions are commonly implemented by subclassing a framework class and overriding a Factory Method to return a specific object.
Because the signature of a Factory Method must be the same for all implementers of the Factory Method, you may be forced to pass unnecessary parameters to some Factory Method implementers. For example, if one subclass requires an int and a double to create an object, while another subclass requires only an int to create an object, a Factory Method implemented by both subclasses will need to accept both an int and a double . Since the double will be unnecessary for one subclass, looking at the code may be a bit confusing.
Factory Methods are often called by Template Methods [ DP ]. The collaboration of these two patterns frequently evolves into a class hierarchy as a result of refactoring to rid the hierarchy of duplicate code. For example, imagine that you find a method either in a superclass and overridden by a subclass or in several subclasses, and this method is implemented nearly identically in these places except for an object creation step. You see how you could replace all versions of this method with a single superclass Template Method, provided that the Template Method can issue one object creation call without knowing the class of object that the superclass and/or subclasses will instantiate, initialize, and return. No pattern is better suited to that task than Factory Method.
Is using a Factory Method simpler than calling new or calling a Creation Method? The pattern certainly isn’t simpler to implement. However, the resulting code that uses a Factory Method tends to be simpler than code that duplicates a method in several classes just to perform custom object creation.
Benefits and Liabilities
+ Reduces duplication resulting from a custom object creation step.
+ Effectively communicates where creation occurs and how it may be overridden.
+ Enforces what type a class must implement to be used by a Factory Method.
– May require you to pass unnecessary parameters to some Factory Method implementers.
Mechanics
This refactoring is most commonly used in the following situations:
• When sibling subclasses implement a method similarly, except for an object creation step
• When a superclass and subclass implement a method similarly, except for an object creation step
The mechanics presented in this subsection handle the sibling subclasses scenario and can easily be adapted for the superclass and subclass scenario. For the purposes of these mechanics, a method that is implemented similarly in a hierarchy, except for an object creation step, will be called a similar method.
1. In a subclass that contains a similar method, modify the method so the custom object creation occurs in what these steps will call an instantiation method. You’ll usually do this by applying Extract Method [ F ] on the creation code or by refactoring the creation code to call a previously extracted instantiation method.
Use a generic name for the instantiation method (e.g., createBuilder , newProduct ) because the same method name will need to be used in the sibling subclass’s similar methods. Make the return type for the instantiation method be the type that is common for the custom instantiation logic in the sibling subclass’s similar methods.
Compile and test.
2. Repeat step 1 for the similar method in the sibling subclasses. This should yield one instantiation method for each of the sibling’s subclasses, and the instantiation method’s signature should be the same in every sibling subclass.
Compile and test.
3. Next, modify the superclass of the sibling subclasses. If you can’t modify that class or would rather not do so, apply Extract Superclass [ F ] to produce a superclass that inherits from the superclass of the sibling subclasses and makes the sibling subclasses inherit from the new superclass.
The participant name for the superclass of the sibling subclasses is Factory Method: Creator [ DP ].
Compile and test.
4. Apply Form Template Method [ F ] on the similar method. This will involve applying Pull Up Method [ F ]. When you apply that refactoring, be sure to implement the following advice, which comes from a note in the mechanics for Pull Up Method [ F ]:
If you are in a strongly typed language and the [method you want to pull up] calls another method that is present on both subclasses but not the superclass, declare an abstract method on the superclass. [ F , 323]
One such abstract method you’ll declare on the superclass will be for your instantiation method. Having declared that abstract method, you will have implemented a factory method . Each of the sibling subclasses is now a Factory Method: ConcreteCreator [ DP ].
Compile and test.
5. Repeat steps 1–4 if you have additional similar methods in the sibling subclasses that could benefit from calling the previously created factory method.
6. If the factory method in a majority of ConcreteCreators contains the same instantiation code, move that code to the superclass by transforming the factory method declaration in the superclass into a concrete factory method that performs the default (“majority case”) instantiation behavior.
Compile and test.
Example
In one of my projects, I had used test-driven development to produce an XMLBuilder —a Builder [ DP ] that allowed clients to easily produce XML. Then I found that I needed to create a DOMBuilder , a class that would behave like the XMLBuilder , only it would internally produce XML by creating a Document Object Model ( DOM ) and give clients access to that DOM .
To produce the DOMBuilder , I used the same tests I’d already written to produce the XMLBuilder . I needed to make only one modification to each test: instantiation of a DOMBuilder instead of an XMLBuilder :
public class DOMBuilderTest extends TestCase...
private OutputBuilder builder;
public void testAddAboveRoot() {
String invalidResult =
"<orders>" +
"<order>" +
"</order>" +
"</orders>" +
"<customer>" +
"</customer>";
builder = new DOMBuilder("orders"); // used to be new XMLBuilder("orders")
builder.addBelow("order");
try {
builder.addAbove("customer");
fail("expecting java.lang.RuntimeException");
} catch (RuntimeException ignored) {}
}
A key design goal for DOMBuilder was to make it and XMLBuilder share the same type: OutputBuilder , as shown in the following diagram.
After writing the DOMBuilder , I had nine test methods that were nearly identical on the XMLBuilderTest and DOMBuilderTest . In addition, DOMBuilderTest had its own unique tests, which tested access to and contents of a DOM . I wasn’t happy with all the test-code duplication, because if I made a change to an XMLBuilderTest , I needed to make the same change to the corresponding DOMBuilderTest . I knew it was time to refactor to the Factory Method. Here’s how I went about doing that work.
1. The similar method I first identify is the test method, testAddAboveRoot() . I extract its instantiation logic into an instantiation method like so:
public class DOMBuilderTest extends TestCase...
private OutputBuilder createBuilder(String rootName) {
return new DOMBuilder(rootName);
}
public void testAddAboveRoot() {
String invalidResult =
"<orders>" +
"<order>" +
"</order>" +
"</orders>" +
"<customer>" +
"</customer>";
builder = createBuilder("orders");
builder.addBelow("order");
try {
builder.addAbove("customer");
fail("expecting java.lang.RuntimeException");
} catch (RuntimeException ignored) {}
}
Notice that the return type for the new createBuilder(…) method is an OutputBuilder . I use that return type because the sibling subclass, XMLBuilderTest , will need to define its own createBuilder(…) method (in step 2) and I want the instantiation method’s signature to be the same for both classes.
I compile and run my tests to ensure that everything’s still working.
2. Now I repeat step 1 for all other sibling subclasses, which in this case is just XMLBuilderTest :
public class XMLBuilderTest extends TestCase...
private OutputBuilder createBuilder(String rootName) {
return new XMLBuilder(rootName);
}
public void testAddAboveRoot() {
String invalidResult =
"<orders>" +
"<order>" +
"</order>" +
"</orders>" +
"<customer>" +
"</customer>";
builder = createBuilder("orders");
builder.addBelow("order");
try {
builder.addAbove("customer");
fail("expecting java.lang.RuntimeException");
} catch (RuntimeException ignored) {}
}
I compile and test to make sure the tests still work.
3. I’m now about to modify the superclass of my tests. But that superclass is TestCase , which is part of the JUnit framework. I don’t want to modify that superclass, so I apply Extract Superclass [ F ] to produce AbstractBuilderTest , a new superclass for my test classes:
public class AbstractBuilderTest extends TestCase {
}
public class XMLBuilderTest extends AbstractBuilderTest ...
public class DOMBuilderTest extends AbstractBuilderTest ...
4. I can now apply Form Template Method (205) . Because the similar method is now identical in XMLBuilderTest and DOMBuilderTest , the Form Template Method mechanics I must follow instruct me to use Pull Up Method [ F ] on testAddAboveRoot() . Those mechanics first lead me to apply Pull Up Field [ F ] on the builder field:
public class AbstractBuilderTest extends TestCase {
protected OutputBuilder builder;
}
public class XMLBuilderTest extends AbstractBuilderTest...
private OutputBuilder builder;
public class DOMBuilderTest extends AbstractBuilderTest...
private OutputBuilder builder;
Continuing with the Pull Up Method [ F ] mechanics for testAddAboveRoot() , I now find that I must declare an abstract method on the superclass for any method that is called by testAddAboveRoot() and present in the XMLBuilderTest and DOMBuilderTest . The method, createBuilder(…) , is such a method, so I pull up an abstract method declaration of it:
public abstract class AbstractBuilderTest extends TestCase {
protected OutputBuilder builder;
protected abstract OutputBuilder createBuilder(String rootName);
}
I can now proceed with pulling up testAddAboveRoot() to AbstractBuilderTest :
public abstract class AbstractBuilderTest extends TestCase...
public void testAddAboveRoot() {
String invalidResult =
"<orders>" +
"<order>" +
"</order>" +
"</orders>" +
"<customer>" +
"</customer>";
builder = createBuilder("orders");
builder.addBelow("order");
try {
builder.addAbove("customer");
fail("expecting java.lang.RuntimeException");
} catch (RuntimeException ignored) {}
}
That step removed testAddAboveRoot() from XMLBuilderTest and DOMBuilderTest . The createBuilder(…) method, which is now declared in AbstractBuilderTest and implemented in XMLBuilderTest and DOMBuilderTest , now implements the Factory Method [ DP ] pattern.
As always, I compile and test my tests to make sure that they still work.
5. Since there are additional similar methods between XMLBuilderTest and DOMBuilderTest , I repeat steps 1–4 for each similar method.
6. At this point I consider creating a default implementation of createBuilder(…) in AbstractBuilderTest . I would only do this if it would help reduce duplication in the multiple subclass implementations of createBuilder(…) . In this case, I don’t have such a need because XMLBuilderTest and DOMBuilderTest each instantiate their own kind of OutputBuilder . So that brings me to the end of the refactoring.
Encapsulate Composite with Builder
Building a Composite is repetitive, complicated,
or error-prone.
Simplify the build by letting a Builder handle the details.
Motivation
A Builder [ DP ] performs burdensome or complicated construction steps on behalf of a client. A common motivation for refactoring to a Builder is to simplify client code that creates complex objects. When difficult or tedious parts of creation are implemented by a Builder, a client can direct the Builder’s creation work without having to know how that work is accomplished.
Builders often encapsulate Composites [ DP ] because the construction of Composites can frequently be repetitive, complicated, or error-prone. For example, to add a child node to a parent node, a client must do the following:
• Instantiate a new node
• Initialize the new node
• Correctly add the new node to the right parent node
This process is error-prone because you can either forget to add a new node to a parent or you can add the new node to the wrong parent. The process is repetitive because it requires performing the same batch of construction steps over and over again. It’s well worth refactoring to any Builder that can reduce errors or minimize and simplify creation steps.
Another motivation for encapsulating a Composite with a Builder is to decouple client code from Composite code. For example, in the client code shown in the following diagram, notice how the creation of the DOM Composite, orderTag , is tightly coupled to the DOM’s Document , DocumentImpl , Element , and Text interfaces and classes.
Such tight coupling makes it difficult to change Composite implementations. On one project, we needed to upgrade our system to use a newer version of the DOM , which happened to have several differences from the DOM 1.0 version we had been using. This painful upgrade involved changing many lines of Composite-construction code that were spread across the system. As part of the upgrade, we encapsulated the new DOM code within a DOMBuilder , as shown in the diagram on the following page.
All of the methods on DOMBuilder accept strings as arguments and return void. There is no mention of DOM interfaces or classes in DOMBuilder ’s interface, yet DOMBuilder internally assembles DOM objects at runtime. Client code that uses a DOMBuilder is loosely coupled to DOM code. That’s good, for when future versions of the DOM are released or when we decide to use JDOM or our own TagNode objects, we can easily produce new Builders that feature the identical interface as DOMBuilder . Having one generic Builder interface also enables us to configure our system to use whatever Builder implementation is needed in a given context.
The authors of Design Patterns describe the intent of the Builder pattern as follows: “Separate the construction of a complex object from its internal representation so that the same construction process can create different representations” [ DP , 97].
While “creat[ing] different representations” of a complex object is a useful service, it isn’t the only service a Builder provides. As mentioned earlier, simplifying construction or decoupling client code from a complex object are also equally good reasons for using a Builder.
A Builder’s interface ought to reveal its intentions so clearly that anyone who looks at it will instantly know what it does. In practice, a Builder’s interface, or a portion of it, may not be so clear because Builders do a lot of work behind the scenes to make construction simple. This means that you may need to look at a Builder’s implementation or read its test code or documentation to fully understand the features it provides.
Benefits and Liabilities
+ Reduces the repetitive and error-prone nature of Composite creation.
+ Creates a loose coupling between client and Composite.
+ Allows for different representations of the encapsulated Composite or complex object.
– May not have the most intention-revealing interface.
Mechanics
Because there are numerous ways to write a Builder that builds a Composite, there cannot be one set of mechanics for this refactoring. Instead, I’ll offer general steps that you can implement as you see fit. Whatever design you choose for your Builder, I suggest that you use test-driven development [ Beck, TDD ] to produce it.
The following mechanics assume you already have Composite-construction code and you’d like to encapsulate this code with a Builder.
1. Create a builder , a new class that will become a Builder [ DP ] by the end of this refactoring. Make it possible for your builder to produce a one-node Composite [ DP ]. Add a method to the builder to obtain the result of its build.
Compile and test.
2. Make the builder capable of building children. This often involves creating multiple methods for allowing clients to easily direct the creation and positioning of children.
Compile and test.
3. If the Composite-construction code you’re replacing sets attributes or values on nodes, make the builder capable of setting those attributes and values.
Compile and test.
4. Reflect on how simple your builder is for clients to use, and then make it simpler.
5. Refactor your Composite-construction code to use the new builder. This involves making your client code what is known in Design Patterns as a Builder: Client and Builder: Director.
Compile and test.
Example
The Composite I’d like to encapsulate with a Builder is called TagNode . This class is featured in the refactoring Replace Implicit Tree with Composite (178) . TagNode facilitates the creation of XML. It plays all three Composite roles because the TagNode class is a Component, which can be either a Leaf or a Composite at runtime, as shown in the following diagram.
TagNode ’s toString() method outputs an XML representation of all TagNode objects it contains. A TagBuilder will encapsulate TagNode , providing clients with a less repetitive and error-prone way to create a Composite of TagNode objects.
1. My first step is to create a builder that can successfully build one node. In this case, I want to create a TagBuilder that produces the correct XML for a tree containing a single TagNode . I begin by writing a failing test that uses assertXmlEquals , a method I wrote for comparing two pieces of XML:
public class TagBuilderTest...
public void testBuildOneNode() {
String expectedXml =
"<flavors/>";
String actualXml = new TagBuilder("flavors").toXml();
assertXmlEquals(expectedXml, actualXml);
}
Passing that test is easy. Here’s the code I write:
public class TagBuilder {
private TagNode rootNode;
public TagBuilder(String rootTagName) {
rootNode = new TagNode(rootTagName);
}
public String toXml() {
return rootNode.toString();
}
}
The compiler and test code are happy with this new code.
2. Now I’ll make TagBuilder capable of handling children. I want to deal with numerous scenarios, each of which causes me to write a different TagBuilder method.
I start with the scenario of adding a child to a root node. Because I want TagBuilder to both create a child node and position it correctly within the encapsulated Composite, I decide to produce one method for doing just that, called addChild() . The following test uses this method:
public class TagBuilderTest...
public void testBuildOneChild() {
String expectedXml =
"<flavors>"+
"<flavor/>" +
"</flavors>";
TagBuilder builder = new TagBuilder("flavors");
builder.addChild("flavor");
String actualXml = builder.toXml();
assertXmlEquals(expectedXml, actualXml);
}
Here are the changes I make to pass this test:
public class TagBuilder {
private TagNode rootNode;
private TagNode currentNode;
public TagBuilder(String rootTagName) {
rootNode = new TagNode(rootTagName);
currentNode = rootNode;
}
public void addChild(String childTagName) {
TagNode parentNode = currentNode;
currentNode = new TagNode(childTagName);
parentNode.add(currentNode);
}
public String toXml() {
return rootNode.toString();
}
}
That was easy. To fully test that the new code works, I make an even harder test and see if it runs successfully:
public class TagBuilderTest...
public void testBuildChildrenOfChildren() {
String expectedXml =
"<flavors>"+
"<flavor>" +
"<requirements>" +
"<requirement/>" +
"</requirements>" +
"</flavor>" +
"</flavors>";
TagBuilder builder = new TagBuilder("flavors");
builder.addChild("flavor");
builder.addChild("requirements");
builder.addChild("requirement");
String actualXml = builder.toXml();
assertXmlEquals(expectedXml, actualXml);
}
The code passes this test as well. It’s now time to handle another scenario—adding a sibling. Again, I write a failing test:
public class TagBuilderTest...
public void testBuildSibling() {
String expectedXml =
"<flavors>"+
"<flavor1/>" +
"<flavor2/>" +
"</flavors>";
TagBuilder builder = new TagBuilder("flavors");
builder.addChild("flavor1");
builder.addSibling("flavor2");
String actualXml = builder.toXml();
assertXmlEquals(expectedXml, actualXml);
}
Adding a sibling for an existing child implies that there is a way for TagBuilder to know who the common parent is for the child and its new sibling. There is currently no way to know this, as each TagNode instance doesn’t store a reference to its parent. So I write the following failing test to drive the creation of this needed behavior:
public class TagNodeTest...
public void testParents() {
TagNode root = new TagNode("root");
assertNull(root.getParent());
TagNode childNode = new TagNode("child");
root.add(childNode);
assertEquals(root, childNode.getParent());
assertEquals("root", childNode.getParent().getName());
}
To pass this test, I add the following code to TagNode :
public class TagNode...
private TagNode parent;
public void add(TagNode childNode) {
childNode.setParent(this);
children().add(childNode);
}
private void setParent(TagNode parent) {
this.parent = parent;
}
public TagNode getParent() {
return parent;
}
With the new functionality in place, I can refocus on writing code to pass the testBuildSibling() test, listed earlier. Here’s the new code I write:
public class TagBuilder...
public void addChild(String childTagName) {
addTo(currentNode, childTagName);
}
public void addSibling(String siblingTagName) {
addTo(currentNode.getParent(), siblingTagName);
}
private void addTo(TagNode parentNode, String tagName) {
currentNode = new TagNode(tagName);
parentNode.add(currentNode);
}
Once again, the compiler and tests are happy with the new code. I write additional tests to confirm that sibling and child behavior works under various conditions.
Now I need to handle a final child-building scenario: the case when addChild() or addSibling() won’t work because a child must be added to a specific parent. The test below indicates the problem:
public class TagBuilderTest...
public void testRepeatingChildrenAndGrandchildren() {
String expectedXml =
"<flavors>"+
"<flavor>" +
"<requirements>" +
"<requirement/>" +
"</requirements>" +
"</flavor>" +
"<flavor>" +
"<requirements>" +
"<requirement/>" +
"</requirements>" +
"</flavor>" +
"</flavors>";
TagBuilder builder = new TagBuilder("flavors");
for (int i=0; i<2; i++) {
builder.addChild("flavor");
builder.addChild("requirements");
builder.addChild("requirement");
}
assertXmlEquals(expectedXml, builder.toString());
}
The preceding test won’t pass because it doesn’t build what is expected. When the loop runs for the second time, the call to the builder ’s addChild() method picks up where it left off, meaning that it adds a child to the last added node, which produces the following incorrect result: