Generalization is the transformation of specific code into general-purpose code. The production of generalized code frequently occurs as a result of refactoring. All seven refactorings in this chapter yield generalized code. The most common motivation for applying them is to remove duplicated code. A secondary motivation is to simplify or clarify code.
Form Template Method (205) helps remove duplication in similar methods of subclasses in a hierarchy. If the methods perform roughly the same steps, in the same order, yet the steps are slightly different, you can separate what varies from what is generic by producing a superclass method known as a Template Method [ DP ].
Extract Composite (214) is an application of the refactoring Extract Superclass [ F ]. It’s applicable when a Composite [ DP ] has been implemented in multiple subclasses of a hierarchy with no good reason. By extracting a Composite to a superclass, the subclasses share one generic implementation of the Composite.
If you have some code for handling one object and separate code for handling a group of the same objects (usually in some collection), Replace One/Many Distinctions with Composite (224) will help you produce a generic solution that handles one or many objects without distinguishing between the two.
Replace Hard-Coded Notifications with Observer (236) is a classic example of replacing a specific solution with a general one. In this case, there is a tight coupling between objects that notify and objects that get notified. To allow instances of other classes to be notified, the code can be refactored to use an Observer [ DP ].
An Adapter [ DP ] provides another way to unify interfaces. When clients communicate with similar classes using different interfaces, there tends to be duplicated processing logic. By applying Unify Interfaces with Adapter (247) , clients may interact with similar classes using a generic interface. This tends to pave the way for other refactorings to remove duplicated process logic in the client code.
When a class acts as an Adapter for multiple versions of a component, library, API, or other entity, the class usually contains duplication and often lacks a simple design. Applying Extract Adapter (258) produces classes that implement a common interface and adapt a single version of some code.
The final refactoring in this chapter, Replace Implicit Language with Interpreter (269) , targets code that would be better designed were it to use an explicit language. Such code often uses numerous methods to accomplish what a language can do, only in a far more primitive and repetitive way. Refactoring such code to an Interpreter [ DP ] can yield a general-purpose solution that is more compact, simple, and flexible.
Form Template Method
Two methods in subclasses perform similar steps
in the same order, yet the steps are different.
Generalize the methods by extracting their steps
into methods with identical signatures, then pull up
the generalized methods to form a Template Method.
Motivation
Template Methods “implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behavior that can vary” [ DP , 326]. When invariant and variant behaviors are mixed together in the subclass implementations of a method, the invariant behavior is duplicated in the subclasses. Refactoring to a Template Method helps rid subclasses of their duplicated invariant behavior by moving the behavior to one place: a generalized algorithm in a superclass method.
A Template Method’s invariant behavior consists of the following:
• Methods called and the ordering of those methods
• Abstract methods that subclasses must override
• Hook methods (i.e., concrete methods) that subclasses may override
For example, consider the following code:
public abstract class Game...
public void initialize() {
deck = createDeck();
shuffle(deck);
drawGameBoard();
dealCardsFrom(deck);
}
protected abstract Deck createDeck();
protected void shuffle(Deck deck) {
...shuffle implementation
}
protected abstract void drawGameBoard();
protected abstract void dealCardsFrom(Deck deck);
The list of methods called by and ordered within initialize() is invariant. The fact that subclasses must override the abstract methods is also invariant. The shuffle() implementation provided by Game is not invariant: it’s a hook method that lets subclasses inherit behavior or vary it by overriding shuffle() .
Because it is too tedious to implement many methods just to flesh out a Template Method in a subclass, the authors of Design Patterns [ DP ] suggest that a Template Method should minimize the number of abstract methods classes must override. There’s also no simple way for programmers to know which methods may be overridden (i.e., hook methods) without studying the contents of a Template Method.
Template Methods often call Factory Methods [ DP ], like createDeck() in the above code. The refactoring Introduce Polymorphic Creation with Factory Method (88) provides a real-world example of this.
Languages like Java allow you to declare a Template Method final , which prevents accidental overriding of the Template Method by subclasses. In general, this is done only if client code in a system or framework totally relies on the invariant behavior in a Template Method and if allowing reinterpretation of that invariant behavior could cause client code to work incorrectly.
Martin Fowler’s Form Template Method [ F ] and my version cover much of the same ground and can be thought of as the same refactoring. My mechanics use different terminology and have a different final step than Martin’s. In addition, the code I’ve discussed in the Example section illustrates a case where the invariant behavior duplicated in subclasses is subtle, whereas Martin’s example deals with a case where such duplication is explicit. If you aren’t familiar with the Template Method pattern, you’d do well to study both versions of this refactoring.
Benefits and Liabilities
+ Removes duplicated code in subclasses by moving invariant behavior to a superclass.
+ Simplifies and effectively communicates the steps of a general algorithm.
+ Allows subclasses to easily customize an algorithm.
– Complicates a design when subclasses must implement many methods to flesh out the algorithm.
Mechanics
1. In a hierarchy, find a similar method (a method in a subclass that performs similar steps in a similar order to a method in another subclass). Apply Compose Method (123) on the similar method (in both subclasses), extracting identical methods (methods that have the same signature and body in each subclass) and unique methods (methods that have a different signature and body in each subclass).
When deciding whether to extract code as a unique method or an identical method, consider this: If you extract the code as a unique method, you’ll eventually (during step 5) need to produce an abstract or concrete version of that unique method in the superclass. Will it make sense for subclasses to inherit or override the unique method? If not, extract the code into an identical method.
2. Pull up the identical methods to the superclass by applying Pull Up Method [ F ].
3. To produce an identical body for each version of the similar method, apply Rename Method [ F ] on every unique method until the similar method is identical in each subclass.
Compile and test after each application of Rename Method [ F ].
4. If the similar method doesn’t already have an identical signature in each subclass, apply Rename Method [ F ] to produce an identical signature.
5. Apply Pull Up Method [ F ] on the similar method (in either subclass), defining abstract methods on the superclass for each unique method. The pulled-up similar method is now a Template Method.
Compile and test.
Example
At the end of the example used in this catalog for the refactoring Replace Conditional Logic with Strategy (129) there are three subclasses of the abstract class, CapitalStrategy :
These three subclasses happen to contain a small amount of duplication, which, as we’ll see in this section, can be removed by applying Form Template Method . It is relatively common to combine the Strategy and Template Method patterns to produce concrete Strategy classes that have little or no duplicate code in them.
The CapitalStrategy class defines an abstract method for the capital calculation:
public abstract class CapitalStrategy...
public abstract double capital(Loan loan);
Subclasses of CapitalStrategy calculate capital similarly:
public class CapitalStrategyAdvisedLine...
public double capital(Loan loan) {
return loan.getCommitment() * loan.getUnusedPercentage() *
duration(loan) * riskFactorFor(loan);
}
public class CapitalStrategyRevolver...
public double capital(Loan loan) {
return (loan.outstandingRiskAmount() * duration(loan) * riskFactorFor(loan))
+ (loan.unusedRiskAmount() * duration(loan) * unusedRiskFactor(loan));
}
public class CapitalStrategyTermLoan...
public double capital(Loan loan) {
return loan.getCommitment() * duration(loan) * riskFactorFor(loan);
}
protected double duration(Loan loan) {
return weightedAverageDuration(loan);
}
private double weightedAverageDuration(Loan loan)...
I observe that CapitalStrategyAdvisedLine ’s calculation is identical to CapitalStrategyTermLoan ’s calculation, except for a step that multiplies the result by the loan’s unused percentage ( loan.getUnusedPercentage() ). Spotting this similar sequence of steps with a slight variation means I can generalize the algorithm by refactoring to Template Method. I’ll do that in the following steps and then deal with the third class, CapitalStrategyRevolver , at the end of this Example section.
1. The capital(…) method implemented by CapitalStrategyAdvisedLine and CapitalStrategyTermLoan is the similar method in this example.
The mechanics direct me to apply Compose Method (123) on the capital() implementations by extracting identical methods or unique methods. Since the formulas in capital() are identical except for CapitalStrategyAdvisedLine ’s step of multiplying by loan.getUnusedPercentage() , I must choose whether to extract that step into its own unique method or extract it as part of a method that includes other code. The mechanics work either way. In this case, several years of programming loan calculators for a bank aids me in making a decision. The risk amount for an advised line is calculated by multiplying the loan’s commitment amount by its unused percentage (i.e., loan.getCommitment() * loan.getUnusedPercentage() ). In addition, I know the standard formula for risk-adjusted capital:
Risk Amount × Duration × Risk Factor
That knowledge leads me to extract the CapitalStrategyAdvisedLine code, loan.getCommitment() * loan.getUnusedPercentage() , into its own method, riskAmountFor() , while performing a similar step for CapitalStrategyTermLoan :
public class CapitalStrategyAdvisedLine...
public double capital(Loan loan) {
return riskAmountFor(loan) * duration(loan) * riskFactorFor(loan);
}
private double riskAmountFor(Loan loan) {
return loan.getCommitment() * loan.getUnusedPercentage();
}
public class CapitalStrategyTermLoan...
public double capital(Loan loan) {
return riskAmountFor(loan) * duration(loan) * riskFactorFor(loan);
}
private double riskAmountFor(Loan loan) {
return loan.getCommitment();
}
Domain knowledge clearly influenced my refactoring decisions during this step. In his book Domain-Driven Design [ Evans ], Eric Evans describes how domain knowledge often directs what we choose to refactor or how we choose to refactor it.
2. This step asks me to pull up identical methods to the superclass, CapitalStrategy . In this case, the riskAmountFor(…) method is not an identical method because the code in each implementation of it varies, so I can move on to the next step.
3. Now I must ensure that any unique methods have the same signature in each subclass. The only unique method, riskAmountFor(…) , already has the same signature in each subclass, so I can proceed to the next step.
4. I must now ensure that the similar method, capital(…) , has the same signature in both subclasses. It does, so I proceed to the next step.
5. Because the capital(…) method in each subclass now has the same signature and body, I can pull it up to CapitalStrategy by applying Pull Up Method [ F ]. This involves declaring an abstract method for the unique method, riskAmountFor(…) :
public abstract class CapitalStrategy...
public abstract double capital(Loan loan);
public double capital(Loan loan) {
return riskAmountFor(loan) * duration(loan) * riskFactorFor(loan);
}
public abstract double riskAmountFor(Loan loan);
The capital() method is now a Template Method. That completes the refactoring for the CapitalStrategyAdvisedLine and CapitalStrategyTermLoan subclasses.
Before I handle the capital calculation in CapitalStrategyRevolver , I’d like to show what would have happened had I not created a riskAmountFor(…) method during step 1 of the refactoring. In that case, I would have created a unique method for CapitalStrategyAdvisedLine ’s step of multiplying by loan.getUnusedPercentage() . I would have called such a step unusedPercentageFor(…) and implemented it as a hook method in CapitalStrategy :
public abstract class CapitalStrategy...
public double capital(Loan loan) {
return loan.getCommitment() * unusedPercentageFor(loan) *
duration(loan) * riskFactorFor(loan);
}
public abstract double riskAmountFor(Loan loan);
protected double unusedPercentageFor(Loan loan) { // hook method
return 1.0
};
Because this hook method returns 1.0 , it has no effect on calculations unless the method is overridden, as it is by CapitalStrategyAdvisedLine :
public class CapitalStrategyAdvisedLine...
protected double unusedPercentageFor(Loan loan) {
return loan.getUnusedPercentage();
};
The hook method allows CapitalStrategyTermLoan to inherit its capital(…) calculation, rather than implement a riskAmount(…) method:
public class CapitalStrategyTermLoan...
public double capital(Loan loan) {
return loan.getCommitment() * duration(loan) * riskFactorFor(loan);
}
protected double duration(Loan loan) {
return weightedAverageDuration(loan);
}
private double weightedAverageDuration(Loan loan)...
So that is another way to produce a Template Method for the capital() calculation. However, it suffers from a few downsides:
• The resulting code poorly communicates the risk-adjusted capital formula (Risk Amount × Duration × Risk Factor).
• Two of the three CapitalStrategy subclasses, CapitalStrategyTermLoan and, as we’ll see, CapitalStrategyRevolver , inherit the hook method’s do-nothing behavior, which, because it is a unique step in CapitalStrategyAdvisedLine , really belongs exclusively in that class.
Now let’s see how CapitalStrategyRevolver would take advantage of the new capital() Template Method. Its original capital() method looks like this:
public class CapitalStrategyRevolver...
public double capital(Loan loan) {
return (loan.outstandingRiskAmount() * duration(loan) * riskFactorFor(loan))
+ (loan.unusedRiskAmount() * duration(loan) * unusedRiskFactor(loan));
}
The first half of the formula resembles the general formula, Risk Amount × Duration × Risk Factor. The second half of the formula is similar, but it’s dealing with the unused portion of a loan. We can refactor this code to take advantage of the Template Method as follows:
public class CapitalStrategyRevolver...
public double capital(Loan loan) {
return
super.capital(loan)
+ (loan.unusedRiskAmount() * duration(loan) * unusedRiskFactor(loan));
}
protected double riskAmountFor(Loan loan) {
return loan.outstandingRiskAmount();
}
You could argue whether this new implementation is easier to understand than the previous one. Certainly some duplication in the formula has been removed. Yet is the resulting formula easier to follow? I think so, because it communicates that capital is calculated according to the general formula with the addition of unused capital. The addition of unused capital can be made clearer by applying Extract Method [ F ] on capital() :
public class CapitalStrategyRevolver...
public double capital(Loan loan) {
return super.capital(loan) + unusedCapital(loan);
}
public double unusedCapital(Loan loan) {
return loan.unusedRiskAmount() * duration(loan) * unusedRiskFactor(loan);
}
Extract Composite
Subclasses in a hierarchy implement the same Composite.
Extract a superclass that implements the Composite.
Motivation
In Extract Superclass [ F ], Martin Fowler explains that if you have two or more classes with similar features, it makes sense to move the common features to a superclass. This refactoring is similar: it addresses the case when the similar feature is a Composite [ DP ] that would be better off in a superclass.
Subclasses in hierarchies that store collections of children and have methods for reporting information about those children are common. When the children being collected happen to be classes in the same hierarchy, there’s a good chance that much duplicate code can be removed by refactoring to Composite.
Removing such duplication can greatly simplify subclasses. On one project, I found that people were confused about how to add new behavior to the system, and much of the confusion stemmed from the complex, child-handling logic propagated in numerous subclasses. By applying Extract Composite , subclass code became simple, which made it easier for folks to understand how to write new subclasses. In addition, the very existence of a superclass named to express that it handled Composites communicated to developers that some rich functionality could be inherited via subclassing.
This refactoring and Extract Superclass [ F ] are essentially the same. I apply this refactoring when I’m only concerned with pulling up common child-handling logic to a superclass. Following that, if there is still more behavior that can be pulled up to a superclass but isn’t related to the Composite, I apply the pull-up logic in Extract Superclass .
Benefits and Liabilities
+ Eliminates duplicated child-storage and child-handling logic.
+ Effectively communicates that child-handling logic may be inherited.
Mechanics
These mechanics are based on the mechanics from Extract Superclass [ F ].
1. Create a composite , a class that will become a Composite [ DP ] during this refactoring. Name this class to reflect what kind of children it will contain (e.g., CompositeTag ).
Compile.
2. Make each child container (a class in the hierarchy that contains duplicate child-handling code) a subclass of your composite .
Compile.
3. In a child container, find a child-processing method that is purely duplicated or partially duplicated across the child containers. A purely duplicated method has the same method body with the same or different method names across child containers. A partially duplicated method has a method body with common and uncommon code and the same or different method names across child containers.
Whether you’ve found a purely duplicated or partially duplicated method, if its name isn’t consistent across child containers, make it consistent by applying Rename Method [ F ].
For a purely duplicated method, move the child collection field referenced by the method to your composite by applying Pull Up Field [ F ]. Rename this field if its name doesn’t make sense for all child containers. Now move the method to the composite by applying Pull Up Method [ F ]. If the pulled-up method relies on constructor code still residing in child containers, pull up that code to the composite’s constructor.
For a partially duplicated method, see if the method body can be made consistent across all child containers by using Substitute Algorithm [ F ]. If so, refactor it as a purely duplicated method. Otherwise, extract the code that is common across all child-container implementations by using Extract Method [ F ] and pull it up to the composite by using Pull Up Method [ F ]. If the method body follows the same sequence of steps, some of which are implemented differently, see if you can apply Form Template Method (205) .
Compile and test after each refactoring.
4. Repeat step 3 for child-processing methods in the child containers that contain purely duplicated or partially duplicated code.
5. Check each client of each child container to see if it can now communicate with the child container using the composite interface. If it can, make it do so.
Compile and test after each refactoring.
Example
This refactoring occurred on the open-source HTML Parser (see http://sourceforge.net/projects/htmlparser ). When the parser parses a piece of HTML, it identifies and creates objects representing HTML tags and pieces of text. For example, here’s some HTML:
Hello, and welcome to my Web page! I work forGiven such HTML, the parser would create objects of the following types:
• Tag (for the <BODY> tag)
• StringNode (for the String , “Hello, and welcome . . .”)
• LinkTag (for the <A HREF= " … " > tag)
Because the link tag ( <A HREF= " … " > ) contains an image tag ( <IMG SRC " … " > ), you might wonder what the parser does with it. The image tag, which the parser treats as an ImageTag , is treated as a child of the LinkTag . When the parser notices that the link tag contains an image tag, it constructs and gives one ImageTag object as a child to the LinkTag object.
Additional tags in the parser, such as FormTag , TitleTag , and others, are also child containers. As I studied some of these classes, it didn’t take long to spot duplicate code for storing and handling child nodes. For example, consider the following:
public class LinkTag extends Tag...
private Vector nodeVector;
public String toPlainTextString() {
StringBuffer sb = new StringBuffer();
Node node;
for (Enumeration e=linkData();e.hasMoreElements();) {
node = (Node)e.nextElement();
sb.append(node.toPlainTextString());
}
return sb.toString();
}
public class FormTag extends Tag...
protected Vector allNodesVector;
public String toPlainTextString() {
StringBuffer stringRepresentation = new StringBuffer();
Node node;
for (Enumeration e=getAllNodesVector().elements();e.hasMoreElements();) {
node = (Node)e.nextElement();
stringRepresentation.append(node.toPlainTextString());
}
return stringRepresentation.toString();
}
Because FormTag and LinkTag both contain children, they both have a Vector for storing children, though it goes by a different name in each class. Both classes need to support the toPlainTextString() operation, which outputs the non-HTML-formatted text of the tag’s children, so both classes contain logic to iterate over their children and produce plain text. Yet the code to do this operation is nearly identical in these classes! In fact, there are several nearly identical methods in the child-container classes, all of which reek of duplication. So follow along as I apply Extract Composite to this code.
1. I must first create an abstract class that will become the superclass of the child-container classes. Because the child-container classes, like LinkTag and FormTag , are already subclasses of Tag , I create the following class:
public abstract class CompositeTag extends Tag {
public CompositeTag(
int tagBegin,
int tagEnd,
String tagContents,
String tagLine) {
super(tagBegin, tagEnd, tagContents, tagLine);
}
}
2. Now I make the child containers subclasses of CompositeTag :
public class LinkTag extends CompositeTag
public class FormTag extends CompositeTag
// and so on...
Note that for the remainder of this refactoring, I’ll show code from only two child containers, LinkTag and FormTag , even though there are others in the code base.
3. I look for a purely duplicated method across all child containers and find toPlainTextString() . Because this method has the same name in each child container, I don’t have to change its name anywhere. My first step is to pull up the child Vector that stores children. I do this using the LinkTag class:
public abstract class CompositeTag extends Tag...
protected Vector nodeVector; // pulled-up field
public class LinkTag extends CompositeTag...
private Vector nodeVector;
I want FormTag to use the same newly pulled-up Vector , nodeVector (yes, it’s an awful name, I’ll change it soon), so I rename its local child Vector to be nodeVector :
public class FormTag extends CompositeTag...
protected Vector allNodesVector;
protected Vector nodeVector;
...
Then I delete this local field (because FormTag inherits it):
public class FormTag extends CompositeTag...
protected Vector nodeVector;
Now I can rename nodeVector in the composite:
public abstract class CompositeTag extends Tag...
protected Vector nodeVector;
protected Vector children;
I’m now ready to pull up the toPlainTextString() method to CompositeTag . My first attempt at doing this with an automated refactoring tool fails because the two methods aren’t identical in LinkTag and FormTag . The trouble is that LinkTag gets an iterator on its children by means of the linkData() method, while FormTag gets an iterator on its children by means of the getAllNodesVector().elements() :
public class LinkTag extends CompositeTag
public Enumeration linkData() {
return children.elements();
}
public String toPlainTextString()...
for (Enumeration e= linkData() ;e.hasMoreElements();)
...
public class FormTag extends CompositeTag...
public Vector getAllNodesVector() {
return children;
}
public String toPlainTextString()...
for (Enumeration e= getAllNodesVector().elements() ;e.hasMoreElements();)
...
To fix this problem, I must create a consistent method for getting access to a CompositeTag ’s children. I do this by making LinkTag and FormTag implement an identical method, called children() , which I pull up to CompositeTag :
public abstract class CompositeTag extends Tag...
public Enumeration children() {
return children.elements();
}
The automated refactoring in my IDE now lets me easily pull up toPlainTextString() to CompositeTag . I run my tests and everything works fine.
4. In this step I repeat step 3 for additional methods that may be pulled up from the child containers to the composite. There happen to be several of these methods. I’ll show you one that involves a method called toHTML() . This method outputs the HTML of a given node. Both LinkTag and FormTag have their own implementations for this method. To implement step 3, I must first decide whether toHTML() is purely duplicated or partially duplicated.
Here’s a look at how LinkTag implements the method:
public class LinkTag extends CompositeTag
public String toHTML() {
StringBuffer sb = new StringBuffer();
putLinkStartTagInto(sb);
Node node;
for (Enumeration e = children();e.hasMoreElements();) {
node = (Node)e.nextElement();
sb.append(node.toHTML());
}
sb.append("</A>");
return sb.toString();
}
public void putLinkStartTagInto(StringBuffer sb) {
sb.append("<A ");
String key,value;
int i = 0;
for (Enumeration e = parsed.keys();e.hasMoreElements();) {
key = (String)e.nextElement();
i++;
if (key!=TAGNAME) {
value = getParameter(key);
sb.append(key+"=\""+value+"\"");
if (i<parsed.size()-1) sb.append(" ");
}
}
sb.append(">");
}
After creating a buffer, putLinkStartTagInto(…) deals with getting the contents of the start tag into the buffer, along with any attributes it may have. The start tag would be something like <A HREF= " … " > or <A NAME= " … " > , where HREF and NAME represent attributes of the tag. The tag could have children, such as a StringNode , as in <A HREF= " … " >I’m a string node</A> or child ImageTag instances. Finally, there is the end tag, </A> , which must be added to the result buffer before the HTML representation of the tag is returned.
Let’s now see how FormTag implements the toHTML() method:
public class FormTag extends CompositeTag...
public String toHTML() {
StringBuffer rawBuffer = new StringBuffer();
Node node,prevNode=null;
rawBuffer.append("<FORM METHOD=\""+formMethod+"\" ACTION=\""+formURL+"\"");
if (formName!=null && formName.length()>0)
rawBuffer.append(" NAME=\""+formName+"\"");
Enumeration e = children.elements();
node = (Node)e.nextElement();
Tag tag = (Tag)node;
Hashtable table = tag.getParsed();
String key,value;
for (Enumeration en = table.keys();en.hasMoreElements();) {
key=(String)en.nextElement();
if (!(key.equals("METHOD")
|| key.equals("ACTION")
|| key.equals("NAME")
|| key.equals(Tag.TAGNAME))) {
value = (String)table.get(key);
rawBuffer.append(" "+key+"="+"\""+value+"\"");
}
}
rawBuffer.append(">");
rawBuffer.append(lineSeparator);
for (;e.hasMoreElements();) {
node = (Node)e.nextElement();
if (prevNode!=null) {
if (prevNode.elementEnd()>node.elementBegin()) {
// It’s a new line
rawBuffer.append(lineSeparator);
}
}
rawBuffer.append(node.toHTML());
prevNode=node;
}
return rawBuffer.toString();
}
This implementation has some similarities and differences compared with the LinkTag implementation. Therefore, according to the definition presented earlier in the Mechanics section, toHTML() should be treated as a partially duplicated child-container method. That means that my next step is to see if I can make one implementation of this method by applying the refactoring Substitute Algorithm [ F ].
It turns out I can. It is easier than it looks because both versions of toHTML() essentially do the same three things: output the start tag along with any attributes, output any child tags, and output the close tag. Knowing that, I arrive at a common method for dealing with the start tag, which I pull up to CompositeTag :
public abstract class CompositeTag extends Tag...
public void putStartTagInto(StringBuffer sb) {
sb.append("<" + getTagName() + " ");
String key,value;
int i = 0;
for (Enumeration e = parsed.keys();e.hasMoreElements();) {
key = (String)e.nextElement();
i++;
if (key!=TAGNAME) {
value = getParameter(key);
sb.append(key+"=\""+value+"\"");
if (i<parsed.size()) sb.append(" ");
}
}
sb.append(">");
}
public class LinkTag extends CompositeTag...
public String toHTML() {
StringBuffer sb = new StringBuffer();
putStartTagInto(sb);
...
public class FormTag extends CompositeTag
public String toHTML() {
StringBuffer rawBuffer = new StringBuffer();
putStartTagInto(rawBuffer);
...
I perform similar operations to make a consistent way of obtaining HTML from child nodes and from an end tag. All of that work enables me to pull up one generic toHTML() method to the composite:
public abstract class CompositeTag extends Tag...
public String toHTML() {
StringBuffer htmlContents = new StringBuffer();
putStartTagInto(htmlContents);
putChildrenTagsInto(htmlContents);
putEndTagInto(htmlContents);
return htmlContents.toString();
}
To complete this part of the refactoring, I’ll continue to move child-related methods to CompositeTag , though I’ll spare you the details.
5. The final step involves checking clients of child containers to see if they can now communicate with the child containers using the CompositeTag interface. In this case, there are no such cases in the parser itself, so I’m finished with the refactoring.
Replace One/Many Distinctions with Composite
A class processes single and multiple objects
using separate pieces of code.
Use a Composite to produce one piece of code
capable of handling single or multiple objects.
Motivation
When a class has a method for processing one object and a nearly identical method for processing a collection of the objects, a one/many distinction exists. Such a distinction can result in problems such as the following.
• Duplicated code: Because the method that processes one object does the same thing as the method that processes a collection of the objects, duplicated code is often spread across the two methods. It’s possible to reduce this duplication without implementing a Composite [ DP ] (see the Example section for details), yet even if duplication is reduced, there are still two methods performing the same kind of processing.
• Nonuniform client code: Whether they have single objects or collections of objects, clients want their objects processed in one way. Yet the existence of two processing methods with different signatures forces clients to pass different kinds of data to the methods (i.e., one object or a collection of objects). This makes client code nonuniform, which reduces simplicity.
• Merging of results: The best way to explain this is with an example. Say you want to find all products that are red and priced under $5.00 or blue and priced above $10.00. One way to find these products is to call a ProductRepository ’s selectBy(List specs) method, which returns a List of results. Here’s an example call to selectBy(…) :
List redProductsUnderFiveDollars = new ArrayList();
redProductsUnderFiveDollars.add(new ColorSpec(Color.red));
redProductsUnderFiveDollars.add(new BelowPriceSpec(5.00));
List foundRedProductsUnderFiveDollars =
productRepository.selectBy(redProductsUnderFiveDollars);
The main problem with selectBy(List specs) is that it can’t handle an OR condition. So if you want to find all products that are red and under $5.00 or blue and above $10.00, you have to make separate calls to selectBy(…) and then merge the results:
List foundRedProductsUnderFiveDollars =
productRepository.selectBy(redProductsUnderFiveDollars);
List foundBlueProductsAboveTenDollars =
productRepository.selectBy(blueProductsAboveTenDollars);
List foundProducts = new ArrayList();
foundProducts.addAll(foundRedProductsUnderFiveDollars);
foundProducts.addAll(foundBlueProductsAboveTenDollars);
As you can see, this approach is awkward and verbose.
The Composite pattern provides a better way. It lets clients process one or many objects with a single method. This has many benefits.
• There’s no duplicated code across methods because only one method handles the objects, whether one or many.
• Clients communicate with that method in a uniform way.
• Clients can make one call to obtain the results of processing a tree of objects rather than having to make several calls and merging processed results. For example, to find red products under $5.00 or blue products above $10.00, a client creates and passes the following Composite to the processing method:
In short, replacing a one/many distinction with a Composite is a way to remove duplication, make client calls uniform, and support the processing of trees of objects. However, if these latter two particular benefits aren’t all that important to your system and you can reduce most of the duplication in methods that have a one/many distinction, a Composite implementation could be overkill.
One common downside of the Composite pattern relates to type safety. To prevent clients from adding invalid objects to a Composite, the Composite code must contain runtime checks of the objects that clients attempt to add to it. This problem is also present with collections because clients can add invalid objects to collections as well.
Benefits and Liabilities
+ Removes duplicate code associated with handling one or many objects.
+ Provides a uniform way to process one or many objects.
+ Supports richer ways to process many objects (e.g., an OR expression).
– May require runtime checks for type safety during construction of the Composite.
Mechanics
In this section and the Example section, a method that works with one object is called a one-object method while a method that works with a collection of objects is called a many-object method.
1. The many-object method accepts a collection as a parameter. Create a new class that accepts the collection in a constructor and provides a getter method for it. This composite class will become what is known as a Composite in Design Patterns [ DP ].
Within the many-object method, declare and instantiate an instance of your composite (i.e., the new class). In addition, find all references within the many-object method to the collection and update the code so access to the collection is obtained via the composite’s getter method.
Compile and test.
2. Apply Extract Method [ F ] on the code within the many-object method that works with the collection. Make the extracted method public. Then apply Move Method [ F ] on the extracted method to move it to your composite.
Compile and test.
3. The many-object method will now be nearly identical to the one-object method. The main difference is that the many-object method instantiates your composite. If there are other differences, refactor to eliminate them.
Compile and test.
4. Change the many-object method so it contains one line of code: a call to the one-object method that passes it your composite instance as an argument. You’ll need to make the composite share the same interface or superclass as the type used by the one-object method.
To do this, consider making the composite a subclass of the type used by the one-object method or create a new interface (using Extract Interface [ F ]) that the composite and all objects passed to the one-object method implement.
Compile and test.
5. Because the many-object method now consists of just one line of code, it can be inlined by applying Inline Method [ F ].
Compile and test.
6. Apply Encapsulate Collection [ F ] on your composite. This will produce an add(…) method on the composite, which clients will call instead of passing a collection to the composite’s constructor. In addition, the getter method for the collection will now return an unmodifiable collection.
Compile and test.
Example
This example deals with Spec instances and how they are used to obtain a desired set of Product instances from a ProductRepository . The example also illustrates the Specification pattern [ Evans ] as described in Replace Implicit Language with Interpreter (269) .
Let’s begin by studying some test code for the ProductRepository . Before any test can run, a ProductRepository (called repository ) must be created. For the test code, I fill a repository with toy Product instances:
public class ProductRepositoryTest extends TestCase...
private ProductRepository repository;
private Product fireTruck =
new Product("f1234", "Fire Truck",
Color.red, 8.95f, ProductSize.MEDIUM);
private Product barbieClassic =
new Product("b7654", "Barbie Classic",
Color.yellow, 15.95f, ProductSize.SMALL);
private Product frisbee =
new Product("f4321", "Frisbee",
Color.pink, 9.99f, ProductSize.LARGE);
private Product baseball =
new Product("b2343", "Baseball",
Color.white, 8.95f, ProductSize.NOT_APPLICABLE);
private Product toyConvertible =
new Product("p1112", "Toy Porsche Convertible",
Color.red, 230.00f, ProductSize.NOT_APPLICABLE);
protected void setUp() {
repository = new ProductRepository();
repository.add(fireTruck);
repository.add(barbieClassic);
repository.add(frisbee);
repository.add(baseball);
repository.add(toyConvertible);
}
The first test we’ll study looks for Product instances of a certain color by means of a call to repository.selectBy(…) :
public class ProductRepositoryTest extends TestCase...
public void testFindByColor() {
List foundProducts = repository.selectBy(new ColorSpec(Color.red));
assertEquals("found 2 red products", 2, foundProducts.size());
assertTrue("found fireTruck", foundProducts.contains(fireTruck));
assertTrue(
"found Toy Porsche Convertible",
foundProducts.contains(toyConvertible));
}
The repository.selectBy(…) method looks like this:
public class ProductRepository...
private List products = new ArrayList();
public Iterator iterator() {
return products.iterator();
}
public List selectBy(Spec spec) {
List foundProducts = new ArrayList();
Iterator products = iterator();
while (products.hasNext()) {
Product product = (Product)products.next();
if (spec.isSatisfiedBy(product))
foundProducts.add(product);
}
return foundProducts;
}
Let’s now look at another test, which calls a different repository.selectBy(…) method. This test assembles a List of Spec instances in order to select specific kinds of products from the repository :
public class ProductRepositoryTest extends TestCase...
public void testFindByColorSizeAndBelowPrice() {
List specs = new ArrayList();
specs.add(new ColorSpec(Color.red));
specs.add(new SizeSpec(ProductSize.SMALL));
specs.add(new BelowPriceSpec(10.00));
List foundProducts = repository.selectBy(specs);
assertEquals(
"small red products below $10.00",
0,
foundProducts.size());
}
The List -based repository.selectBy(…) method looks like this:
public class ProductRepository {
public List selectBy(List specs) {
List foundProducts = new ArrayList();
Iterator products = iterator();
while (products.hasNext()) {
Product product = (Product)products.next();
Iterator specifications = specs.iterator();
boolean satisfiesAllSpecs = true;
while (specifications.hasNext()) {
Spec productSpec = ((Spec)specifications.next());
satisfiesAllSpecs &= productSpec.isSatisfiedBy(product);
}
if (satisfiesAllSpecs)
foundProducts.add(product);
}
return foundProducts;
}
As you can see, the List -based selectBy(…) method is more complicated than the one- Spec selectBy(…) method. If you compare the two methods, you’ll notice a good deal of duplicate code. A Composite can help remove this duplication; however, there’s another way to remove the duplication that doesn’t involve a Composite. Consider this:
public class ProductRepository...
public List selectBy(Spec spec) {
Spec[] specs = { spec };
return selectBy(Arrays.asList(specs));
}
public List selectBy(List specs)...
// same implementation as before
This solution retains the more complicated List -based selectBy(…) method. However, it also completely simplifies the one- Spec selectBy(…) method, which greatly reduces the duplicated code. The only remaining duplication is the existence of the two selectBy(…) methods.
So, is it wise to use this solution instead of refactoring to Composite? Yes and no. It all depends on the needs of the code in question. For the system on which this example code was based, there is a need to support queries with OR, AND, and NOT conditions, like this one:
product.getColor() != targetColor ||
product.getPrice() < targetPrice
The List -based selectBy(…) method cannot support such queries. In addition, having just one selectBy(…) method is preferred so clients can call it in a uniform way. Therefore, I decide to refactor to the Composite pattern by implementing the following steps.
1. The List -based selectBy(…) method is the many-object method. It accepts the following parameter: List specs . My first step is to create a new class that will hold onto the value of the specs parameter and provide access to it via a getter method:
public class CompositeSpec {
private List specs;
public CompositeSpec(List specs) {
this.specs = specs;
}
public List getSpecs() {
return specs;
}
}
Next, I’ll instantiate this class within the List -based selectBy(…) method and update code to call its getter method:
public class ProductRepository...
public List selectBy(List specs) {
CompositeSpec spec = new CompositeSpec(specs);
List foundProducts = new ArrayList();
Iterator products = iterator();
while (products.hasNext()) {
Product product = (Product)products.next();
Iterator specifications = spec.getSpecs() .iterator();
boolean satisfiesAllSpecs = true;
while (specifications.hasNext()) {
Spec productSpec = ((Spec)specifications.next());
satisfiesAllSpecs &= productSpec.isSatisfiedBy(product);
}
if (satisfiesAllSpecs)
foundProducts.add(product);
}
return foundProducts;
}
I compile and test to confirm that these changes work.
2. Now I apply Extract Method [ F ] on the selectBy(…) code that specifically deals with specs :
public class ProductRepository...
public List selectBy(List specs) {
CompositeSpec spec = new CompositeSpec(specs);
List foundProducts = new ArrayList();
Iterator products = iterator();
while (products.hasNext()) {
Product product = (Product)products.next();
if ( isSatisfiedBy(spec, product) )
foundProducts.add(product);
}
return foundProducts;
}
public boolean isSatisfiedBy(CompositeSpec spec, Product product) {
Iterator specifications = spec.getSpecs().iterator();
boolean satisfiesAllSpecs = true;
while (specifications.hasNext()) {
Spec productSpec = ((Spec)specifications.next());
satisfiesAllSpecs &= productSpec.isSatisfiedBy(product);
}
return satisfiesAllSpecs;
}
The compiler and test code are happy with this change, so I can now apply Move Method [ F ] to move the isSatisfiedBy(…) method to the CompositeSpec class:
public class ProductRepository...
public List selectBy(List specs) {
CompositeSpec spec = new CompositeSpec(specs);
List foundProducts = new ArrayList();
Iterator products = iterator();
while (products.hasNext()) {
Product product = (Product)products.next();
if ( spec.isSatisfiedBy(product) )
foundProducts.add(product);
}
return foundProducts;
}
public class CompositeSpec...
public boolean isSatisfiedBy(Product product) {
Iterator specifications = getSpecs().iterator();
boolean satisfiesAllSpecs = true;
while (specifications.hasNext()) {
Spec productSpec = ((Spec)specifications.next());
satisfiesAllSpecs &= productSpec.isSatisfiedBy(product);
}
return satisfiesAllSpecs;
}
One again, I check that the compiler and test code are happy with this change. Both are.
3. The two selectBy(…) methods are now nearly identical. The only difference is that the List -based selectBy(…) method instantiates a CompositeSpec instance:
public class ProductRepository...
public List selectBy(Spec spec) {
// same code
}
public List selectBy(List specs) {
CompositeSpec spec = new CompositeSpec(specs);
// same code
}
The next step will help remove the duplicated code.
4. I now want to make the List -based selectBy(…) method call the one- Spec selectBy(…) method, like so:
public class ProductRepository...
public List selectBy(Spec spec)...
public List selectBy(List specs) {
return selectBy(new CompositeSpec(specs));
}
The compiler does not like this code because CompositeSpec does not share the same interface as Spec , the type used by the called selectBy(…) method. Spec is an abstract class that looks like this:
Since CompositeSpec already implements the isSatisfiedBy(…) method declared by Spec , it’s trivial to make CompositeSpec a subclass of Spec :
public class CompositeSpec extends Spec ...
Now the compiler is happy, as is the test code.
5. Because the List -based selectBy(…) method is now only one line of code that calls the one- Spec selectBy(…) method, I inline it by applying Inline Method [ F ]. Client code that used to call the List -based selectBy(…) now calls the one- Spec selectBy(…) method. Here’s an example of such a change:
public class ProductRepositoryTest...
public void testFindByColorSizeAndBelowPrice() {
List specs = new ArrayList();
specs.add(new ColorSpec(Color.red));
specs.add(new SizeSpec(ProductSize.SMALL));
specs.add(new BelowPriceSpec(10.00));
List foundProducts = repository.selectBy(specs);
List foundProducts = repository.selectBy( new CompositeSpec(specs) );
...
There’s now only one selectBy(…) method that accepts Spec objects like ColorSpec , SizeSpec , or the new CompositeSpec . This is a useful start. However, to build Composite structures that support product searches like product.getColor() != targetColor || product.getPrice() < targetPrice , there is a need for classes like NotSpec and OrSpec . I won’t show how they’re created here; you can read about them in the refactoring Replace Implicit Language with Interpreter (269) .
6. The final step involves applying Encapsulate Collection [ F ] on the collection inside of CompositeSpec . I do this to make CompositeSpec more type-safe (i.e., to prevent clients from adding objects to it that aren’t a subclass of Spec ).
I begin by defining the add(Spec spec) method:
public class CompositeSpec extends Spec...
private List specs;
public void add(Spec spec) {
specs.add(spec);
}
Next, I initialize specs to an empty list:
public class CompositeSpec extends Spec...
private List specs \= new ArrayList() ;
Now comes the fun part. I find all callers of CompositeSpec ’s constructor and update them to call a new, default CompositeSpec constructor as well as the new add(…) method. Here is one such caller and the updates I make to it:
public class ProductRepositoryTest...
public void testFindByColorSizeAndBelowPrice()...
List specs = new ArrayList();
CompositeSpec specs = new CompositeSpec();
specs.add(new ColorSpec(Color.red));
specs.add(new SizeSpec(ProductSize.SMALL));
specs.add(new BelowPriceSpec(10.00));
List foundProducts = repository.selectBy( specs );
...
I compile and test to confirm that the changes work. Once I’ve updated all other clients, there are no more callers to CompositeSpec ’s constructor that take a List . So I delete it:
public class CompositeSpec extends Spec...
public CompositeSpec(List specs) {
this.specs = specs;
}
Now I update CompositeSpec ’s getSpecs(…) method to return an unmodifiable version of specs :
public class CompositeSpec extends Spec...
private List specs = new ArrayList();
public List getSpecs()
return Collections.unmodifiableList (specs);
}
I compile and test to confirm that my implementation of Encapsulate Collection works. It does. CompositeSpec is now a fine implementation of the Composite pattern:
Replace Hard-Coded Notifications with Observer
Subclasses are hard-coded to notify a single
instance of another class.
Remove the subclasses by making their superclass
capable of notifying one or more instances of any class
that implements an Observer interface.
Motivation
Knowing when to refactor to an Observer [ DP ] first involves understanding when you don’t need an Observer. Consider the case of a single instance of a class called Receiver that changes when an instance of a class called Notifier changes, as shown in the following diagram.
In this case, the Notifier instance holds onto a Receiver reference and is hard-coded to notify that reference when it receives new information. Such a tight coupling between Notifier and Receiver makes sense when one Notifier instance must notify only one Receiver instance. If that circumstance changes and a Notifier instance must notify numerous Receiver instances, or instances of other classes, the design must evolve. This is exactly what occurred on Kent Beck and Erich Gamma’s JUnit framework [ Beck and Gamma ]. When users of the framework needed more than one party to observe changes to a TestResult instance, a hard-coded notification was refactored to use the Observer pattern (see the Example section for details).
Every implementation of the Observer pattern leads to loose coupling between a subject (a class that is the source of notifications) and its observers. The Observer interface makes this loose coupling possible. To be notified of new information, a class need only implement the Observer interface and register itself with a subject. The subject, in turn, holds onto a collection of instances that implement the Observer interface, notifying them when changes occur.
Classes that play the role of subject must contain a method for adding Observers and can optionally contain a method for removing Observers. If there is never a need to remove Observers during the life of a subject instance, there’s no need to implement the remove method. Although this seems like basic common sense, many programmers fall into the trap of implementing this pattern exactly as they see its structure defined on class diagrams in books.
Two common Observer implementation problems to watch out for involve cascading notifications and memory leaks. Cascading notifications occur when a subject notifies an observer, which, by also playing the role of subject, notifies other observers, and so on. The result is an overly complicated design that’s difficult to debug. A Mediator [ DP ] implementation may help improve such code. Memory leaks occur when an observer instance is not garbage collected because the instance is still referenced by a subject. If you remember to always remove your observers from their subjects, you’ll avoid memory leaks.
The Observer pattern is used often. Because it isn’t difficult to implement, you may be tempted to use this pattern before it’s actually needed. Resist that temptation! If you begin with a hard-coded notification, you can always evolve a design to use an Observer when you genuinely need one.
Benefits and Liabilities
+ Loosely couples a subject with its observers.
+ Supports one or many observers.
– Complicates a design when a hard-coded notification will suffice.
– Complicates a design when you have cascading notifications.
– May cause memory leaks when observers aren’t removed from their subjects.
Mechanics
A notifier is a class that references and sends notifications to another class. A receiver is a class that registers itself with a notifier and receives messages from the notifier. This refactoring details the steps for eliminating unnecessary notifiers by making their superclass a subject (known in Design Patterns as a ConcreteSubject) and transforming receivers into observers (known in Design Patterns as ConcreteObservers).
1. If a notifier performs custom behavior on behalf of its receiver, instead of performing pure notification logic, move that behavior to the notifier’s receiver by applying Move Method [ F ]. When finished, the notifier contains only notification methods (methods that notify a receiver).
Repeat for all notifiers.
Compile and test.
2. Produce an observer interface by applying Extract Interface [ F ] on a receiver, selecting only those methods called by its notifier. If other notifiers call receiver methods not on the observer interface, add those methods to the observer interface so that it will work for all receivers.
Compile.
3. Make every receiver implement the observer interface. Then make every notifier communicate with its receiver exclusively through the observer interface. Every receiver is now an observer.
Compile and test.
4. Choose a notifier and apply Pull Up Method [ F ] on its notification methods. This includes pulling up the notifier’s observer interface reference as well as code for setting that reference. The notifier’s superclass is now the subject.
Repeat for all notifiers .
Compile.
5. Update each notifier’s observer to register and communicate with the subject, instead of the notifier, and then delete the notifier.
Compile and test.
6. Refactor the subject so it holds onto a collection of observers, rather than just one. This includes updating the way observers register themselves with their subject. It’s common to create a method on the subject for adding observers (e.g., addObserver(Observer observer) ). Finally, update the subject so its notification methods notify all observers in its collection of observers.
Compile and test.
Example
The code sketch at the beginning of this refactoring depicts a piece of the design of Kent Beck and Erich Gamma’s JUnit Testing Framework [ Beck and Gamma ]. In JUnit 2.x, the authors defined two TestResult subclasses called UITestResult and TextTestResult , both of which are Collecting Parameters (see Move Accumulation to Collecting Parameter , 313 ).
TestResult subclasses gather information from test case objects (e.g., whether a test passed or failed) in order to report that information to a TestRunner , a class that displays test results to the screen. The UITestResult class was hard-coded to report information for a Java Abstract Window Toolkit ( AWT ) TestRunner , while the TextTestResult was hard-coded to report information for a console-based TestRunner . Here’s a look at a part of the UITestResult class and the connection to its TestRunner :
class UITestResult extends TestResult {
private TestRunner fRunner;
UITestResult( TestRunner runner ) {
fRunner= runner;
}
public synchronized void addFailure(Test test, Throwable t) {
super.addFailure(test, t);
fRunner.addFailure(this, test, t); // notification to TestRunner
}
...
}
package ui;
public class TestRunner extends Frame { // TestRunner for AWT
private TestResult fTestResult;
...
protected TestResult createTestResult() {
return new UITestResult(this); // hard-coded to UITestResult
}
synchronized public void runSuite() {
...
fTestResult = createTestResult();
testSuite.run( fTestResult );
}
public void addFailure(TestResult result, Test test, Throwable t) {
... // display the failure in a graphical AWT window
}
}
This design was perfectly simple and good, for at this stage in JUnit’s evolution, if the TestResult / TestRunner notifications had been programmed with the Observer pattern, the design would have been more sophisticated than it needed to be. That circumstance changed when users of JUnit requested the ability for multiple objects to observe a TestResult at runtime. Now the hard-coded relationship between TestRunner instances and TestResult instances wasn’t sufficient. To make a TestResult instance capable of supporting many observers, an Observer implementation was necessary.
Would such a change be a refactoring or an enhancement? Making JUnit’s TestRunner instances rely on an Observer implementation, rather than being hard-coded to specific TestResult subclasses, would not change their behavior; it would only make them more loosely coupled to TestResult . On the other hand, making a TestResult class hold onto a collection of observers, rather than just one solitary observer, would be new behavior. So an Observer implementation in this example is both a refactoring (i.e., a behavior-preserving transformation) and an enhancement. However, the refactoring is the essential work here, while the enhancement (supporting a collection of observers rather than just one observer) is simply a consequence of an introduction of the Observer pattern.
1. The first step involves ensuring that every notifier implements only notification methods, instead of performing custom behavior on behalf of a receiver. This is true of UITestResult and not true of TextTestResult . Rather than notifying its TestRunner of test results, TextTestResult reports test results directly to the console using Java’s System.out.println() method:
public class TextTestResult extends TestResult...
public synchronized void addError(Test test, Throwable t) {
super.addError(test, t);
System.out.println("E");
}
public synchronized void addFailure(Test test, Throwable t) {
super.addFailure(test, t);
System.out.print("F");
}
By applying Move Method [ F ], I make TextTestResult contain pure notification methods, while moving its custom behavior to its associated TestRunner :
package textui;
public class TextTestResult extends TestResult...
private TestRunner fRunner;
TextTestResult( TestRunner runner ) {
fRunner= runner;
}
public synchronized void addError(Test test, Throwable t) {
super.addError(test, t);
fRunner.addError(this, test, t);
}
...
package textui;
public class TestRunner...
protected TextTestResult createTestResult() {
return new TextTestResult( this );
}
// moved method
public void addError(TestResult testResult, Test test, Throwable t) {
System.out.println("E");
}
...
TextTestResult now notifies its TestRunner , which reports information to the screen. I compile and test to confirm that the changes work.
2. Now I want to create an observer interface called TestListener . To create that interface, I apply Extract Interface [ F ] on the TestRunner associated with the TextTestResult . When choosing what methods to include in the new interface, I must know which methods TextTestResult calls on TestRunner . Those methods are highlighted in bold in the following listing:
class TextTestResult extends TestResult...
public synchronized void addError(Test test, Throwable t) {
super.addError(test, t);
fRunner.addError(this, test, t);
}
public synchronized void addFailure(Test test, Throwable t) {
super.addFailure(test, t);
fRunner.addFailure(this, test, t);
}
public synchronized void startTest(Test test) {
super.startTest(test);
fRunner.startTest(this, test);
}
Given this information, I extract the following interface:
public interface TestListener {
public void addError(TestResult testResult, Test test, Throwable t);
public void addFailure(TestResult testResult, Test test, Throwable t);
public void startTest(TestResult testResult, Test test);
}
public class TestRunner implements TestListener ...
Now I inspect the other notifier, UITestResult , to see if it calls TestRunner methods that are not on the TestListener interface. It does—it overrides a TestResult method called endTest(…) :
package ui;
class UITestResult extends TestResult...
public synchronized void endTest(Test test) {
super.endTest(test);
fRunner.endTest(this, test);
}
That leads me to update TestListener with the additional method:
public interface TestListener...
public void endTest(TestResult testResult, Test test);
I compile to confirm that everything works fine. However, it doesn’t work because the TestRunner for TextTestResult implements the TestListener interface and does not declare the method endTest(…) . No problem; I simply add that method to the TestRunner to make everything run:
public class TestRunner implements TestListener...
public void endTest(TestResult testResult, Test test) {
}
3. Now I must make UITestResult ’s associated TestRunner implement TestListener and also make both TextTestResult and UITestResult communicate with their TestRunner instances using the TestListener interface. Here are a few of the changes:
public class TestRunner extends Frame implements TestListener ...
class UITestResult extends TestResult...
protected TestListener fRunner;
UITestResult( TestListener runner) {
fRunner= runner;
}
public class TextTestResult extends TestResult...
protected TestListener fRunner;
TextTestResult( TestListener runner) {
fRunner= runner;
}
I compile and test to confirm that these changes work.
4. Now I apply Pull Up Method [ F ] on every notification method in TextTestResult and UITestResult . This step is tricky because the methods I’ll be pulling up already exist on TestResult , the superclass of TextTestResult and UITestResult . To do this correctly, I need to merge code from the TestResult subclasses into TestResult . This yields the following changes:
public class TestResult...
protected TestListener fRunner;
public TestResult(TestListener runner) {
this();
fRunner= runner;
}
public TestResult() {
fFailures= new Vector(10);
fErrors= new Vector(10);
fRunTests= 0;
fStop= false;
}
public synchronized void addError(Test test, Throwable t) {
fErrors.addElement(new TestFailure(test, t));
fRunner.addError(this, test, t);
}
public synchronized void addFailure(Test test, Throwable t) {
fFailures.addElement(new TestFailure(test, t));
fRunner.addFailure(this, test, t);
}
public synchronized void endTest(Test test) {
fRunner.endTest(this, test);
}
public synchronized void startTest(Test test) {
fRunTests++;
fRunner.startTest(this, test);
}
package ui;
class UITestResult extends TestResult {
}
package textui;
class TextTestResult extends TestResult {
}
These changes pass the compiler with no problems.
5. I can now update the TestRunner instances to work directly with TestResult . For example, here is a change I make to textui.TestRunner :
package textui;
public class TestRunner implements TestListener...
protected TestResult createTestResult() {
return new TestResult(this) ;
}
protected void doRun(Test suite, boolean wait)...
TestResult result= createTestResult();
I make a similar change for ui.TestRunner . Finally, I delete both TextTestResult and UITestResult . I compile and test. The compile is fine, yet the tests fail miserably!
I do some exploring and a little debugging. I discover that my changes to TestResult can cause a null pointer exception when the fRunner field isn’t initialized. That circumstance occurs only when TestResult ’s original constructor is called because it doesn’t initialize fRunner . I correct this problem by insulating all calls to fRunner with the following conditional logic:
public class TestResult...
public synchronized void addError(Test test, Throwable t) {
fErrors.addElement(new TestFailure(test, t));
if (null != fRunner)
fRunner.addError(this, test, t);
}
public synchronized void addFailure(Test test, Throwable t) {
fFailures.addElement(new TestFailure(test, t));
if (null != fRunner)
fRunner.addFailure(this, test, t);
}
// etc.
The tests now pass and I’m happy again. The two TestRunner s are now observers of the subject, TestResult . At this point I can delete both TextTestResult and UITestResult because they are no longer being used.
6. The final step involves updating TestResult so it can hold onto and notify one or many observers. I declare a List of observers like so:
public class TestResult...
private List observers = new ArrayList();
Then I supply a method by which observers can add themselves to the observers list:
public class TestResult...
public void addObserver(TestListener testListener) {
observers.add(testListener);
}
Next, I update TestResult ’s notification methods so they work with the list of observers. Here’s one such update:
public class TestResult...
public synchronized void addError(Test test, Throwable t) {
fErrors.addElement(new TestFailure(test, t));
for (Iterator i = observers.iterator();i.hasNext();) {
TestListener observer = (TestListener)i.next();
observer.addError(this, test, t);
}
}
Finally, I update the TestRunner instances so they use the new addObserver() method rather than calling a TestResult constructor. Here’s the change I make to the textui.TestRunner class:
package textui;
public class TestRunner implements TestListener...
protected TestResult createTestResult() {
TestResult testResult = new TestResult();
testResult.addObserver(this);
return testResult;
}
After compiling and testing that these changes work, I can delete the now unused constructor in TestResult :
public class TestResult...
public TestResult(TestListener runner) {
this();
fRunner= runner;
}
That completes the refactoring to the Observer pattern. Now, TestResult notifications are no longer hard-coded to specific TestRunner instances, and TestResult can handle one or many observers of its results.
Unify Interfaces with Adapter
Clients interact with two classes, one of which
has a preferred interface.
Unify the interfaces with an Adapter.
Motivation
Refactoring to an Adapter [ DP ] is useful when all of the following conditions are true.
• Two classes do the same thing or similar things and have different interfaces.
• Client code could be simpler, more straightforward, and more succinct if the classes shared the same interface.
• You can’t simply alter the interface of one of the classes because it’s part of a third-party library, or it’s part of a framework that many other clients already use, or you lack source code.
The smell Alternative Classes with Different Interfaces ( 43 ) identifies when code could be communicating with alternative classes via a common interface but for some reason does not. A simple way to solve such a problem is to rename or move methods until the interfaces are the same. If that isn’t possible, say, because you’re working with code you can’t change (like a third-party class or interface, such as a DOM Element), you may need to consider implementing an Adapter.
Refactoring to an Adapter tends to generalize code and pave the way for other refactorings to remove duplicate code. Typically in this situation you have separate client code for communicating with alternative classes. By introducing an Adapter to unify the interfaces of the alternative classes, you generalize how clients interact with those alternative classes. After that, other refactorings, such as Form Template Method (205) , can help remove duplicated processing logic in client code. This generally results in simpler, easier-to-read client code.
Benefits and Liabilities
+ Removes or reduces duplicated code by enabling clients to communicate with alternative classes via the same interface.
+ Simplifies client code by making it possible to communicate with objects via a common interace.
+ Unifies how clients interact with alternative classes.
– Complicates a design when you can change the interface of a class rather than adapting it.
Mechanics
1. A client prefers one class’s interface over another, yet the client would like to communicate with both classes via a common interface. Apply Extract Interface [ F ] on the class with the client’s preferred interface to produce a common interface. Update any of this class’s methods that accept an argument of its own type to accept the argument as type common interface.
The remaining mechanics will now make it possible for the client to communicate with the adaptee (the class with the interface the client does not prefer) via the common interface.
Compile and test.
2. On the client class that uses the adaptee, apply Extract Class [ F ] to produce a primitive adapter (a class containing an adaptee field, a getter method for the adaptee, and a setter method or constructor parameter and code for setting the adaptee’s value).
3. Update all of the client class’s fields, local variables, and parameters of type adaptee to be of type adapter. This involves updating client calls on the adaptee to first obtain an adaptee reference from the adapter before invoking the adaptee method.
Compile and test.
4. Wherever the client invokes the same adaptee method (via the adapter’s getter method), apply Extract Method [ F ] to produce an adaptee invocation method. Parameterize this adaptee invocation method with an adaptee and make the method use the parameter value when it invokes the adaptee method. For example, a client makes an invocation on the adaptee, current , which is of type ElementAdapter :
ElementAdapter childNode = new ElementAdapter(...);
current.getElement().appendChild(childNode.getElement()); // invocation
The invocation on current is extracted to the method:
appendChild(current, childNode);
The method, appendChild(…) , looks like this:
private void appendChild(
ElementAdapter parent, ElementAdapter childNode) {
parent.getElement().appendChild(childNode.getElement());
}
Compile and test. Repeat this step for all client invocations of adaptee methods.
5. Apply Move Method [ F ] on an adaptee invocation method to move it from the client to the adapter. Every client call on the adaptee method should now go through the adapter.
When moving a method to the adapter, make it resemble the corresponding method in the common interface. If the body of a moved method requires a value from the client in order to compile, avoid adding it as a parameter to the method because that will make its method signature differ from the corresponding method on the common interface. Whenever possible, find a way to pass the value without disturbing the signature (e.g., pass it via the adapter’s constructor, or pass some other object reference to the adapter so it can obtain the value at runtime). If you must pass the missing value to the moved method as a parameter, you’ll need to revise the corresponding method signature on the common interface to make the two equivalent.
Compile and test.
Repeat for all adaptee invocation methods until the adapter contains methods with the same signatures as the methods on the common interface.
6. Update the adapter to formally “implement” the common interface. This should be a trivial step given the work already accomplished. Change all adapter methods that accept an argument of type adapter to accept the argument as type common interface.
Compile and test.
7. Update the client class so that all fields, local variables, and parameters use the common interface instead of the adapter’s type.
Compile and test.
Client code now communicates with both classes using the common interface. To further remove duplication in this client code, you can often apply refactorings like Form Template Method (205) and Introduce Polymorphic Creation with Factory Method (88) .
Example
This example relates to code that builds XML (see Replace Implicit Tree with Composite , 178; Encapsulate Composite with Builder , 96 ; and Introduce Polymorphic Creation with Factory Method , 88 ). In this case, there are two builders: XMLBuilder and DOMBuilder . Both extend from AbstractBuilder , which implements the OutputBuilder interface:
The code in XMLBuilder and DOMBuilder is largely the same, except that XMLBuilder collaborates with a class called TagNode , while DOMBuilder collaborates with objects that implement the Element interface:
public class DOMBuilder extends AbstractBuilder...
private Document document;
private Element root;
private Element parent;
private Element current;
public void addAttribute(String name, String value) {
current.setAttribute(name, value);
}
public void addBelow(String child) {
Element childNode = document.createElement(child);
current.appendChild(childNode);
parent = current;
current = childNode;
history.push(current);
}
public void addBeside(String sibling) {
if (current == root)
throw new RuntimeException(CANNOT_ADD_BESIDE_ROOT);
Element siblingNode = document.createElement(sibling);
parent.appendChild(siblingNode);
current = siblingNode;
history.pop();
history.push(current);
}
public void addValue(String value) {
current.appendChild(document.createTextNode(value));
}
And here’s the similar code from XMLBuilder :
public class XMLBuilder extends AbstractBuilder...
private TagNode rootNode;
private TagNode currentNode;
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);
}
public void addAttribute(String name, String value) {
currentNode.addAttribute(name, value);
}
public void addValue(String value) {
currentNode.addValue(value);
}
These methods, and numerous others that I’m not showing in order to conserve space, are nearly the same in DOMBuilder and XMLBuilder , except for the fact that each builder works with either TagNode or Element . The goal of this refactoring is to create a common interface for TagNode and Element so that the duplication in the builder methods can be eliminated.
1. My first task is to create a common interface. I base this interface on the TagNode class because its interface is the one I prefer for client code. TagNode has about ten methods, five of which are public. The common interface needs only three of these methods. I apply Extract Interface [ F ] to obtain the desired result:
public interface XMLNode {
public abstract void add(XMLNode childNode);
public abstract void addAttribute(String attribute, String value);
public abstract void addValue(String value);
}
public class TagNode implements XMLNode ...
public void add( XMLNode childNode) {
children().add(childNode);
}
// etc.
I compile and test to make sure these changes worked.
2. Now I begin working on the DOMBuilder class. I want to apply Extract Class [ F ] to DOMBuilder in order to produce an adapter for Element . This results in the creation of the following class:
public class ElementAdapter {
Element element;
public ElementAdapter(Element element) {
this.element = element;
}
public Element getElement() {
return element;
}
}
3. Now I update all of the Element fields in DOMBuilder to be of type ElementAdapter and update any code that needs to be updated because of this change:
public class DOMBuilder extends AbstractBuilder...
private Document document;
private ElementAdapter rootNode;
private ElementAdapter parentNode;
private ElementAdapter currentNode;
public void addAttribute(String name, String value) {
currentNode. getElement() .setAttribute(name, value);
}
public void addChild(String childTagName) {
ElementAdapter childNode =
new ElementAdapter( document.createElement(childTagName) ) ;
currentNode. getElement() .appendChild(childNode .getElement() );
parentNode = currentNode;
currentNode = childNode;
history.push(currentNode);
}
public void addSibling(String siblingTagName) {
if (currentNode == root)
throw new RuntimeException(CANNOT_ADD_BESIDE_ROOT);
ElementAdapter siblingNode =
new ElementAdapter( document.createElement(siblingTagName) ) ;
parentNode. getElement() .appendChild(siblingNode .getElement() );
currentNode = siblingNode;
history.pop();
history.push(currentNode);
}
4. Now I create an adaptee invocation method for each adaptee method called by DOMBuilder . I use Extract Method [ F ] for this purpose, making sure that each extracted method takes an adaptee as an argument and uses that adaptee in its body:
public class DOMBuilder extends AbstractBuilder...
public void addAttribute(String name, String value) {
addAttribute(currentNode, name, value);
}
private void addAttribute(ElementAdapter current, String name, String value) {
currentNode.getElement().setAttribute(name, value);
}
public void addChild(String childTagName) {
ElementAdapter childNode =
new ElementAdapter(document.createElement(childTagName));
add(currentNode, childNode);
parentNode = currentNode;
currentNode = childNode;
history.push(currentNode);
}
private void add(ElementAdapter parent, ElementAdapter child) {
parent.getElement().appendChild(child.getElement());
}
public void addSibling(String siblingTagName) {
if (currentNode == root)
throw new RuntimeException(CANNOT_ADD_BESIDE_ROOT);
ElementAdapter siblingNode =
new ElementAdapter(document.createElement(siblingTagName));
add(parentNode, siblingNode);
currentNode = siblingNode;
history.pop();
history.push(currentNode);
}
public void addValue(String value) {
addValue(currentNode, value);
}
private void addValue(ElementAdapter current, String value) {
currentNode.getElement().appendChild(document.createTextNode(value));
}
5. I can now move each adaptee invocation method to ElementAdapter using Move Method [ F ]. I’d like the moved method to resemble the corresponding methods in the common interface, XMLNode , as much as possible. This is easy to do for every method except addValue(…) , which I’ll address in a moment. Here are the results after moving the addAttribute(…) and add(…) methods:
public class ElementAdapter {
Element element;
public ElementAdapter(Element element) {
this.element = element;
}
public Element getElement() {
return element;
}
public void addAttribute(String name, String value) {
getElement().setAttribute(name, value);
}
public void add(ElementAdapter child) {
getElement().appendChild(child.getElement());
}
}
And here are examples of changes in DOMBuilder as a result of the move:
public class DOMBuilder extends AbstractBuilder...
public void addAttribute(String name, String value) {
currentNode.addAttribute(name, value);
}
public void addChild(String childTagName) {
ElementAdapter childNode =
new ElementAdapter(document.createElement(childTagName));
currentNode.add(childNode);
parentNode = currentNode;
currentNode = childNode;
history.push(currentNode);
}
// etc.
The addValue(…) method is more tricky to move to ElementAdapter because it relies on a field within ElementAdapter called document :
public class DOMBuilder extends AbstractBuilder...
private Document document;
public void addValue(ElementAdapter current, String value) {
current.getElement().appendChild( document. createTextNode(value));
}
I don’t want to pass a field of type Document to the addValue(…) method on ElementAdapter because if I do so, that method will move further away from the target, which is the addValue(…) method on XMLNode :
public interface XMLNode...
public abstract void addValue(String value);
At this point I decide to pass an instance of Document to ElementAdapter via its constructor:
public class ElementAdapter...
Element element;
Document document;
public ElementAdapter(Element element, Document document ) {
this.element = element;
this.document = document;
}
And I make the necessary changes in DOMBuilder to call this updated constructor. Now I can easily move addValue(…) :
public class ElementAdapter...
public void addValue(String value) {
getElement().appendChild(document.createTextNode(value));
}
6. Now I make ElementAdapter implement the XMLNode interface. This step is straightforward, except for a small change to the add(…) method to allow it to call the getElement() method, which is not part of the XMLNode interface:
public class ElementAdapter implements XMLNode ...
public void add(XMLNode child) {
ElementAdapter childElement = (ElementAdapter)child;
getElement().appendChild( childElement. getElement());
}
7. The final step is to update DOMBuilder so that all of its ElementAdapter fields, local variables, and parameters change their type to XMLNode :
public class DOMBuilder extends AbstractBuilder...
private Document document;
private XMLNode rootNode;
private XMLNode parentNode;
private XMLNode currentNode;
public void addChild(String childTagName) {
XMLNode childNode =
new ElementAdapter(document.createElement(childTagName), document);
...
}
protected void init(String rootName) {
document = new DocumentImpl();
rootNode = new ElementAdapter(document.createElement(rootName), document);
document.appendChild( ((ElementAdapter)rootNode) .getElement());
...
}
At this point, by adapting Element in DOMBuilder , the code in XMLBuilder is so similar to that of DOMBuilder that it makes sense to pull up the similar code to AbstractBuilder . I achieve that by applying Form Template Method (205) and Introduce Polymorphic Creation with Factory Method (88) . The following diagram shows the result.
Extract Adapter
One class adapts multiple versions of a
component, library, API, or other entity.
Extract an Adapter for a single version of the
component, library, API, or other entity.
Motivation
While software must often support multiple versions of a component, library, or API, code that handles these versions doesn’t have to be a confusing mess. Yet I routinely encounter code that attempts to handle multiple versions of something by overloading classes with version-specific state variables, constructors, and methods. Accompanying such code are comments like “This is for version X—please delete this code when we move to version Y!” Sure, like that’s ever going to happen. Most programmers won’t delete the version X code for fear that something they don’t know about still relies on it. So the comments don’t get deleted, and many versions supported by the code remain in the code.
Now consider an alternative: for each version of something you need to support, create a separate class. The class name could even include the version number of what it supports, to be really explicit about what it does. Such classes are called Adapters [ DP ]. Adapters implement a common interface and are responsible for functioning correctly with one (and usually only one) version of some code. Adapters make it easy for client code to swap in support for one library or API version or another. And programmers routinely rely on runtime information to configure their programs with the correct Adapter.
I refactor to Adapters fairly often. I like Adapters because they let me decide how I want to communicate with other people’s code. In a fast-changing world, Adapters help me stay insulated from highly useful but rapidly changing APIs, such as those springing eternally from the open source world.
In some cases, Adapters may adapt too much. For example, a client needs access to behavior on an adaptee, yet it cannot access that behavior because it only has access to the adaptee via an Adapter. In that case, the Adapter must be redesigned to accommodate client needs.
Systems that depend on multiple versions of a component, library, or API tend to have a good deal of version-dependent logic scattered throughout the code (a sure sign of the Solution Sprawl smell, 43 ). While you wouldn’t want to complicate a design by refactoring to Adapter too early, it’s useful to apply this refactoring as soon as you find complexity, propagating conditionality, or a maintanance issue resulting from code written to handle multiple versions.
Adapter and Facade
The Adapter pattern is often confused with the Facade pattern [ DP ]. Both patterns make code easier to use, yet each operates on different levels: Adapters adapt objects, while Facades adapt entire subsystems.
Facades are often used to communicate with legacy systems. For example, consider an organization with a sophisticated, two-million-line COBOL system that continually generates a good deal of the organization’s income. Such a system may be hard to extend or maintain because it was never refactored. Yet because it contains important functionality, new systems must depend on it.
Facades are useful in this context. They provide new systems with simpler views of poorly designed or highly complex legacy code. These new systems can communicate with Facade objects, which in turn do all the hard work of communicating with the legacy code.
Over time, teams can rewrite entire legacy subsystems by simply writing new implementations for each Facade. The process goes like this:
• Identify a subsystem of your legacy system.
• Write Facades for that subsystem.
• Write new client programs that rely on calls to the Facades.
• Create versions of each Facade using newer technologies.
• Test that the newer and older Facades function identically.
• Update client code to use the new Facades.
• Repeat for the next subsystem.
Benefits and Liabilities
+ Isolates differences in versions of a component, library, or API.
+ Makes classes responsible for adapting only one version of something.
+ Provides insulation from frequently changing code.
– Can shield a client from important behavior that isn’t available on the Adapter.
Mechanics
There are different ways to go about this refactoring, depending on how your code looks before you begin. For example, if you have a class that uses a lot of conditional logic to handle multiple versions of something, it’s likely that you can create Adapters for each version by repeatedly applying Replace Conditional with Polymorphism [ F ]. If you have a case like the one shown in the code sketch—in which an existing Adapter class supports multiple versions of a library with version-specific variables and methods—you’ll extract multiple Adapters using a different approach. Here I outline the mechanics for this latter scenario.
1. Identify an overburdened adapter , a class that adapts too many versions of something.
2. Create a new adaper , a class produced by applying Extract Subclass [ F ] or Extract Class [ F ] for a single version of the multiple versions supported by the overburdened adapter. Copy or move all instance variables and methods used exclusively for that version into the new adapter.
To do this, you may need to make some private members of the overburdened adapter public or protected. It may also be necessary to initialize some instance variables via a constructor in the new adapter, which will necessitate updates to callers of the new constructor.
Compile and test.
3. Repeat step 2 until the overburdened adapter has no more version-specific code.
4. Remove any duplication found in the new adapters by applying refactorings like Pull Up Method [ F ] and Form Template Method (205) .
Compile and test.
Example
The code I’ll refactor in this example, which was depicted in the code sketch at the beginning of this refactoring, is based on real-world code that handles queries to a database using a third-party library. To protect the innocent, I’ve renamed that library SD , which stands for SuperDatabase.
1. I begin by identifying an Adapter that is overburdened with support for multiple versions of SuperDatabase. This class, called Query , provides support for SuperDatabase versions 5.1 and 5.2.
In the following code listing, notice the version-specific instance variables, duplicate login() methods, and conditional code in doQuery() :
public class Query...
private SDLogin sdLogin; // needed for SD version 5.1
private SDSession sdSession; // needed for SD version 5.1
private SDLoginSession sdLoginSession; // needed for SD version 5.2
private boolean sd52; // tells if we’re running under SD 5.2
private SDQuery sdQuery; // this is needed for SD versions 5.1 & 5.2
// this is a login for SD 5.1
// NOTE: remove this when we convert all aplications to 5.2
public void login(String server, String user, String password) throws QueryException {
sd52 = false;
try {
sdSession = sdLogin.loginSession(server, user, password);
} catch (SDLoginFailedException lfe) {
throw new QueryException(QueryException.LOGIN_FAILED,
"Login failure\n" + lfe, lfe);
} catch (SDSocketInitFailedException ife) {
throw new QueryException(QueryException.LOGIN_FAILED,
"Socket fail\n" + ife, ife);
}
}
// 5.2 login
public void login(String server, String user, String password,
String sdConfigFileName) throws QueryException {
sd52 = true;
sdLoginSession = new SDLoginSession(sdConfigFileName, false);
try {
sdLoginSession.loginSession(server, user, password);
} catch (SDLoginFailedException lfe) {
throw new QueryException(QueryException.LOGIN_FAILED,
"Login failure\n" + lfe, lfe);
} catch (SDSocketInitFailedException ife) {
throw new QueryException(QueryException.LOGIN_FAILED,
"Socket fail\n" + ife, ife);
} catch (SDNotFoundException nfe) {
throw new QueryException(QueryException.LOGIN_FAILED,
"Not found exception\n" + nfe, nfe);
}
}
public void doQuery() throws QueryException {
if (sdQuery != null)
sdQuery.clearResultSet();
if (sd52)
sdQuery = sdLoginSession.createQuery(SDQuery.OPEN_FOR_QUERY);
else
sdQuery = sdSession.createQuery(SDQuery.OPEN_FOR_QUERY);
executeQuery();
}
2. Because Query doesn’t already have subclasses, I decide to apply Extract Subclass [ F ] to isolate code that handles SuperDatabase 5.1 queries. My first step is to define the subclass and create a constructor for it:
class QuerySD51 extends Query {
public QuerySD51() {
super();
}
}
Next, I find all client calls to Query ’s constructor and, where appropriate, change the code to call the QuerySD51 constructor. For example, I find the following client code, which holds onto a Query field called query :
public void loginToDatabase(String db, String user, String password)...
query = new Query();
try {
if (usingSDVersion52()) {
query.login(db, user, password, getSD52ConfigFileName()); // Login to SD 5.2
} else {
query.login(db, user, password); // Login to SD 5.1
}
...
} catch(QueryException qe)...
I change this to:
public void loginToDatabase(String db, String user, String password)...
query = new Query();
try {
if (usingSDVersion52()) {
query = new Query();
query.login(db, user, password, getSD52ConfigFileName()); // Login to SD 5.2
} else {
query = new QuerySD51();
query.login(db, user, password); // Login to SD 5.1
}
...
} catch(QueryException qe) {
Next, I apply Push Down Method [ F ] and Push Down Field [ F ] to outfit QuerySD51 with the methods and instance variables it needs. During this step, I have to be careful to consider the clients that make calls to public Query methods, for if I move a public method like login() from Query to QuerySD51 , the caller will not be able to call the public method unless its type is changed to QuerySD51 . Because I don’t want to make such changes to client code, I proceed cautiously, sometimes copying and modifying public methods instead of completely removing them from Query . While I do this, I generate duplicate code, but that doesn’t bother me now—I’ll get rid of the duplication in the final step of this refactoring.
class Query...
private SDLogin sdLogin;
private SDSession sdSession;
protected SDQuery sdQuery;
// this is a login for SD 5.1
public void login(String server, String user, String password) throws QueryException {
// I make this a do-nothing method
}
public void doQuery() throws QueryException {
if (sdQuery != null)
sdQuery.clearResultSet();
if (sd52)
sdQuery = sdLoginSession.createQuery(SDQuery.OPEN_FOR_QUERY);
else
sdQuery = sdSession.createQuery(SDQuery.OPEN_FOR_QUERY);
executeQuery();
}
class QuerySD51 {
private SDLogin sdLogin;
private SDSession sdSession;
public void login(String server, String user, String password) throws QueryException {
sd52 = false;
try {
sdSession = sdLogin.loginSession(server, user, password);
} catch (SDLoginFailedException lfe) {
throw new QueryException(QueryException.LOGIN_FAILED,
"Login failure\n" + lfe, lfe);
} catch (SDSocketInitFailedException ife) {
throw new QueryException(QueryException.LOGIN_FAILED,
"Socket fail\n" + ife, ife);
}
}
public void doQuery() throws QueryException {
if (sdQuery != null)
sdQuery.clearResultSet();
if (sd52)
sdQuery = sdLoginSession.createQuery(SDQuery.OPEN_FOR_QUERY);
else
sdQuery = sdSession.createQuery(SDQuery.OPEN_FOR_QUERY);
executeQuery();
}
}
I compile and test that QuerySD51 works. No problems.
3. Next, I repeat step 2 to create QuerySD52 . Along the way, I can make the Query class abstract, along with the doQuery() method. Here’s what I have now:
Query is now free of version-specific code, but it is not free of duplicate code.
4. Now I go on a mission to remove duplication. I quickly find some in the two implementations of doQuery() :
abstract class Query...
public abstract void doQuery() throws QueryException;
class QuerySD51...
public void doQuery() throws QueryException {
if (sdQuery != null)
sdQuery.clearResultSet();
sdQuery = sdSession.createQuery(SDQuery.OPEN_FOR_QUERY);
executeQuery();
}
class QuerySD52...
public void doQuery() throws QueryException {
if (sdQuery != null)
sdQuery.clearResultSet();
sdQuery = sdLoginSession.createQuery(SDQuery.OPEN_FOR_QUERY);
executeQuery();
}
Each of these methods simply initializes the sdQuery instance in a different way. This means that I can apply Introduce Polymorphic Creation with Factory Method (88) and Form Template Method (205) to create a single superclass version of doQuery() :
public abstract class Query...
protected abstract SDQuery createQuery(); // a Factory Method [DP]
public void doQuery() throws QueryException { // a Template Method [DP]
if (sdQuery != null)
sdQuery.clearResultSet();
sdQuery = createQuery(); // call to the Factory Method
executeQuery();
}
class QuerySD51...
protected SDQuery createQuery() {
return sdSession.createQuery(SDQuery.OPEN_FOR_QUERY);
}
class QuerySD52...
protected SDQuery createQuery() {
return sdLoginSession.createQuery(SDQuery.OPEN_FOR_QUERY);
}
After compiling and testing the changes, I now face a more obvious duplication problem: Query still contains the SD 5.1 and 5.2 login() methods, even though they no longer do anything (the real login work is now handled by the subclasses). The signatures for these two login() method are identical, except for one parameter:
// SD 5.1 login
public void login(String server, String user, String password) throws QueryException...
// SD 5.2 login
public void login(String server, String user,
String password, String sdConfigFileName ) throws QueryException...
I decide to make the login() signatures the same, by simply supplying QuerySD52 with the sdConfigFileName information via its constructor:
class QuerySD52...
private String sdConfigFileName;
public QuerySD52(String sdConfigFileName) {
super();
this.sdConfigFileName = sdConfigFileName;
}
Now Query has only one abstract login() method:
abstract class Query...
public abstract void login(String server, String user,
String password) throws QueryException...
Client code is updated as follows:
public void loginToDatabase(String db, String user, String password)...
if (usingSDVersion52())
query = new QuerySD52(getSD52ConfigFileName());
else
query = new QuerySD51();
try {
query.login(db, user, password);
...
} catch(QueryException qe)...
I’m nearly done. Because Query is an abstract class, I decide to rename it AbstractQuery , which communicates more about its nature. But making that name change necessitates changing client code to declare variables of type AbstractQuery instead of Query . I don’t want to do that, so I apply Extract Interface [ F ] on AbstractQuery to obtain a Query interface that AbstractQuery can implement:
interface Query {
public void login(String server, String user, String password) throws QueryException;
public void doQuery() throws QueryException;
}
abstract class Abstract Query implements Query ...
public abstract void login(String server, String user,
String password) throws QueryException…
Now, subclasses of AbstractQuery implement login() , while AbstractQuery doesn’t even need to declare the login() method because it is an abstract class.
I compile and test to see that everything works as planned. Each version of SuperDatabase is now fully adapted. The code is smaller and treats each version in a more uniform way, all of which makes it easier to:
• See similarities and differences between the versions
• Remove support for older, unused versions
• Add support for newer versions
Variations
Adapting with Anonymous Inner Classes
The first version of Java (JDK 1.0) included an interface called Enumeration , which was used to iterate over collections like Vector and Hashtable collections. Over time, better collections classes were added to the JDK, along with a new interface called Iterator . To make it possible to interoperate with code written using the Enumeration interface, the JDK provided the following Creation Method, which used Java’s anonymous inner class capability to adapt an Iterator with an Enumeration :
public class Collections...
public static Enumeration enumeration(final Collection c) {
return new Enumeration() {
Iterator i = c.iterator();
public boolean hasMoreElements() {
return i.hasNext();
}
public Object nextElement() {
return i.next();
}
};
}
Replace Implicit Language with Interpreter
Numerous methods on a class combine elements
of an implicit language.
Define classes for elements of the implicit language so that
instances may be combined to form interpretable expressions.
Motivation
An Interpreter [ DP ] is useful for interpreting simple languages. A simple language is one that has a grammar that may be modeled using a small number of classes. Sentences and expressions in simple languages are formed by combining instances of the grammar’s classes, typically using a Composite [ DP ] structure.
Programmers divide into two camps with respect to the Interpreter pattern: those who are comfortable implementing it and those who aren’t. However, whether or not you’re comfortable with terms like parse trees and abstract syntax trees, terminal and nonterminal expressions, implementing an Interpreter is only slightly more complicated than implementing a Composite. The trick is knowing when you need an Interpreter.
You don’t need an Interpreter for complex languages or for really simple ones. For complex languages, it’s usually best to use a tool (such as JavaCC) that supports parsing, grammar definition, and interpretation. For example, on one project, my colleagues and I used a parser generator to produce a grammar that had more than 20 classes—too many to comfortably program by hand using the Interpreter pattern. On another project, our language’s grammar was so simple and uniform that we didn’t use any classes to interpret each expression in the language.
If a language’s grammar requires fewer than a dozen classes to implement, it may be useful to model using the Interpreter pattern. Search expressions for objects or database values often have such grammars. Typical searches require the use of words like “and,” “not,” and “or” (called nonterminal expressions ), as well as values like “$10.00,” “small,” and “blue” (called terminal expressions ). For example:
• Find products below $10.00.
• Find products below $10.00 and not white.
• Find products that are blue, small, and below $20.00.
Such search expressions are often programmed into systems without using an explicit language. Consider this class:
ProductFinder...
public List byColor(Color colorOfProductToFind)...
public List byPrice(float priceLimit)...
public List bySize(int sizeToFind)...
public List belowPrice(float price) ...
public List belowPriceAvoidingAColor(float price)...
public List byColorAndBelowPrice(Color color, float price)...
public List byColorSizeAndBelowPrice(Color color, int size, float price)...
Programmed in this way, a product-finding language is implicit: present, but unexpressed. Two problems result from this approach. First, you must create a new method for each new combination of product criteria. Second, the product-finding methods tend to duplicate a lot of product-finding code. An Interpreter solution (shown in the Example section) is better because it can support a large variety of product queries with a little over a half-dozen small classes and no duplication of code.
Refactoring to an Interpreter involves the start-up cost of defining classes for a grammar and altering client code to compose instances of the classes to represent language expressions. Is that price worth it? It is if the alternative is lots of duplicated code to handle a combinatorial explosion of implicit language expressions, such as the many finder methods in the ProductFinder class just shown.
Two patterns that make heavy use of Interpreter are Specification [ Evans ] and Query Object [ Fowler, PEAA ]. Both model search expressions using simple grammars and compositions of objects. These patterns provide a useful way to separate a search expression from its representation. For example, a Query Object models a query in a generic way, which allows you to convert it into a SQL representation (or some other representation) when you want to perform an actual database query.
Interpreters are often used within systems to allow for the runtime configuration of behavior. For example, a system may accept a user’s query preferences through a user interface and then dynamically produce an interpretable object structure that represents the query. In this way, Interpreters can provide a level of power and flexibility that isn’t possible when all behavior in a system is static and can’t be configured dynamically.
Benefits and Liabilities
+ Supports combinations of language elements better than an implicit language does.
+ Requires no new code to support new combinations of language elements.
+ Allows for runtime configuration of behavior.
– Has a start-up cost for defining a grammar and changing client code to use it.
– Requires too much programming when your language is complex.
– Complicates a design when a language is simple.
Mechanics
These mechanics are heavily weighted towards the use of Interpreter in the context of the Specification and Query Object patterns because most of the Interpreter implementations I’ve written or encountered have been implementations of those two patterns. In this context, an implicit language is modeled using numerous object selection methods, each of which iterates across a collection to select a specific set of objects.
1. Find an object selection method that relies on a single criterion argument (e.g., double targetPrice ) to find a set of objects. Create a concrete specification class for the criterion argument, which accepts the argument’s value in a constructor and provides a getter method for it. Within the object selection method, declare and instantiate a variable of type concrete specification and update the code so access to the criterion is obtained via the concrete specification’s getter method.
Name your concrete specification by what it does (e.g., ColorSpec helps find products by a given color).
If your object selection method relies on multiple criteria for its object selection, apply this step and step 2 for each piece of the criterion. In step 4, you’ll deal with composing concrete specifications into composite specifications.
Compile and test that object selection still works correctly.
2. Apply Extract Method [ F ] on the conditional statement in the object selection method to produce a method called isSatisfiedBy() , which should have a Boolean result. Now apply Move Method [ F ] to move this method to the concrete specification.
Create a specification superclass (if you haven’t already created one) by applying Extract Superclass [ F ] on the concrete specification. Make this superclass abstract and have it declare a single abstract method for isSatisfiedBy(…) .
Compile and test that object selection still works correctly.
3. Repeat steps 1 and 2 for similar object selection methods, including methods that rely on the criteria for object selection.
4. If you have an object selection method that relies on multiple concrete specifications (i.e., the method now instantiates more than one concrete specification for use in its object selection logic), apply a modified version of step 1 by creating a composite specification (a class composed of the concrete specifications instantiated inside the object selection method). You may pass the concrete specifications to the composite specification via its constructor or, if there are many concrete specifications, supply an add(…) method on the composite specification.
Then apply step 2 on the object selection method’s conditional statement to move the logic to the composite specification’s isSatisfiedBy(…) method. Make the composite specification extend from the specification superclass.
5. Each object selection method now works with one specification object (i.e., one concrete specification or one composite specification). In addition, the object selection methods are identical except for specification creation code. Remove duplicated code in the object selection methods by applying Extract Method [ F ] on the identical code from any object selection method. Name the extracted method something like selectBy(…) and have it accept one argument of type specification interface and return a collection of objects (e.g., public List selectBy(Spec spec) ).
Compile and test.
Adjust all object selection methods to call the selectBy(…) method.
Compile and test.
6. Apply Inline Method [ F ] on every object selection method.
Compile and test.
Example
The code sketch and the Motivation section already gave you an introduction to this example, which is inspired from an inventory management system. That system’s Finder classes ( AccountFinder , InvoiceFinder , ProductFinder , and so forth) eventually came to suffer from a Combinatorial Explosion smell ( 45 ), which necessitated the refactoring to Specification. It’s worth noting that this does not reveal a problem with Finder classes: the point is that a time may come when a refactoring to Specification is justified.
I begin by studying the tests and code for a ProductFinder that is in need of this refactoring. I’ll start with the test code. Before any test can run, I need a ProductRepository object that’s filled with various Product objects and a ProductFinder object that knows about the ProductRepository :
public class ProductFinderTests extends TestCase...
private ProductFinder finder;
private Product fireTruck =
new Product("f1234", "Fire Truck",
Color.red, 8.95f, ProductSize.MEDIUM);
private Product barbieClassic =
new Product("b7654", "Barbie Classic",
Color.yellow, 15.95f, ProductSize.SMALL);
private Product frisbee =
new Product("f4321", "Frisbee",
Color.pink, 9.99f, ProductSize.LARGE);
private Product baseball =
new Product("b2343", "Baseball",
Color.white, 8.95f, ProductSize.NOT_APPLICABLE);
private Product toyConvertible =
new Product("p1112", "Toy Porsche Convertible",
Color.red, 230.00f, ProductSize.NOT_APPLICABLE);
protected void setUp() {
finder = new ProductFinder(createProductRepository());
}
private ProductRepository createProductRepository() {
ProductRepository repository = new ProductRepository();
repository.add(fireTruck);
repository.add(barbieClassic);
repository.add(frisbee);
repository.add(baseball);
repository.add(toyConvertible);
return repository;
}
The “toy” products above work fine for test code. Of course, the production code uses real product objects, which are obtained using object-relational mapping logic.
Now I look at a few simple tests and the implementation code that satisfies them. The testFindByColor() method checks whether the ProductFinder.byColor(…) method correctly finds red toys, while testFindByPrice() checks whether ProductFinder.byPrice(…) correctly finds toys at a given price:
public class ProductFinderTests extends TestCase...
public void testFindByColor() {
List foundProducts = finder.byColor(Color.red);
assertEquals("found 2 red products", 2, foundProducts.size());
assertTrue("found fireTruck", foundProducts.contains(fireTruck));
assertTrue(
"found Toy Porsche Convertible",
foundProducts.contains(toyConvertible));
}
public void testFindByPrice() {
List foundProducts = finder.byPrice(8.95f);
assertEquals("found products that cost $8.95", 2, foundProducts.size());
for (Iterator i = foundProducts.iterator(); i.hasNext();) {
Product p = (Product) i.next();
assertTrue(p.getPrice() == 8.95f);
}
}
Here’s the implementation code that satisfies these tests:
public class ProductFinder...
private ProductRepository repository;
public ProductFinder(ProductRepository repository) {
this.repository = repository;
}
public List byColor(Color colorOfProductToFind) {
List foundProducts = new ArrayList();
Iterator products = repository.iterator();
while (products.hasNext()) {
Product product = (Product) products.next();
if (product.getColor().equals(colorOfProductToFind))
foundProducts.add(product);
}
return foundProducts;
}
public List byPrice(float priceLimit) {
List foundProducts = new ArrayList();
Iterator products = repository.iterator();
while (products.hasNext()) {
Product product = (Product) products.next();
if (product.getPrice() == priceLimit)
foundProducts.add(product);
}
return foundProducts;
}
There’s plenty of duplicate code in these two methods. I’ll be getting rid of that duplication during this refactoring. Meanwhile, I explore some more tests and code that are involved in the Combinatorial Explosion problem. Below, one test is concerned with finding Product instances by color, size, and below a certain price, while the other test is concerned with finding Product instances by color and above a certain price:
public class ProductFinderTests extends TestCase...
public void testFindByColorSizeAndBelowPrice() {
List foundProducts =
finder.byColorSizeAndBelowPrice(Color.red, ProductSize.SMALL, 10.00f);
assertEquals(
"found no small red products below $10.00",
0,
foundProducts.size());
foundProducts =
finder.byColorSizeAndBelowPrice(Color.red, ProductSize.MEDIUM, 10.00f);
assertEquals(
"found firetruck when looking for cheap medium red toys",
fireTruck,
foundProducts.get(0));
}
public void testFindBelowPriceAvoidingAColor() {
List foundProducts =
finder.belowPriceAvoidingAColor(9.00f, Color.white);
assertEquals(
"found 1 non-white product < $9.00",
1,
foundProducts.size());
assertTrue("found fireTruck", foundProducts.contains(fireTruck));
foundProducts = finder.belowPriceAvoidingAColor(9.00f, Color.red);
assertEquals(
"found 1 non-red product < $9.00",
1,
foundProducts.size());
assertTrue("found baseball", foundProducts.contains(baseball));
}
Here’s how the implementation code looks for these tests:
public class ProductFinder...
public List byColorSizeAndBelowPrice(Color color, int size, float price) {
List foundProducts = new ArrayList();
Iterator products = repository.iterator();
while (products.hasNext()) {
Product product = (Product) products.next();
if (product.getColor() == color
&& product.getSize() == size
&& product.getPrice() < price)
foundProducts.add(product);
}
return foundProducts;
}
public List belowPriceAvoidingAColor(float price, Color color) {
List foundProducts = new ArrayList();
Iterator products = repository.iterator();
while (products.hasNext()) {
Product product = (Product) products.next();
if (product.getPrice() < price && product.getColor() != color)
foundProducts.add(product);
}
return foundProducts;
}
Again, I see plenty of duplicate code because each of the specific finder methods iterates over the same repository and selects just those Product instances that match the specified criteria. I’m now ready to begin the refactoring.
1. The first step is to find an object selection method that relies on a criterion argument for its selection logic. The ProductFinder method byColor(Color colorOfProductToFind) meets this requirement:
public class ProductFinder...
public List byColor(Color colorOfProductToFind) {
List foundProducts = new ArrayList();
Iterator products = repository.iterator();
while (products.hasNext()) {
Product product = (Product) products.next();
if (product.getColor().equals(colorOfProductToFind))
foundProducts.add(product);
}
return foundProducts;
}
I create a concrete specification class for the criterion argument, Color colorOfProductToFind . I call this class ColorSpec . It needs to hold onto a Color field and provide a getter method for it:
public class ColorSpec {
private Color colorOfProductToFind;
public ColorSpec(Color colorOfProductToFind) {
this.colorOfProductToFind = colorOfProductToFind;
}
public Color getColorOfProductToFind() {
return colorOfProductToFind;
}
}
Now I can add a variable of type ColorSpec to the byColor(…) method and replace the reference to the parameter, colorOfProductToFind , with a reference to the specification’s getter method:
public List byColor(Color colorOfProductToFind) {
ColorSpec spec = new ColorSpec(colorOfProductToFind);
List foundProducts = new ArrayList();
Iterator products = repository.iterator();
while (products.hasNext()) {
Product product = (Product) products.next();
if (product.getColor().equals( spec.getColorOfProductToFind() ))
foundProducts.add(product);
}
return foundProducts;
}
After these changes, I compile and run my tests. Here’s one such test:
public void testFindByColor() {
List foundProducts = finder.byColor(Color.red);
assertEquals("found 2 red products", 2, foundProducts.size());
assertTrue("found fireTruck", foundProducts.contains(fireTruck));
assertTrue("found Toy Porsche Convertible", foundProducts.contains(toyConvertible));
}
2. Now I’ll apply Extract Method [ F ] to extract the conditional statement in the while loop to an isSatisfiedBy(…) method:
public List byColor(Color colorOfProductToFind) {
ColorSpec spec = new ColorSpec(colorOfProductToFind);
List foundProducts = new ArrayList();
Iterator products = repository.iterator();
while (products.hasNext()) {
Product product = (Product) products.next();
if ( isSatisfiedBy(spec, product) )
foundProducts.add(product);
}
return foundProducts;
}
private boolean isSatisfiedBy(ColorSpec spec, Product product) {
return product.getColor().equals(spec.getColorOfProductToFind());
}
The isSatisfiedBy(…) method can now be moved to ColorSpec by applying Move Method [ F ]:
public class ProductFinder...
public List byColor(Color colorOfProductToFind) {
ColorSpec spec = new ColorSpec(colorOfProductToFind);
List foundProducts = new ArrayList();
Iterator products = repository.iterator();
while (products.hasNext()) {
Product product = (Product) products.next();
if ( spec.isSatisfiedBy(product) )
foundProducts.add(product);
}
return foundProducts;
}
public class ColorSpec...
public boolean isSatisfiedBy(Product product) {
return product.getColor().equals(getColorOfProductToFind());
}
Finally, I create a specification superclass by applying Extract Superclass [ F ] on ColorSpec :
public abstract class Spec {
public abstract boolean isSatisfiedBy(Product product);
}
I make ColorSpec extend this class:
public class ColorSpec extends Spec ...
I compile and test to see that Product instances can still be selected by a given color correctly. Everything works fine.
3. Now I repeat steps 1 and 2 for similar object selection methods. This includes methods that work with criteria (i.e., multiple pieces of criterion). For example, the byColorAndBelowPrice(…) method accepts two arguments that act as criteria for selecting Product instances out of the repository:
public List byColorAndBelowPrice(Color color, float price) {
List foundProducts = new ArrayList();
Iterator products = repository.iterator();
while (products.hasNext()) {
Product product = (Product)products.next();
if (product.getPrice() < price && product.getColor() == color)
foundProducts.add(product);
}
return foundProducts;
}
By implementing steps 1 and 2, I end up with the BelowPriceSpec class:
public class BelowPriceSpec extends Spec {
private float priceThreshold;
public BelowPriceSpec(float priceThreshold) {
this.priceThreshold = priceThreshold;
}
public boolean isSatisfiedBy(Product product) {
return product.getPrice() < getPriceThreshold();
}
public float getPriceThreshold() {
return priceThreshold;
}
}
Now I can create a new version of byColorAndBelowPrice(…) that works with the two concrete specifications:
public List byColorAndBelowPrice(Color color, float price) {
ColorSpec colorSpec = new ColorSpec(color);
BelowPriceSpec priceSpec = new BelowPriceSpec(price);
List foundProducts = new ArrayList();
Iterator products = repository.iterator();
while (products.hasNext()) {
Product product = (Product)products.next();
if ( colorSpec.isSatisfiedBy(product) &&
priceSpec.isSatisfiedBy(product) )
foundProducts.add(product);
}
return foundProducts;
}
4. The byColorAndBelowPrice(…) method uses criteria ( color and price ) in its object selection logic. I’d like to make this method, and others like it, work with a composite specification rather than with individual specifications. To do that, I’ll implement a modified version of step 1 and an unmodified version of step 2. Here’s how byColorAndBelowPrice(…) looks after step 1:
public List byColorAndBelowPrice(Color color, float price) {
ColorSpec colorSpec = new ColorSpec(color);
BelowPriceSpec priceSpec = new BelowPriceSpec(price);
AndSpec spec = new AndSpec(colorSpec, priceSpec);
List foundProducts = new ArrayList();
Iterator products = repository.iterator();
while (products.hasNext()) {
Product product = (Product)products.next();
if ( spec.getAugend() .isSatisfiedBy(product) &&
spec.getAddend() .isSatisfiedBy(product))
foundProducts.add(product);
}
return foundProducts;
}
The AndSpec class looks like this:
public class AndSpec {
private Spec augend, addend;
public AndSpec(Spec augend, Spec addend) {
this.augend = augend;
this.addend = addend;
}
public Spec getAddend() {
return addend;
}
public Spec getAugend() {
return augend;
}
}
After implementing step 2, the code now looks like this:
public List byColorAndBelowPrice(Color color, float price) {
...
AndSpec spec = new AndSpec(colorSpec, priceSpec);
while (products.hasNext()) {
Product product = (Product)products.next();
if ( spec. isSatisfiedBy(product))
foundProducts.add(product);
}
return foundProducts;
}
public class AndSpec extends Spec ...
public boolean isSatisfiedBy(Product product) {
return getAugend().isSatisfiedBy(product) &&
getAddend().isSatisfiedBy(product);
}
I now have a composite specification that handles an AND operation to join two concrete specifications. In another object selection method called belowPriceAvoidingAColor(…) , I have more complicated conditional logic:
public class ProductFinder...
public List belowPriceAvoidingAColor(float price, Color color) {
List foundProducts = new ArrayList();
Iterator products = repository.iterator();
while (products.hasNext()) {
Product product = (Product) products.next();
if (product.getPrice() < price && product.getColor() != color)
foundProducts.add(product);
}
return foundProducts;
}
This code requires two composite specifications ( AndProductSpecification and NotProductSpecification ) and two concrete specifications. The conditional logic in the method can be portrayed as shown in the diagram on the following page.
My first task is to produce a NotSpec :
public class NotSpec extends Spec {
private Spec specToNegate;
public NotSpec(Spec specToNegate) {
this.specToNegate = specToNegate;
}
public boolean isSatisfiedBy(Product product) {
return !specToNegate.isSatisfiedBy(product);
}
}
Then I modify the conditional logic to use AndSpec and NotSpec :
public List belowPriceAvoidingAColor(float price, Color color) {
AndSpec spec =
new AndSpec(
new BelowPriceSpec(price),
new NotSpec(
new ColorSpec(color)
)
);
List foundProducts = new ArrayList();
Iterator products = repository.iterator();
while (products.hasNext()) {
Product product = (Product) products.next();
if ( spec. isSatisfiedBy(product))
foundProducts.add(product);
}
return foundProducts;
}
That takes care of the belowPriceAvoidingAColor(…) method. I continue replacing logic in the object selection methods until all of them use either one concrete specification or one composite specification.
5. The bodies of all object selection methods are now identical, except for the specification creation logic:
Spec spec = ...create some spec
List foundProducts = new ArrayList();
Iterator products = repository.iterator();
while (products.hasNext()) {
Product product = (Product) products.next();
if ( spec. isSatisfiedBy(product))
foundProducts.add(product);
}
return foundProducts;
This means I can apply Extract Method [ F ] on everything except the specification creation logic in any object selection method to produce a selectBy(…) method. I decide to perform this step on the belowPrice(…) method:
public List belowPrice(float price) {
BelowPriceSpec spec = new BelowPriceSpec(price);
return selectBy(spec);
}
private List selectBy(ProductSpecification spec) {
List foundProducts = new ArrayList();
Iterator products = repository.iterator();
while (products.hasNext()) {
Product product = (Product)products.next();
if (spec.isSatisfiedBy(product))
foundProducts.add(product);
}
return foundProducts;
}
I compile and test to make sure this works. Now I make remaining ProductFinder object selection methods call the same selectBy(…) method. For example, here’s the call to belowPriceAvoidingAColor(…) :
public List belowPriceAvoidingAColor(float price, Color color) {
ProductSpec spec =
new AndProduct(
new BelowPriceSpec(price),
new NotSpec(
new ColorSpec(color)
)
);
return selectBy(spec) ;
}
6. Now every object selection method can be inlined using Inline Method [ F ]:
public class ProductFinder...
public List byColor(Color colorOfProductToFind) {
ColorSpec spec = new ColorSpec(colorOfProductToFind));
return selectBy(spec);
}
public class ProductFinderTests extends TestCase...
public void testFindByColor()...
List foundProducts = finder.byColor(Color.red);
ColorSpec spec = new ColorSpec(Color.red));
List foundProducts = finder.selectBy(spec);
I compile and test to make sure that everything’s working. Then I conclude this refactoring by repeating step 6 for every object selection method.