Much of the code we write doesn’t start out being simple. To make it simple, we must reflect on what isn’t simple about it and continually ask, “How could it be simpler?” We can often simplify code by considering a completely different solution. The refactorings in this chapter present different solutions for simplifying methods, state transitions, and tree structures.

Compose Method (123) is about producing methods that efficiently communicate what they do and how they do what they do. A Composed Method [ Beck, SBPP ] consists of calls to well-named methods that are all at the same level of detail. If you want to keep your system simple, endeavor to apply Compose Method (123) everywhere.

Algorithms often become complex as they begin to support many variations. Replace Conditional Logic with Strategy (129) shows how to simplify algorithms by breaking them up into separate classes. Of course, if your algorithm isn’t sufficiently complicated to justify a Strategy [ DP ], refactoring to one will only complicate your design.

You probably won’t refactor to a Decorator [ DP ] frequently. Yet it is a great simplification tool for a certain situation: when you have too much special-case or embellishment logic in a class. Move Embellishment to Decorator (144) describes how to identify when you really need a Decorator and then shows how to separate embellishments from the core responsibility of a class.

Logic for controlling state transitions is notorious for becoming complex. This is especially true as you add more and more state transitions to a class. The refactoring Replace State-Altering Conditionals with State (166) describes how to drastically simplify complex state transition logic and helps you determine whether your logic is complex enough to require a State [ DP ] implementation.

Replace Implicit Tree with Composite (178) is a refactoring that targets the complexity of building and working with tree structures. It shows how a Composite [ DP ] can simplify a client’s creation and interaction with a tree structure.

The Command pattern [ DP ] is useful for simplifying certain types of code. The refactoring Replace Conditional Dispatcher with Command (191) shows how this pattern can completely simplify a switch statement that controls which chunk of behavior to execute.

Compose Method

You can’t rapidly understand a method’s logic.

Transform the logic into a small number of
intention-revealing steps at the same level of detail.

Compose Method

Motivation

Kent Beck once said that some of his best patterns are those that he thought someone would laugh at him for writing. Composed Method [ Beck, SBPP ] may be such a pattern. A Composed Method is a small, simple method that you can understand in seconds. Do you write a lot of Composed Methods? I like to think I do, but I often find that I don’t, at first. So I have to go back and refactor to this pattern. When my code has many Composed Methods, it tends to be easy to use, read, and extend.

A Composed Method is composed of calls to other methods. Good Composed Methods have code at the same level of detail. For example, the code set in bold in the following listing is not at the same level of detail as the nonbold code:

private void paintCard(Graphics g) {
    Image image = null;
    if (card.getType().equals("Problem")) {
      image = explanations.getGameUI().problem;
    } else if (card.getType().equals("Solution")) {
      image = explanations.getGameUI().solution;
    } else if (card.getType().equals("Value")) {
      image = explanations.getGameUI().value;
    }
    g.drawImage(image,0,0,explanations.getGameUI());

   if (shouldHighlight())
     paintCardHighlight(g);
   paintCardText(g);
}

By refactoring to a Composed Method, all of the methods called within the paintCard() method are now at the same level of detail:

private void paintCard(Graphics g) {
   paintCardImage(g);
   if (shouldHighlight())
     paintCardHighlight(g);
   paintCardText(g);
}

Most refactorings to Composed Method involve applying Extract Method [ F ] several times until the Composed Method does most (if not all) of its work via calls to other methods. The most difficult part is deciding what code to include or not include in an extracted method. If you extract too much code into a method, you’ll have a hard time naming the method to adequately describe what it does. In that case, just apply Inline Method [ F ] to get the code back into the original method, and then explore other ways to break it up.

Once you finish this refactoring, you will likely have numerous small, private methods that are called by your Composed Method. Some may consider such small methods to be a performance problem. They are only a performance problem when a profiler says they are. I rarely find that my worst performance problems relate to Composed Methods; they almost always relate to other coding problems.

If you apply this refactoring on numerous methods within the same class, you may find that the class has an overabundance of small, private methods. In that case, you may see an opportunity to apply Extract Class [ F ].

Another possible downside of this refactoring involves debugging. If you debug a Composed Method, it can become difficult to find where the actual work gets done because the logic is spread out across many small methods.

A Composed Method’s name communicates what it does, while its body communicates how it does what it does. This allows you to rapidly comprehend the code in a Composed Method. When you add up all the time you and your team spend trying to understand a system’s code, you can just imagine how much more efficient and effective you’ll be if the system is composed of many Composed Methods.

Benefits and Liabilities

+  Efficiently communicates what a method does and how it does what it does.

+  Simplifies a method by breaking it up into well-named chunks of behavior at the same level of detail.

–  Can lead to an overabundance of small methods.

–  Can make debugging difficult because logic is spread out across many small methods.

Mechanics

This is one of the most important refactorings I know. Conceptually, it is also one of the simplest—so you’d think that this refactoring would lead to a simple set of mechanics. In fact, it’s just the opposite. While the steps themselves aren’t complex, there is no simple, repeatable set of steps. Instead, there are guidelines for refactoring to Composed Method, some of which include the following.

•     Think small: Composed Methods are rarely more than ten lines of code and are usually about five lines.

•     Remove duplication and dead code: Reduce the amount of code in the method by getting rid of blatant and/or subtle code duplication or code that isn’t being used.

•     Communicate intention: Name your variables, methods, and parameters clearly so they communicate their purposes (e.g., public void addChildTo(Node parent) ).

•     Simplify: Transform your code so it’s as simple as possible. Do this by questioning how you’ve coded something and by experimenting with alternatives.

•     Use the same level of detail: When you break up one method into chunks of behavior, make the chunks operate at similar levels of detail. For example, if you have a piece of detailed conditional logic mixed in with some high-level method calls, you have code at different levels of detail. Push the detail down into a well-named method, at the same level of detail as the other methods in the Composed Method.

Example

This example comes from a custom-written collections library. A List class contains an add(…) method by which a user can add an object to a List instance:

public class List...
   public void add(Object element) {
      if (!readOnly) {
         int newSize = size + 1;
         if (newSize > elements.length) {
            Object[] newElements =
               new Object[elements.length + 10];
            for (int i = 0; i < size; i++)
               newElements[i] = elements[i];
            elements = newElements;
         }
         elements[size++] = element;
      }
   }

The first thing I want to change about this 11-line method is its first conditional statement. Instead of using a conditional to wrap all of the method’s code, I’d rather see the condition used as a guard clause, by which we can make an early exit from the method:

public class List...
   public void add(Object element) {
       if (readOnly)
          return;
      int newSize = size + 1;
      if (newSize > elements.length) {
         Object[] newElements =
            new Object[elements.length + 10];
         for (int i = 0; i < size; i++)
            newElements[i] = elements[i];
         elements = newElements;

      }
      elements[size++] = element;
   }

Next, I study the code in the middle of the method. This code checks to see whether the size of the elements array will exceed capacity if a new object is added. If capacity will be exceeded, the elements array is expanded by a factor of 10. The magic number 10 doesn’t communicate very well at all. I change it to be a constant:

public class List...
    private final static int GROWTH_INCREMENT = 10;

   public void add(Object element)...
      ...
      Object[] newElements =
         new Object[elements.length +  GROWTH_INCREMENT ];
      ...

Next, I apply Extract Method [ F ] on the code that checks whether the elements array is at capacity and needs to grow. This leads to the following code:

public class List...
   public void add(Object element) {
      if (readOnly)
         return;
       if (atCapacity()) {
         Object[] newElements =
            new Object[elements.length + GROWTH_INCREMENT];
         for (int i = 0; i < size; i++)
            newElements[i] = elements[i];
         elements = newElements;
      }
      elements[size++] = element;
   }

    private boolean atCapacity() {
       return (size + 1) > elements.length;
    }

Next, I apply Extract Method [ F ] on the code that grows the size of the elements array:

public class List...
   public void add(Object element) {
      if (readOnly)
         return;
      if (atCapacity())
          grow();
      elements[size++] = element;
   }

    private void grow() {
       Object[] newElements =
          new Object[elements.length + GROWTH_INCREMENT];
       for (int i = 0; i < size; i++)
          newElements[i] = elements[i];
       elements = newElements;
    }

Finally, I focus on the last line of the method:

elements[size++] = element;

Although this is one line of code, it is not at the same level of detail as the rest of the method. I fix this by extracting this code into its own method:

public class List...
   public void add(Object element) {
      if (readOnly)
         return;
      if (atCapacity())
         grow();
       addElement(element);
   }

    private void addElement(Object element) {
       elements[size++] = element;
    }

The add(…) method now contains only five lines of code. Before this refactoring, it would take a little time to understand what the method was doing. After this refactoring, I can rapidly understand what the method does in one second. This is a typical result of applying Compose Method .

Replace Conditional Logic with Strategy

Conditional logic in a method controls which
of several variants of a calculation are executed.

Create a Strategy for each variant and make the method
delegate the calculation to a Strategy instance.

Replace Conditional Logic with Strategy

Motivation

“Simplifying Conditional Expressions” is a chapter in Refactoring [ F ] that contains over a half-dozen highly useful refactorings devoted to cleaning up conditional complexity. About Decompose Conditional [ F ], Martin Fowler writes, “One of the most common areas of complexity in a program lies in complex conditional logic” [ F , 238]. We often find such logic in algorithms because they tend to grow, becoming more sophisticated over time. The Strategy pattern [ DP ] helps manage the complexity that results from having numerous variations of an algorithm.

Conditional logic is often used to decide which variation of an algorithm to use. Refactorings like Decompose Conditional [ F ] or Compose Method (123) can simplify such code. On the other hand, they can also overrun your host class with small methods that apply only to specific variations of the algorithm, thereby complicating the host class. In such a situation, it may be better to move each algorithm variation to new classes or to subclasses of the host class. This essentially involves choosing between object composition and inheritance.

Replace Conditional Logic with Strategy (129) involves object composition: you produce a family of classes for each variation of the algorithm and outfit the host class with one Strategy instance to which the host delegates at runtime. An inheritance-based solution can be achieved by applying Replace Conditional with Polymorphism [ F ]. The prerequisite for that refactoring is an inheritance structure (i.e., the algorithm’s host class must have subclasses). If subclasses exist and each variation of the algorithm maps easily to specific subclasses, this is probably your preferred refactoring. If you must first create the subclasses, you’ll have to decide whether it would be easier to use an object-compositional approach, like refactoring to Strategy. If the conditionals in the algorithm are controlled by one type code, it may be easy to create subclasses of the algorithm’s host class, one for each type code (see Replace Type Code with Subclasses [ F ]). If there is no such type code, you’ll likely be better off refactoring to Strategy. Finally, if clients need to swap one calculation type for another at runtime, you’d better avoid an inheritance-based approach because this means changing the type of object a client is working with rather than simply substituting one Strategy instance for another.

When deciding whether to refactor to or towards a Strategy, you have to consider how the algorithm embedded in each Strategy will access the data it needs to do its job. As the Mechanics section points out, there are two ways to do this: pass the host class (called the context ) to the Strategy so it can call back on methods to get its data, or just pass the data directly to the Strategy via parameters. Both of these approaches have upsides and downsides, which are discussed in the Mechanics section.

The Strategy and Decorator patterns offer alternative ways to eliminate conditional logic associated with special-case or alternative behavior. The sidebar Decorator vs. Strategy in the Motivation section of Move Embellishment to Decorator (144) offers a look at how these two patterns differ.

When implementing a Strategy-based design, you’ll want to consider how your context class will obtain its Strategy. If you don’t have many combinations of Strategies and context classes, it’s good practice to shield client code from having to worry about both instantiating a Strategy instance and outfitting a context with a Strategy instance. Encapsulate Classes with Factory (80) can help with this: just define one or more methods that return a context instance, properly outfitted with the appropriate Strategy instance.

Benefits and Liabilities

+  Clarifies algorithms by decreasing or removing conditional logic.

+  Simplifies a class by moving variations on an algorithm to a hierarchy.

+  Enables one algorithm to be swapped for another at runtime.

–  Complicates a design when an inheritance-based solution or a refactoring from “Simplifying Conditional Expressions” [ F ] is simpler.

–  Complicates how algorithms obtain or receive data from their context class.

Mechanics

Identify the context , a class with a calculation method that contains a lot of conditional logic.

1.  Create a strategy , a concrete class (known as Strategy:ConcreteStrategy in Design Patterns [ DP ]) that will become a genuine ConcreteStrategy by the end of this refactoring. Name your strategy after the behavior performed by the calculation method. You can append the word “Strategy” to the class name if you find it helps communicate the purpose of this new type.

2.  Apply Move Method [ F ] to move the calculation method to the strategy. When you perform this step, retain a version of the calculation method on the context that delegates to the strategy’s calculation method. Implementing this delegation will involve defining and instantiating a delegate , a field in context that holds a reference to a strategy.

     Since most strategies require data in order to do their calculations, you’ll need to determine how to make that data available to the strategy. Here are two common approaches.

a.  Pass the context as a parameter to the strategy’s constructor or calculation method. This may involve making context methods public so the strategy can obtain the information it needs. A downside of this approach is that it often breaks “information hiding” (i.e., data that was visible only to the context now must be made visible to other classes, such as the strategy). An upside to this approach is that when you add new public methods to your context, they will be immediately available to all concrete strategies without a lot of code changes. If you take this approach, consider giving the least public access to context data—for example, in Java, consider giving your strategies package protection access to context data.

b.  Pass the necessary data from the context to the strategy via calculation method parameters. A downside of this approach is that data will be passed to every concrete strategy regardless of whether particular strategies need that data. An upside to this approach is that it involves the least coupling between the context and the strategy.

     A challenge of following this approach relates to the amount of data you’ll need to pass to the strategy. If you have to pass ten parameters to your strategy, it may be better to pass the entire context as a reference to the strategy. On the other hand, you may be able to apply Introduce Parameter Object [ F ] to cut down the number of parameters you must pass to your strategy, thereby making data-passing an acceptable approach. Furthermore, if some parameters are passed to the strategy solely to handle the needs of a specific concrete strategy, you can remove that data from the parameter list and pass it to the concrete strategy via a constructor or initialization method.

     There may be helper methods in the context that really belong in the strategy because they are referenced only by the calculation method that’s now in the strategy. Move such helper methods from the context to the strategy by implementing whatever accessors are necessary.

Image   Compile and test.

3.  Let clients outfit a context with an instance of the strategy by applying Extract Parameter (346) on the context code that instantiates a concrete strategy and assigns it to the delegate.

Image   Compile and test.

4.  Apply Replace Conditional with Polymorphism [ F ] on the strategy’s calculation method. To apply that refactoring, you’ll first be given a choice to use Replace Type Code with Subclasses [ F ] or Replace Type Code with State/Strategy [ F ]. Choose the former. You’ll need to implement Replace Type Code with Subclasses [ F ] whether you have an explicit type code or not. If conditional logic in the calculation method identifies particular types of the calculation, use that conditional logic in place of explicit types as you work through the mechanics for Replace Type Code with Subclasses [ F ].

     Focus on producing one subclass at a time. Upon completion of this step, you’ll have substantially reduced the conditional logic in the strategy and you’ll have concrete strategies for each variety of the original calculation method. If possible, make the strategy an abstract class.

Image   Compile and test with combinations of context instances and concrete strategy instances.

Example

The example in the code sketch presented in the introduction to this refactoring deals with calculating capital for three different kinds of bank loans: a term loan, a revolver, and an advised line. It contains a fair amount of conditional logic used in performing the capital calculation, though it’s less complicated and contains less conditional logic than was present in the original code, which handled capital calculations for seven distinct loan types.

In this example, we’ll see how Loan ’s method for calculating capital can be strategized (i.e., delegated to a Strategy object). As you study the example, you may wonder why Loan wasn’t simply subclassed to support the different styles of capital calculations. That would not have been a good design choice because the application that used Loan needed to accomplish the following.

•  Calculate capital for loans in a variety of ways. Had there been one Loan subclass for each type of capital calculation, the Loan hierarchy would have been overburdened with subclasses, as shown in the diagram on the following page.

Example

•  Change a loan’s capital calculation at runtime, without changing the class type of the Loan instance. This is easier to do when it involves exchanging a Loan object’s Strategy instance for another Strategy instance, rather than changing the whole Loan object from one subclass of Loan into another.

Now let’s look at some code. The Loan class, which plays the role of the context (as defined in the Mechanics section), contains a calculation method called capital() :

public class Loan...
   public double capital() {
      if (expiry == null && maturity != null)
         return commitment * duration() * riskFactor();
      if (expiry != null && maturity == null) {
         if (getUnusedPercentage() != 1.0)
            return commitment * getUnusedPercentage() * duration() * riskFactor();
         else
            return (outstandingRiskAmount() * duration() * riskFactor())
                + (unusedRiskAmount() * duration() * unusedRiskFactor());
      }
      return 0.0;
   }

Much of the conditional logic deals with figuring out whether the loan is a term loan, a revolver, or an advised line. For example, a null expiry date and a non-null maturity date indicate a term loan. That code doesn’t reveal its intentions well, does it? Once the code figures out what type of loan it has, a specific capital calculation can be performed. There are three such capital calculations, one for each loan type. All three of these calculations rely on the following helper methods:

public class Loan...
   private double outstandingRiskAmount() {
      return outstanding;
   }

   private double unusedRiskAmount() {
      return (commitment - outstanding);
   }

   public double duration() {
      if (expiry == null && maturity != null)
         return weightedAverageDuration();
      else if (expiry != null && maturity == null)
         return yearsTo(expiry);
      return 0.0;
   }

   private double weightedAverageDuration() {
      double duration = 0.0;
      double weightedAverage = 0.0;
      double sumOfPayments = 0.0;
      Iterator loanPayments = payments.iterator();
      while (loanPayments.hasNext()) {
         Payment payment = (Payment)loanPayments.next();
         sumOfPayments += payment.amount();
         weightedAverage += yearsTo(payment.date()) * payment.amount();
      }
      if (commitment != 0.0)
         duration = weightedAverage / sumOfPayments;
      return duration;
   }

   private double yearsTo(Date endDate) {
      Date beginDate = (today == null ? start : today);
      return ((endDate.getTime() - beginDate.getTime()) / MILLIS_PER_DAY) / DAYS_PER_YEAR;
   }

   private double riskFactor() {
      return RiskFactor.getFactors().forRating(riskRating);
   }

   private double unusedRiskFactor() {
      return UnusedRiskFactors.getFactors().forRating(riskRating);
   }

The Loan class can be simplified by extracting specific calculation logic into individual strategy classes, one for each loan type. For example, the method weightedAverageDuration() is used only to calculate capital for a term loan.

I’ll now proceed with the refactoring to Strategy.

1.  Since the strategy I’d like to create will handle the calculation of a loan’s capital, I create a class called CapitalStrategy .

public class CapitalStrategy {
}

2.  Now I apply Move Method [ F ] to move the capital() calculation to CapitalStrategy . This step involves leaving a simple version of capital() on Loan , which will delegate to an instance of CapitalStrategy .

     The first step is to declare capital() in CapitalStrategy :

public class CapitalStrategy {
    public double capital() {
      return 0.0;
    }
}

     Now I need to copy code from Loan to CapitalStrategy . Of course, this will involve copying the capital() method. The mechanics for Move Method [ F ] encourage me to move whatever features (data or methods) are used solely by capital() . I begin by copying the capital() method and then see what else I can easily move from Loan to CapitalStrategy . I end up with the following code, which doesn’t compile at the moment:

public class CapitalStrategy...
    public double capital() {    // copied from Loan
       if (expiry == null && maturity != null)
          return commitment * duration() * riskFactor();
       if (expiry != null && maturity == null) {
          if (getUnusedPercentage() != 1.0)
             return commitment * getUnusedPercentage() * duration() * riskFactor();
          else
             return (outstandingRiskAmount() * duration() * riskFactor())
                 + (unusedRiskAmount() * duration() * unusedRiskFactor());
       }
       return 0.0;
    }

    private double riskFactor() {         // moved from Loan
       return RiskFactor.getFactors().forRating(riskRating);
    }

    private double unusedRiskFactor() {     // moved from Loan
       return UnusedRiskFactors.getFactors().forRating(riskRating);
    }

     I find that I cannot move the duration() method from Loan to CapitalStrategy because the weightedAverageDuration() method relies on Loan ’s payment information. Once I make that payment information accessible to CapitalStrategy , I’ll be able to move duration() and its helper methods to CapitalStrategy . I’ll do that soon. For now, I need to make the code I copied into CapitalStrategy compile. To do that, I must decide whether to pass a Loan reference as a parameter to capital() and its two helper methods or pass data as parameters to capital() , which it can use and pass to its helper methods. I determine that capital() needs the following information from a Loan instance:

•  Expiry date

•  Maturity date

•  Duration

•  Commitment amount

•  Risk rating

•  Unused percentage

•  Outstanding risk amount

•  Unused risk amount

     If I can make that list smaller, I could go with a data-passing approach. So I speculate that I could create a LoanRange class to store dates associated with Loan instances (e.g., expiry and maturity dates). I might also be able to group the commitment amount, outstanding risk amount, and unused risk amount into a LoanRisk class or something with a better name.

     Yet I quickly abandon these ideas when I realize that I have other methods to move from Loan to CapitalStrategy (such as duration() ), which require that I pass even more information (such as payments) to CapitalStrategy . I decide to simply pass a Loan reference to CapitalStrategy and make the necessary changes on Loan to make all the code compile:

public class CapitalStrategy...
   public double capital( Loan loan ) {
      if ( loan.getExpiry()  == null &&  loan.getMaturity()  != null)
         return  loan.getCommitment()  *  loan .duration() *  riskFactorFor(loan) ;
      if ( loan.getExpiry()  != null &&  loan.getMaturity()  == null) {
         if ( loan.getUnusedPercentage()  != 1.0)
            return  loan.getCommitment()  *  loan.getUnusedPercentage()
            *  loan. duration() *  riskFactorFor(loan) ;
         else
            return
              ( loan.outstandingRiskAmount()  *  loan. duration() *  riskFactorFor(loan) )
            + ( loan.unusedRiskAmount()  *  loan. duration() *  unusedRiskFactorFor(loan) );
      }
      return 0.0;
   }

   private double riskFactor For(Loan loan ) {
      return RiskFactor.getFactors().forRating( loan.getRiskRating() );
   }

   private double unusedRiskFactor For(Loan loan ) {
      return UnusedRiskFactors.getFactors().forRating( loan.getRiskRating() );
   }

     The changes I make to Loan all involve creating new methods that make Loan data accessible. Since CapitalStrategy lives in the same package as Loan , I can limit the visibility of this data by using Java’s “package protection” feature. I do this by not assigning an explicit visibility ( public , private , or protected ) to each method:

public class Loan...
    Date getExpiry() {
       return expiry;
    }

    Date getMaturity() {
       return maturity;
    }

    double getCommitment() {
       return commitment;
    }

    double getUnusedPercentage() {
       return unusedPercentage;
    }

    private  double outstandingRiskAmount() {
      return outstanding;
   }

    private  double unusedRiskAmount() {
      return (commitment - outstanding);
   }

     Now all the code in CapitalStrategy compiles. The next step in Move Method [ F ] is to make Loan delegate to CapitalStrategy for the capital calculation:

public class Loan...
   public double capital() {
       return new CapitalStrategy().capital(this);
   }

     Now everything compiles. I run my tests, such as the one below, to see that everything still works:

public class CapitalCalculationTests extends TestCase {
   public void testTermLoanSamePayments() {
      Date start = november(20, 2003);
      Date maturity = november(20, 2006);
      Loan termLoan = Loan.newTermLoan(LOAN_AMOUNT, start, maturity, HIGH_RISK_RATING);
      termLoan.payment(1000.00, november(20, 2004));
      termLoan.payment(1000.00, november(20, 2005));
      termLoan.payment(1000.00, november(20, 2006));
      assertEquals("duration", 2.0, termLoan.duration(), TWO_DIGIT_PRECISION);
      assertEquals("capital", 210.00, termLoan.capital(), TWO_DIGIT_PRECISION);
   }

     All the tests pass. I can now focus on moving more functionality related to the capital calculation from Loan to CapitalStrategy . I will spare you the details; they are similar to what I’ve already shown. When I’m done, CapitalStrategy now looks like this:

public class CapitalStrategy {
   private static final int MILLIS_PER_DAY = 86400000;
   private static final int DAYS_PER_YEAR = 365;

   public double capital(Loan loan) {
      if (loan.getExpiry() == null && loan.getMaturity() != null)
         return loan.getCommitment() * loan.duration() * riskFactorFor(loan);
      if (loan.getExpiry() != null && loan.getMaturity() == null) {
         if (loan.getUnusedPercentage() != 1.0)
            return loan.getCommitment() * loan.getUnusedPercentage()
            * loan.duration() * riskFactorFor(loan);
         else
            return
              (loan.outstandingRiskAmount() * loan.duration() * riskFactorFor(loan))
            + (loan.unusedRiskAmount() * loan.duration() * unusedRiskFactorFor(loan));
      }
      return 0.0;
   }

   private double riskFactorFor(Loan loan) {
      return RiskFactor.getFactors().forRating(loan.getRiskRating());
   }

   private double unusedRiskFactorFor(Loan loan) {
      return UnusedRiskFactors.getFactors().forRating(loan.getRiskRating());
   }

   public double duration(Loan loan) {
      if (loan.getExpiry() == null && loan.getMaturity() != null)
         return weightedAverageDuration(loan);
      else if (loan.getExpiry() != null && loan.getMaturity() == null)
         return yearsTo(loan.getExpiry(), loan);
      return 0.0;
   }

   private double weightedAverageDuration(Loan loan) {
      double duration = 0.0;
      double weightedAverage = 0.0;
      double sumOfPayments = 0.0;
      Iterator loanPayments = loan.getPayments().iterator();
      while (loanPayments.hasNext()) {
         Payment payment = (Payment)loanPayments.next();
         sumOfPayments += payment.amount();
         weightedAverage += yearsTo(payment.date(), loan) * payment.amount();
      }
      if (loan.getCommitment() != 0.0)
         duration = weightedAverage / sumOfPayments;
      return duration;
   }

   private double yearsTo(Date endDate, Loan loan) {
      Date beginDate = (loan.getToday() == null ? loan.getStart() : loan.getToday());
      return ((endDate.getTime() - beginDate.getTime()) / MILLIS_PER_DAY) / DAYS_PER_YEAR;
   }
}

     One consequence of performing these changes is that Loan ’s capital and duration calculations now look like this:

public class Loan...
   public double capital() {
      return new CapitalStrategy().capital(this);
   }

   public double duration() {
      return new CapitalStrategy().duration(this);
   }

     While I resist the temptation to prematurely optimize the Loan class, I don’t ignore an opportunity to remove duplication. In other words, it’s time to replace the two occurrences of new CapitalStrategy() with a CapitalStrategy field on Loan :

public class Loan...
    private CapitalStrategy capitalStrategy;

   private Loan(double commitment, double outstanding,
                 Date start, Date expiry, Date maturity, int riskRating) {
       capitalStrategy = new CapitalStrategy();       ...
   }

   public double capital() {
      return  capitalStrategy .capital(this);
   }

   public double duration() {
      return  capitalStrategy .duration(this);
   }

     I’ve now finished applying Move Method [ F ].

3.  Now I’ll apply Extract Parameter (346) to make it possible to set the value of the delegate, which is currently hard-coded. This step will be important when we get to the next step in the refactoring:

public class Loan...
   private Loan(...,   CapitalStrategy capitalStrategy ) {
      ...
      this.capitalStrategy = capitalStrategy;
   }

   public static Loan newTermLoan(
      double commitment, Date start, Date maturity, int riskRating) {

      return new Loan(
         commitment, commitment, start, null,
         maturity, riskRating,  new CapitalStrategy()
      );
   }

   public static Loan newRevolver(
      double commitment, Date start, Date expiry, int riskRating) {

      return new Loan(commitment, 0, start, expiry,
         null, riskRating,  new CapitalStrategy()
      );
   }

   public static Loan newAdvisedLine(
      double commitment, Date start, Date expiry, int riskRating) {
      if (riskRating > 3) return null;
      Loan advisedLine =
         new Loan(commitment, 0, start, expiry, null, riskRating,  new CapitalStrategy() );
      advisedLine.setUnusedPercentage(0.1);
      return advisedLine;
   }

4.  I can now apply Replace Conditional with Polymorphism [ F ] on CapitalStrategy ’s capital() method. My first step is to create a subclass for the capital calculation for a term loan. This involves making some methods protected in CapitalStrategy (not shown below) and moving some methods to a new class called CapitalStrategyTermLoan (shown below):

public class CapitalStrategyTermLoan extends CapitalStrategy {
    public double capital(Loan loan) {
       return loan.getCommitment() * duration(loan) * riskFactorFor(loan);
    }

    public double duration(Loan loan) {
       return weightedAverageDuration(loan);
    }

    private double weightedAverageDuration(Loan loan) {
       double duration = 0.0;
       double weightedAverage = 0.0;
       double sumOfPayments = 0.0;
       Iterator loanPayments = loan.getPayments().iterator();
       while (loanPayments.hasNext()) {
          Payment payment = (Payment)loanPayments.next();
          sumOfPayments += payment.amount();
          weightedAverage += yearsTo(payment.date(), loan) * payment.amount();
       }
       if (loan.getCommitment() != 0.0)
          duration = weightedAverage / sumOfPayments;
       return duration;
    }

     To test this class, I must first update Loan as follows:

public class Loan...
   public static Loan newTermLoan(
      double commitment, Date start, Date maturity, int riskRating) {
      return new Loan(
         commitment, commitment, start, null, maturity, riskRating,
          new CapitalStrategyTermLoan()
      );
   }

     The tests pass. Now I continue applying Replace Conditional with Polymorphism [ F ] to produce capital strategies for the other two loan types, revolver and advised line. Here are the changes I make to Loan :

public class Loan...
   public static Loan newRevolver(
      double commitment, Date start, Date expiry, int riskRating) {
      return new Loan(
         commitment, 0, start, expiry, null, riskRating,
          new CapitalStrategyRevolver()

      );
   }

   public static Loan newAdvisedLine(
      double commitment, Date start, Date expiry, int riskRating) {
      if (riskRating > 3) return null;
      Loan advisedLine = new Loan(
          commitment, 0, start, expiry, null, riskRating,
           new CapitalStrategyAdvisedLine()
      );
      advisedLine.setUnusedPercentage(0.1);
      return advisedLine;
   }

     Here’s a look at all of the new strategy classes:

Example

     You’ll notice that CapitalStrategy is now an abstract class. It now looks like this:

public abstract class CapitalStrategy {
   private static final int MILLIS_PER_DAY = 86400000;
   private static final int DAYS_PER_YEAR = 365;

   public abstract double capital(Loan loan);

   protected double riskFactorFor(Loan loan) {
      return RiskFactor.getFactors().forRating(loan.getRiskRating());
   }

   public double duration(Loan loan) {
      return yearsTo(loan.getExpiry(), loan);
   }

   protected double yearsTo(Date endDate, Loan loan) {
      Date beginDate = (loan.getToday() == null ? loan.getStart() : loan.getToday());
      return ((endDate.getTime() - beginDate.getTime()) / MILLIS_PER_DAY) / DAYS_PER_YEAR;
   }
}

And that does it for this refactoring. Capital calculations, which include duration calculations, are now performed using several concrete strategies.

Move Embellishment to Decorator

Code provides an embellishment to a class’s core responsibility.

Move the embellishment code to a Decorator.

Move Embellishment to Decorator

Motivation

When new features in a system are needed, it’s common to add new code to old classes. Such new code often embellishes the core responsibility or primary behavior of an existing class. The trouble with some of these embellishments is that they complicate their host classes with new fields, new methods, and new logic, all of which exists for special-case behavior that needs to be executed only some of the time.

The Decorator pattern [ DP ] offers a good remedy: place each embellishment in its own class and let that class wrap the type of object it needs to embellish so that clients may wrap the embellishment around objects at runtime, when special-case behavior is needed.

The JUnit testing framework [ Beck and Gamma ] provides a good example. JUnit makes it easy to write and run tests. Each test is an object of type TestCase , and there’s an easy way to tell the framework to run all of your TestCase objects. But if you want to run one test multiple times, there’s no embellishment within TestCase to do so. For that extended behavior, you must decorate a TestCase object with a RepeatedTest Decorator, as the client code does in the following diagram.

Motivation

Decorator is not a pattern you’d refactor to if you wanted to move an embellishment out of a class with dozens of public methods. Why? Because a Decorator must be what Design Patterns [ DP ] calls a “transparent enclosure”: it must implement all of the public methods of the classes it decorates (and that would require a lot of useless code for a class with dozens of public methods). Transparent enclosures wrap objects in a way that is transparent to the objects being wrapped (i.e., a decoratee doesn’t know it has been decorated).

Since a Decorator and its decoratee share the same interface, Decorators are transparent to client code that uses them. Such transparency works well for client code, unless that code is deliberately checking the identity of an object. In that case, the Decorator can prevent the client code from identifying a particular object instance because the Decorator and the object it decorates are instances of different classes. For example, the following Java code

if (node instanceof StringNode)

would not evaluate to true if node were an instance of a StringNode that had been decorated with a concrete Decorator. That shouldn’t stop you from using this pattern, for it is often possible to rewrite client code to not rely on an object’s type.

Another consideration for using this pattern involves multiple Decorators. If you’ve written two or more concrete Decorators for an object, clients can decorate instances of the object with more than one Decorator. In that case, the ordering of the Decorators may cause unwanted behavior. For example, a Decorator that encrypts data can interfere with a Decorator that filters out certain words if the encryption happens prior to the filtering. In the ideal case, it is best to have Decorators be so independent of each other that they can be arranged in any combination. In practice, that sometimes isn’t possible; then you can consider encapsulating the Decorators and giving clients access to safe combinations of them via specific Creation Methods (see Encapsulate Classes with Factory , 80 ).

Refactoring embellishments out of a class can produce a design that is simple to those who are comfortable with object composition. To those who aren’t, code that used to be in one class is now spread out across many classes. Such a separation may make code harder to understand since because it no longer resides in one place. In addition, having code reside in different objects can make it harder to debug because debugging sessions must go through one or more Decorators before getting to a decorated object. In short, if a team isn’t comfortable with using object composition to “decorate” objects, the team may not be ready for this pattern.

Sometimes an embellishment provides protection logic for an object. In that case, the embellishment can be moved to a Protection Proxy [ DP ] (see the example from Encapsulating Inner Classes , 86 ). Structurally, a Protection Proxy is the same as a Decorator. The difference is in intent. A Protection Proxy protects an object, while a Decorator adds behavior to an object.

I like the Decorator pattern because it helps produce elegant solutions. Yet my colleagues and I don’t find ourselves refactoring to it very often. We’re more likely to refactor towards it and only refactor all the way to it once in a while. As usual, no matter how much you like a pattern, use it only when you really need it.

Decorator versus Strategy

Move Embellishment to Decorator (144) and Replace Conditional Logic with Strategy (129) are competing refactorings. Both can eliminate conditional logic associated with special-case or alternative behavior, and both do so by moving such behavior out of an existing class and into one or more new classes. Yet how these new classes are used is the difference. Decorator instances wrap themselves around an object (or each other), while one or more Strategy instances are used within an object, as shown in the following diagram.

Decorator versus Strategy

When does it make sense to refactor to Decorator versus to Strategy? There’s no simple answer. You must consider numerous issues when making the decision. Here are a few.

•  You can’t share Decorator instances—each instance wraps one object. On the other hand, you can easily share Strategy instances by means of the Singleton or Flyweight patterns [ DP ].

•  A Strategy can have whatever interface it wants, while a Decorator must conform to the interface of the classes it decorates.

•  Decorators can transparently add behavior to many different classes, as long as the classes share the same interface as the Decorators. On the other hand, classes that want to use Strategy objects must know about their existence and how to use them.

•  Using one or more Strategies within a class that holds a lot of data or implements many public methods is common practice. On the other hand, Decorator classes become too heavy and require too much memory when they’re used to decorate classes with lots of data and many public methods.

To learn more about what is similar and different about Decorator and Strategy, I suggest studying these two patterns in Design Patterns [ DP ].

Benefits and Liabilities

+  Simplifies a class by removing embellishments from it.

+  Effectively distinguishes a class’s core responsibility from its embellishments.

+  Helps remove duplicated embellishment logic in several related classes.

–  Changes the object identity of a decorated object.

–  Can make code harder to understand and debug.

–  Complicates a design when combinations of Decorators can adversely affect one another.

Mechanics

Before you begin this refactoring, you must identify an embellished class , a class that contains an embellishment to its core responsibility. Not every class with an embellishment to its core responsibility will be a good candidate for being “decorated.” First ensure that the set of public methods that your Decorator will need to implement isn’t too large. Because a Decorator forms a “transparent enclosure” around the objects it decorates, a piece of client code should be able to call the same set of public methods on a decorated object as it would normally call on the object itself. If your embellished class declares and inherits lots of public methods, either reduce that number (by deleting, moving, or changing the visibility of methods) or consider applying a different refactoring, such as Replace Conditional Logic with Strategy (129) .

1.  Identify or create an enclosure type , an interface or class that declares all of the public methods needed by clients of the embellished class. An enclosure type is known as Decorator: Component in Design Patterns [ DP ].

     If you already have an enclosure type, it’s likely to be an interface implemented by the embellished class or a superclass of the embellished class. Classes that contain state aren’t good enclosure types because Decorators will inherit their state when they don’t need to. If you don’t already have a proper enclosure type, create one by applying Unify Interfaces (343) and/or Extract Interface [ F ].

2.  Find the conditional logic (a switch or if statement) that adds the embellishment to your embellished class and remove that logic by applying Replace Conditional with Polymorphism [ F ].

     Martin Fowler notes that before applying Replace Conditional with Polymorphism , you often need to apply Replace Type Code with Subclasses [ F ] or Replace Type Code with State/Strategy [ F ]. If you apply Replace Type Code with Subclasses , the first step in the mechanics requires creating a Creation Method to fully encapsulate the type code. Should you need such a Creation Method, make sure its return type is the enclosure type. In addition, when you remove the type code field from the superclass, it is not necessary to declare the accessors for the type code as abstract (even though Martin Fowler’s mechanics state that you must do so).

     If you have logic that must be executed before and/or after your embellishment code, you’ll likely need to use Form Template Method [ F ] when applying Replace Conditional with Polymorphism .

Image   Compile and test.

3.  Step 2 produced one or more subclasses of the embellished class. Transform these subclasses into delegating classes by applying Replace Inheritance with Delegation [ F ]. When implementing this refactoring, be sure to do the following.

•  Make each delegating class implement the enclosure type.

•  Make the type for the delegating class’s delegate field be the enclosure type.

•  Decide whether your embellishment code will execute before or after your delegating class makes its call to the delegate.

     If you applied Form Template Method during step 2, your delegating class may need to call non-public methods on the delegate (i.e., the embellished class) that are referenced by your Template Method. If that occurs, change the visibility of these methods to public and reapply Unify Interfaces (343) .

     If your delegating class delegates to a method on the embellished class that can return an undecorated object instance, make sure your delegating class decorates it before handing the instance to a client.

Image   Compile and test.

4.  Each delegating class now assigns its delegate field to a new instance of the embellished class. Ensure that this assignment logic exists in a delegating class constructor. Then extract the part of the assignment statement that instantiates the embellished class into a parameter by applying Extract Parameter (346) . If possible, remove any unnecessary constructor parameters by repeatedly applying Remove Parameter [ F ].

Image   Compile and test.

Example

The open source HTML Parser ( http://sourceforge.net/projects/htmlparser ) allows programs to see the contents of HTML files as specific HTML objects. When the parser encounters tag data or strings sandwiched between tag data, it translates what it finds into the appropriate HTML objects, like Tag , StringNode , EndTag , ImageTag , and so forth. The parser is frequently used to:

•  Translate the contents of one HTML file to another

•  Report information about a piece of HTML

•  Verify the contents of HTML

The Move Embellishment to Decorator refactoring we’ll look at concerns the parser’s StringNode class. Instances of this class are created at runtime when the parser finds chunks of text sandwiched between tags. For example, consider this HTML:

This text will be recognized as a StringNode

Given this line of HTML, the parser creates the following objects at runtime:

•   Tag (for the <BODY> tag)

•   StringNode (for the String , “This text will be recognized as a StringNode”)

•   EndTag (for the </BODY> tag)

There are a few ways to examine the contents of HTML objects: you can obtain the object’s plain-text representation using toPlainTextString() , and you can obtain the object’s HTML representation using toHtml() . In addition, some classes in the parser, including StringNode , implement getText() and setText() methods. Yet a call to a StringNode instance’s getText() method returns the same plain-text representation that calls to toPlainTextString() and toHtml() return. So why are there three methods for obtaining the same value? It’s a typical story of programmers adding new code to classes based on current needs without refactoring existing code to remove duplication. In this case, it’s likely that getText() and toPlainTextString() could be consolidated into one method. In this example, I defer that refactoring work until I learn more about why this consolidation wasn’t already performed.

A common embellishment to StringNode involves decoding “numeric or character entity references” found in StringNode instances. Typical character reference decodings include the following:

Image

The parser’s Translate class has a method called decode(String dataToDecode) that can decode a comprehensive set of numeric and character entity references. Such decoding is an embellishment often applied to StringNode instances after they’ve been found by the parser. For example, consider the following test code, which parses a fragment of HTML and then iterates through a collection of Node instances, decoding the nodes that are instances of StringNode :

public void testDecodingAmpersand() throws Exception {
   String ENCODED_WORKSHOP_TITLE =
      "The Testing &amp; Refactoring Workshop";

   String DECODED_WORKSHOP_TITLE =
      "The Testing & Refactoring Workshop";

   assertEquals(
      "ampersand in string",
      DECODED_WORKSHOP_TITLE,
      parseToObtainDecodedResult(ENCODED_WORKSHOP_TITLE));
}

private String parseToObtainDecodedResult(String stringToDecode)
   throws ParserException {

   StringBuffer decodedContent = new StringBuffer();
   createParser(stringToDecode);

   NodeIterator nodes = parser.elements();
   while (nodes.hasMoreNodes()) {
      Node node = nodes.nextNode();
      if (node instanceof StringNode) {
         StringNode stringNode = (StringNode) node;
         decodedContent.append(
             Translate.decode(stringNode.toPlainTextString())); // decoding step
      }
      if (node instanceof Tag)
         decodedContent.append(node.toHtml());
   }
   return decodedContent.toString();
}

Decoding character and numeric references in StringNode instances is a feature that clients need only some of the time. Yet these clients always perform the decoding themselves, using the same process of iterating nodes, finding nodes that are StringNode instances, and decoding them. Instead of forcing these clients to perform the same decoding steps over and over again, the work could be consolidated in one place by building this decoding behavior into the parser.

I thought of several ways to go about this refactoring and then settled on a straightforward approach: add the decoding embellishment directly to StringNode and observe how the code looks afterward. I had some doubts about this implementation, but I wanted to see how far I could push it until a better design was needed. So, using test-driven development, I added the decoding embellishment to StringNode . This work involved updating test code, changing the Parser class, changing the StringParser class (which instantiates StringNode s) and changing StringNode .

Here’s how I updated the above test to drive the creation of this decoding embellishment:

public void testDecodingAmpersand() throws Exception {
   String ENCODED_WORKSHOP_TITLE =
   "The Testing &amp; Refactoring Workshop";

   String DECODED_WORKSHOP_TITLE =
   "The Testing & Refactoring Workshop";

   StringBuffer decodedContent = new StringBuffer();
   Parser parser = Parser.createParser(ENCODED_WORKSHOP_TITLE);
    parser.setNodeDecoding(true);  // tell parser to decode StringNodes
   NodeIterator nodes = parser.elements();

   while (nodes.hasMoreNodes())
      decodedContent.append(nodes.nextNode().toPlainTextString());

   assertEquals("decoded content",
      DECODED_WORKSHOP_TITLE,
      decodedContent.toString()
   );
}

True to the nature of test-driven development, this updated code wouldn’t even compile until I added the code necessary for parser.setNodeDecoding(true) . My first step was to extend the Parser class to include a flag for toggling StringNode decoding on or off:

public class Parser...
    private boolean shouldDecodeNodes = false;

    public void setNodeDecoding(boolean shouldDecodeNodes) {
       this.shouldDecodeNodes = shouldDecodeNodes;
    }

Next, the StringParser class needed some changes. It contains a method called find(…) that locates, instantiates, and returns StringNode instances during parsing. Here’s a fragment of the code:

public class StringParser...
   public Node find(NodeReader reader, String input, int position, boolean balance_quotes) {
     ...
     return new StringNode(textBuffer, textBegin, textEnd);
   }

I also changed this code to support the new decoding option:

public class StringParser...
   public Node find(NodeReader reader, String input, int position, boolean balance_quotes) {
      ...
      return new StringNode(
         textBuffer, textBegin, textEnd,  reader.getParser().shouldDecodeNodes());
   }

That code wouldn’t compile until I added to the Parser class the shouldDecodeNodes() method and created a new StringNode constructor that would take the boolean value supplied by shouldDecodeNodes() :

public class Parser...
    public boolean shouldDecodeNodes() {
       return shouldDecodeNodes;
    }

public class StringNode extends Node...
    private boolean shouldDecode = false;

    public StringNode(StringBuffer textBuffer, int textBegin, int textEnd, boolean shouldDecode) {
       this(textBuffer, textBegin, textEnd);
       this.shouldDecode = shouldDecode;
    }

Finally, to complete the implementation and make the test pass, I needed to write decoding logic in StringNode :

public class StringNode...
   public String toPlainTextString() {
      String result = textBuffer.toString();
       if (shouldDecode)
          result = Translate.decode(result);
      return result;
   }

My tests were now passing. I observed that the parser’s new decoding embellishment didn’t unduly bloat the code. Yet once you support one embellishment, it’s often easy to find others worth supporting. And sure enough, when I looked over more parser client code, I found that it was common to remove escape characters (like \n for newline, \t for tabs) from StringNode instances. So I decided to give the parser an embellishment to remove escape characters as well. Doing that meant adding another flag to the Parser class (which I called shouldRemoveEscapeCharacters ), updating StringParser to call a StringNode constructor that could handle both the decoding option and the new option for removing escape characters, and adding the following new code to StringNode :

public class StringNode...
    private boolean shouldRemoveEscapeCharacters = false;

    public StringNode(StringBuffer textBuffer, int textBegin, int textEnd,
                      boolean shouldDecode, boolean shouldRemoveEscapeCharacters) {
       this(textBuffer, textBegin, textEnd);
       this.shouldDecode = shouldDecode;
       this.shouldRemoveEscapeCharacters = shouldRemoveEscapeCharacters;
    }

   public String toPlainTextString() {
      String result = textBuffer.toString();
      if (shouldDecode)
         result = Translate.decode(result);
       if (shouldRemoveEscapeCharacters)
          result = ParserUtils.removeEscapeCharacters(result);
      return result;
   }

The embellishments for decoding and escape character removal simplified client code to the parser. But I didn’t like the number of changes I was forced to make across several parser classes just to support each new embellishment. Making such changes across multiple classes was an indication of the code smell Solution Sprawl ( 43 ). This smell resulted from:

•   Too much initialization logic , that is, code to tell Parser and StringParser to toggle an embellishment on or off and to initialize StringNode instances to use one or more embellishments

•   Too much embellishment logic , that is, special-case logic in StringNode to support each embellishment

I reasoned that the initialization problem could best be solved by handing the parser a Factory instance that instantiated the appropriately configured StringNode instances at runtime (see Move Creation Knowledge to Factory , 68 ). I further reasoned that the buildup of embellishment logic could be solved by refactoring to either a Decorator or a Strategy. I decided to revisit the initialization problem later and focus on the Decorator or Strategy refactoring now.

So which pattern would be more useful here? As I explored sibling classes of StringNode (such as RemarkNode , which represents a comment in HTML), I saw that they could also benefit from the decoding and escape character removal behavior now in StringNode . If I refactored that behavior into Strategy classes, then StringNode and its sibling classes would need to be altered to know about the Strategy classes. This would not be necessary with a Decorator implementation because the behavior in Decorators could be transparently wrapped around instances of StringNode and its siblings. That appealed to me; I did not like the idea of changing a lot of code in many classes.

What about performance? I did not give much consideration to performance because I tend to let a profiler lead me to performance problems. I further reasoned that if the Decorator refactoring led to slow performance, it wouldn’t require much work to refactor it to a Strategy implementation.

Having decided that a Decorator would be better than a Strategy, I now needed to decide whether a Decorator would really be a good fit for the code in question. As I mentioned at the beginning of the Mechanics section, it’s vital to learn whether a class is primitive enough to make decoration viable. Primitive, in this case, means that the class doesn’t implement a large number of public methods or declare many fields. I discovered that StringNode is primitive, but its superclass, AbstractNode , is not. The diagram on the following page shows AbstractNode .

Example

I counted ten public methods on AbstractNode . That’s not exactly what I’d call a narrow interface, but it isn’t broad either. I decided it’s small enough to do this refactoring.

Getting ready to refactor, my goal now is to get the embellishment logic out of StringNode by putting each embellishment into its own StringNode Decorator class. If there is ever a need to support multiple embellishments, it will be possible to configure combinations of StringNode Decorators prior to executing a parse.

The following diagram illustrates where StringNode fits into the Node hierarchy and how its decoding logic looked before it was refactored to use a DecodingNode Decorator.

Example

Here are the steps for refactoring StringNode ’s decoding logic to a Decorator.

1.  My first step is to identify or create an enclosure type, a class or interface that declares all public methods of StringNode and whatever public methods it inherits. A good enclosure type won’t contain fields (i.e., state). So StringNode ’s superclass, AbstractNode , is not a good enclosure type because it contains the two primitive int fields, nodeBegin and nodeEnd . Why does it matter whether a class contains fields? Decorators add behavior to the objects they decorate, but they don’t need duplicate copies of the fields in those objects. In this case, because StringNode already inherits nodeBegin and nodeEnd from AbstractNode , Decorators of StringNode don’t also need to inherit those fields.

     So I rule out AbstractNode as the enclosure type. The next natural place to look is the interface that AbstractNode implements, which is called Node . The following diagram shows this interface.

Example

     This would be the perfect enclosure type, except that it doesn’t include StringNode ’s two public methods, getText() and setText(…) . I must add these methods to the Node interface in order to pave the way for creating a transparent enclosure for StringNode . I’m not happy about this step, for it means expanding the interface of Node just to accommodate this refactoring. However, I proceed anyway, knowing that a future refactoring will combine toPlainTextString() and getText() , thereby reducing the size of the Node interface.

     In Java, adding the getText() and setText(…) methods to the Node interface means that all concrete classes that implement Node must implement getText() and setText(…) or inherit implementations of them. StringNode contains the implementations of getText() and setText(…) , but AbstractNode and some of its subclasses (which aren’t shown in this example) have no such implementation (or have only one of the two methods defined). To obtain the solution I need, I must apply the refactoring Unify Interfaces (343) . This refactoring adds getText() and setText(…) to Node and outfits AbstractNode with the following default (do-nothing) versions of the methods, which all subclasses either inherit and/or override:

public abstract class AbstractNode...
    public String getText() {
       return null;
    }

    public void setText(String text) {
    }

3.  I can now work towards replacing the decoding embellishment inside StringNode by applying the refactoring Replace Conditional with Polymorphism [ F ]. Applying that refactoring involves producing an inheritance structure that will look like the one shown here.

Example

     To produce this inheritance structure, I apply Replace Type Code with Subclasses [ F ]. The first step in implementing that refactoring is to apply Self-Encapsulate Field [ F ] on shouldDecode , the type code inside StringNode . The following code shows where shouldDecode is referenced or used within StringNode :

public class StringNode extends AbstractNode...
    private boolean shouldDecode = false;

   public StringNode(
      StringBuffer textBuffer, int textBegin, int textEnd, boolean shouldDecode) {
      this(textBuffer, textBegin, textEnd);
       this.shouldDecode  = shouldDecode;
   }

   public String toPlainTextString() {
      String result = textBuffer.toString();
      if  (shouldDecode)
         result = Translate.decode(result);
      return result;
   }

     To self-encapsulate shouldDecode , I make the following changes:

public class StringNode extends AbstractNode...
   public StringNode(
      StringBuffer textBuffer, int textBegin, int textEnd, boolean shouldDecode) {
      this(textBuffer, textBegin, textEnd);
       setShouldDecode(shouldDecode);
   }

   public String toPlainTextString() {
      String result = textBuffer.toString();
      if ( shouldDecode() )
         result = Translate.decode(result);
      return result;
   }

    private void setShouldDecode(boolean shouldDecode) {
       this.shouldDecode = shouldDecode;
    }

    private boolean shouldDecode() {
       return shouldDecode;
    }

     I’ve nearly self-encapsulated shouldDecode , except for the new StringNode constructor. Because it accepts the type code shouldDecode as a parameter, I need to replace this constructor with a Creation Method (as described in the mechanics to Replace Type Code with Subclasses [ F ]). The Decorator mechanics also tell me to make the return type of this Creation Method be Node , which is the enclosure type that will be vital to implementing the Decorator pattern. Here’s the new Creation Method:

public class StringNode extends AbstractNode...
    private  StringNode(
      StringBuffer textBuffer, int textBegin, int textEnd, boolean shouldDecode) {
      this(textBuffer, textBegin, textEnd);
      setShouldDecode(shouldDecode);
   }

   public static Node createStringNode(
       StringBuffer textBuffer, int textBegin, int textEnd, boolean shouldDecode) {
       return new StringNode(textBuffer, textBegin, textEnd, shouldDecode);
    }

     And here is the updated client call to the new Creation Method:

public class StringParser...
   public  Node  find(
      NodeReader reader,String input,int position, boolean balance_quotes) {
      ...
      return  StringNode.createStringNode(
          textBuffer, textBegin, textEnd, reader.getParser().shouldDecodeNodes());

     I compile and test to see that these changes didn’t break anything. Now, the second step in the mechanics for Replace Type Code with Subclasses [ F ] says:

     For each value of the type code, create a subclass. Override the getting method of the type code in the subclass to return the relevant value. [ F , 224]

     The type code, shouldDecode , has two values: true and false . I decide that StringNode itself will handle the false case (i.e., don’t perform any decoding), while a new subclass called DecodingNode will handle the true case. I start by creating DecodingNode and overriding the shouldDecode() method (which I now make protected ):

public class StringNode extends AbstractNode...
    protected boolean shouldDecode()...

public class DecodingNode extends StringNode {
    public DecodingNode(StringBuffer textBuffer, int textBegin, int textEnd) {
       super(textBuffer, textBegin, textEnd);
    }

    protected boolean shouldDecode() {
       return true;
    }
}

     I now need to alter the Creation Method to create the appropriate object based on the value of shouldDecode :

public class StringNode extends AbstractNode...
   private boolean shouldDecode = false;

   public static Node createStringNode(
      StringBuffer textBuffer, int textBegin, int textEnd, boolean shouldDecode) {
       if (shouldDecode)
          return new DecodingNode(textBuffer, textBegin, textEnd);
      return new StringNode(textBuffer, textBegin, textEnd , shouldDecode );
   }

     I compile and test to see that everything is still working.

     At this point I can simplify StringNode by removing the shouldDecode type code, its setting method, and the constructor that accepts it. All I have to do to make this work is to return false from StringNode ’s shouldDecode() method:

public class StringNode extends AbstractNode...
    private boolean shouldDecode = false;

   public StringNode(StringBuffer textBuffer,int textBegin,int textEnd) {
      super(textBegin,textEnd);
      this.textBuffer = textBuffer;
   }

    private StringNode(
       StringBuffer textBuffer, int textBegin, int textEnd, boolean shouldDecode) {
       this(textBuffer, textBegin, textEnd);
       setShouldDecode(shouldDecode);
    }

   public static Node createStringNode(
      StringBuffer textBuffer, int textBegin, int textEnd, boolean shouldDecode) {
      if (shouldDecode)
         return new DecodingNode(textBuffer, textBegin, textEnd);
      return new StringNode(textBuffer, textBegin, textEnd);
   }

    private void setShouldDecode(boolean shouldDecode) {
       this.shouldDecode = shouldDecode;
    }

   protected boolean shouldDecode() {
       return false;
   }

     Everything works fine after I compile and test. I’ve now successfully created an inheritance structure that will enable me to apply Replace Conditional with Polymorphism [ F ].

     I now want to rid StringNode of the conditional logic inside toPlainTextString() . Here’s how the method looks before I make changes:

public class StringNode extends AbstractNode...
   public String toPlainTextString() {
      String result = textBuffer.toString();
      if (shouldDecode())
         result = Translate.decode(result);
      return result;
   }

     My first step is to give DecodingNode an overriding version of toPlainTextString() :

public class DecodingNode extends StringNode...
    public String toPlainTextString() {
       return Translate.decode(textBuffer.toString());
    }

     I compile and test to see that this minor change doesn’t upset anything. Now I remove the logic that I had copied into DecodingNode from StringNode :

public class StringNode extends AbstractNode...
   public String toPlainTextString() {
       return textBuffer.toString();
       String result = textBuffer.toString();

       if (shouldDecode())
          result = Translate.decode(result);
       return result;
   }

     I can now safely delete the shouldDecode() method in both StringNode and DecodingNode :

public class StringNode extends AbstractNode...
    protected boolean shouldDecode() {
       return false;
    }

public class DecodingNode extends StringNode...
    protected boolean shouldDecode() {
       return true;
    }

     There is also a small amount of duplication in DecodingNode ’s toPlainTextString() : the call to textBuffer.toString() is identical to the call in StringNode ’s toPlainTextString() . I can remove this duplication by having DecodingNode call its superclass, as follows:

public class DecodingNode extends StringNode...
   public String toPlainTextString() {
      return Translate.decode( super.toPlainTextString() );
   }

      StringNode currently has no trace of the type code shouldDecode , and the conditional decoding logic in toPlainTextString() has been replaced with polymorphism.

3.  The next step is to apply the refactoring Replace Inheritance with Delegation [ F ]. That refactoring’s mechanics tell me to begin by creating a field in the subclass, DecodingNode , that refers to itself:

public class DecodingNode extends StringNode...3.
private Node delegate = this

     I make delegate ’s type be Node rather than DecodingNode because DecodingNode will soon be a Decorator and that which it decorates (and delegates to) must implement the same interface as it does (i.e., Node ).

     I now replace direct calls to inherited StringNode methods to make them use delegation. The only DecodingNode method that makes a call to a superclass method is toPlainTextString() :

public class DecodingNode extends StringNode...
   public String toPlainTextString() {
      return Translate.decode(super.toPlainTextString());
   }

     I change this call to use the new field, delegate :

public class DecodingNode extends StringNode...
   public String toPlainTextString() {
      return Translate.decode( delegate .toPlainTextString());
   }

     I compile and test to see whether this still works. It doesn’t! It gets the code into an infinite loop. I then notice that Martin mentions this in a note on the mechanics for Replace Inheritance with Delegation :

You won’t be able to replace any methods that invoke a method on super that is defined on the subclass, or they may get into an infinite recurse. These methods can be replaced only after you have broken inheritance. [ F , 353]

     So I undo that last step and press on with the refactoring. My next step is to break inheritance, that is, to make DecodingNode no longer a subclass of StringNode . During this step I must also make delegate point to a real instance of StringNode :

public class DecodingNode  extends StringNode  ...
   private Node delegate  \= this;

   public DecodingNode(StringBuffer textBuffer, int textBegin, int textEnd) {
       delegate = new StringNode(textBuffer, textBegin, textEnd);
   }

     My compiler is happy with this code, but the following code in StringNode no longer compiles:

public class StringNode extends AbstractNode...
   public static Node createStringNode(
      StringBuffer textBuffer, int textBegin, int textEnd, boolean shouldDecode) {

      if (shouldDecode)
         return new DecodingNode(textBuffer, textBegin, textEnd);
      return new StringNode(textBuffer, textBegin, textEnd);
   }

     The problem is that createStringNode wants to return objects that implement the Node interface, and DecodingNode no longer implements that interface. I solve this by making DecodingNode implement Node :

public class DecodingNode  implements Node...
   private Node delegate;

   public DecodingNode(StringBuffer textBuffer, int textBegin, int textEnd) {
      delegate = new StringNode(textBuffer, textBegin, textEnd);
   }

   public String toPlainTextString() {
      return Translate.decode(delegate.toPlainTextString());
   }

    public void accept(NodeVisitor visitor) {
    }

    public void collectInto(NodeList collectionList, Class nodeType) {
    }

    // etc.

     The final step of Replace Inheritance with Delegation involves having each of the methods I’ve just added to DecodingNode —methods defined by Node —call the corresponding methods on delegate :

public class DecodingNode implements Node...

   public void accept(NodeVisitor visitor) {
       delegate.accept(visitor);
   }

   public void collectInto(NodeList collectionList, Class nodeType) {
       delegate.collectInto(collectionList, nodeType);
   }

   // etc.

4.   DecodingNode is now almost a Decorator. The one thing preventing it from being an actual Decorator is that the field that it delegates to, delegate , is instantiated inside DecodingNode rather then being passed in via a constructor argument. To fix that, I apply Extract Parameter (346) and Remove Parameter [ F ] (to remove unnecessary parameters). I make the following changes to implement those refactorings:

public class StringNode extends AbstractNode...
   public static Node createStringNode(
      StringBuffer textBuffer, int textBegin, int textEnd, boolean shouldDecode) {
      if (shouldDecode)
         return new DecodingNode( new StringNode(textBuffer, textBegin, textEnd) );
      return new StringNode(textBuffer, textBegin, textEnd);
   }

public class DecodingNode implements Node...
   private Node delegate;

   public DecodingNode( Node newDelegate ) {
      delegate =  newDelegate ;
   }

DecodingNode is now a full-fledged Decorator. The following diagram shows how it fits into the Node hierarchy.

Example

Replace State-Altering Conditionals with State

The conditional expressions that control
an object’s state transitions are complex.

Replace the conditionals with State classes that handle
specific states and transitions between them.

Replace State-Altering Conditionals with State

Motivation

The primary reason for refactoring to the State pattern [ DP ] is to tame overly complex state-altering conditional logic. Such logic, which tends to spread itself throughout a class, controls an object’s state, including how states transition to other states. When you implement the State pattern, you create classes that represent specific states of an object and the transitions between those states. The object that has its state changed is known in Design Patterns [ DP ] as the context . A context delegates state-dependent behavior to a state object. State objects make state transitions at runtime by making the context point to a different state object.

Moving state-altering conditional logic out of one class and into a family of classes that represent different states can yield a simpler design that provides a better bird’s-eye view of the transitions between states. On the other hand, if you can easily understand the state transition logic in a class, you likely don’t need to refactor to the State pattern (unless you plan to add many more state transitions in the future). The Example section for this refactoring shows a case where state-altering conditional logic is no longer easy to follow or extend and where the State pattern can make a real difference.

Before refactoring to State, it’s always a good idea to see if simpler refactorings, such as Extract Method [ F ], can help clean up the state-changing conditional logic. If they can’t, refactoring to State can help remove or reduce many lines of conditional logic, yielding simpler code that’s easier to understand and extend.

This Replace State-Altering Conditionals with State refactoring is different from Martin Fowler’s Replace Type Code with State/Strategy [ F ] for the following reasons.

•   Differences between State and Strategy :The State pattern is useful for a class that must easily transition between instances of a family of state classes, while the Strategy pattern is useful for allowing a class to delegate execution of an algorithm to an instance of a family of Strategy classes. Because of these differences, the motivation and mechanics for refactoring to these two patterns differs (see Replace Conditional Logic with Strategy , 129).

•   End-to-end mechanics :Martin deliberately doesn’t document a full refactoring to the State pattern because the complete implementation depends on a further refactoring he wrote, Replace Conditional with Polymorphism [ F ]. While I respect that decision, I thought it would be more helpful to readers to understand how the refactoring works from end to end, so my Mechanics and Example sections delineate all of the steps to get you from conditional state-changing logic to a State implementation.

If your state objects have no instance variables (i.e., they are stateless ), you can optimize memory usage by having context objects share instances of the stateless state instances. The Flyweight and Singleton patterns [ DP ] are often used to implement sharing (e.g., see Limit Instantiation with Singleton , 296 ). However, it’s always best to add state-sharing code after your users experience system delays and a profiler points you to the state-instantiation code as a prime bottleneck.

Benefits and Liabilities

+  Reduces or removes state-changing conditional logic.

+  Simplifies complex state-changing logic.

+  Provides a good bird’s-eye view of state-changing logic.

–  Complicates a design when state transition logic is already easy to follow.

Mechanics

1.  The context class is a class that contains the original state field , a field that gets assigned to or compared against a family of constants during state transitions. Apply Replace Type Code with Class (286) on the original state field such that its type becomes a class. We’ll call that new class the state superclass.

     The context class is known as State: Context and the state superclass as State: State in Design Patterns [ DP ].

Image   Compile.

2.  Each constant in the state superclass now refers to an instance of the state superclass. Apply Extract Subclass [ F ] to produce one subclass (known as State: ConcreteState [ DP ]) per constant, then update the constants in the state superclass so that each refers to the correct subclass instance of the state superclass. Finally, declare the state superclass to be abstract.

Image   Compile.

3.  Find a context class method that changes the value of the original state field based on state transition logic. Copy this method to the state superclass, making the simplest changes possible to make the new method work. (A common, simple change is to pass the context class to the method in order to have code call methods on the context class.) Finally, replace the body of the context class method with a delegation call to the new method.

Image   Compile and test.

     Repeat this step for every context class method that changes the value of the original state field based on state transition logic.

4.  Choose a state that the context class can enter, and identify which state superclass methods make this state transition to other states. Copy the identified method(s), if any, to the subclass associated with the chosen state and remove all unrelated logic.

      Unrelated logic usually includes verifications of a current state or logic that transitions to unrelated states.

Image   Compile and test.

     Repeat for all states the context class can enter.

5.  Delete the bodies of each of the methods copied to the state superclass during step 3 to produce an empty implementation for each method.

Image   Compile and test.

Example

To understand when it makes sense to refactor to the State pattern, it helps to study a class that manages its state without requiring the sophistication of the State pattern. SystemPermission is such a class. It uses simple conditional logic to keep track of the state of a permission request to access a software system. Over the lifetime of a SystemPermission object, an instance variable named state transitions between the states requested, claimed, denied , and granted . Here is a state diagram of the possible transitions:

Example

Below is the code for SystemPermission and a fragment of test code to show how the class gets used:

public class SystemPermission...
  private SystemProfile profile;
  private SystemUser requestor;
  private SystemAdmin admin;
  private boolean isGranted;
  private String state;

  public final static String REQUESTED = "REQUESTED";
  public final static String CLAIMED = "CLAIMED";
  public final static String GRANTED = "GRANTED";
  public final static String DENIED = "DENIED";

  public SystemPermission(SystemUser requestor, SystemProfile profile) {
    this.requestor = requestor;
    this.profile = profile;
    state = REQUESTED;
    isGranted = false;
    notifyAdminOfPermissionRequest();
  }

  public void claimedBy(SystemAdmin admin) {
    if (!state.equals(REQUESTED))
      return;
    willBeHandledBy(admin);
    state = CLAIMED;
  }

  public void deniedBy(SystemAdmin admin) {
    if (!state.equals(CLAIMED))
      return;
    if (!this.admin.equals(admin))
      return;
    isGranted = false;
    state = DENIED;
    notifyUserOfPermissionRequestResult();
  }

  public void grantedBy(SystemAdmin admin) {
    if (!state.equals(CLAIMED))
      return;
    if (!this.admin.equals(admin))
      return;
    state = GRANTED;
    isGranted = true;
    notifyUserOfPermissionRequestResult();
  }

public class TestStates extends TestCase...
  private SystemPermission permission;

  public void setUp() {
    permission = new SystemPermission(user, profile);
  }

  public void testGrantedBy() {
    permission.grantedBy(admin);
    assertEquals("requested", permission.REQUESTED, permission.state());
    assertEquals("not granted", false, permission.isGranted());
    permission.claimedBy(admin);
    permission.grantedBy(admin);
    assertEquals("granted", permission.GRANTED, permission.state());
    assertEquals("granted", true, permission.isGranted());
  }

Notice how the instance variable, state , gets assigned to different values as clients call specific SystemPermission methods. Now look at the overall conditional logic in SystemPermission . This logic is responsible for transitioning between states, but the logic isn’t very complicated so the code doesn’t require the sophistication of the State pattern.

This conditional state-changing logic can quickly become hard to follow as more real-world behavior gets added to the SystemPermission class. For example, I helped design a security system in which users needed to obtain UNIX and/or database permissions before the user could be granted general permission to access a given software system. The state transition logic that requires UNIX permission before general permission may be granted looks like this:

Example

Adding support for UNIX permission makes SystemPermission ’s state-altering conditional logic more complicated than it used to be. Consider the following:

public class SystemPermission...
  public void claimedBy(SystemAdmin admin) {
    if (!state.equals(REQUESTED) && !state.equals(UNIX_REQUESTED))
      return;
    willBeHandledBy(admin);
    if (state.equals(REQUESTED))
      state = CLAIMED;
    else if (state.equals(UNIX_REQUESTED))
      state = UNIX_CLAIMED;
  }

  public void deniedBy(SystemAdmin admin) {
    if (!state.equals(CLAIMED) && !state.equals(UNIX_CLAIMED))
      return;
    if (!this.admin.equals(admin))
      return;
    isGranted = false;
    isUnixPermissionGranted = false;
    state = DENIED;
    notifyUserOfPermissionRequestResult();
  }

  public void grantedBy(SystemAdmin admin) {
    if (!state.equals(CLAIMED) && !state.equals(UNIX_CLAIMED))
      return;
    if (!this.admin.equals(admin))
      return;

    if (profile.isUnixPermissionRequired() && state.equals(UNIX_CLAIMED))
      isUnixPermissionGranted = true;
    else if (profile.isUnixPermissionRequired() &&
      !isUnixPermissionGranted()) {
      state = UNIX_REQUESTED;
      notifyUnixAdminsOfPermissionRequest();
      return;
    }
    state = GRANTED;
    isGranted = true;
    notifyUserOfPermissionRequestResult();
  }

An attempt can be made to simplify this code by applying Extract Method [ F ]. For example, I could refactor the grantedBy() method like so:

public void grantedBy(SystemAdmin admin) {
  if ( !isInClaimedState() )
    return;

  if (!this.admin.equals(admin))
    return;
  if ( isUnixPermissionRequestedAndClaimed() )
    isUnixPermissionGranted = true;
  else if ( isUnixPermisionDesiredButNotRequested() ) {
    state = UNIX_REQUESTED;
    notifyUnixAdminsOfPermissionRequest();
    return;
  }
  ...

Although that’s an improvement, SystemPermission now has lots of state-specific Boolean logic (e.g., methods like isUnixPermissionRequestedAndClaimed()) , and the grantedBy() method still isn’t simple. It’s time to see how I simplify things by refactoring to the State pattern.

1.   SystemPermission has a field called state , which is of type String . The first step is to change state ’s type to be a class by applying the refactoring Replace Type Code with Class (286) . This yields the following new class:

public class PermissionState {
   private String name;

   private PermissionState(String name) {
     this.name = name;
   }

   public final static PermissionState REQUESTED = new PermissionState("REQUESTED");
   public final static PermissionState CLAIMED = new PermissionState("CLAIMED");
   public final static PermissionState GRANTED = new PermissionState("GRANTED");
   public final static PermissionState DENIED = new PermissionState("DENIED");
   public final static PermissionState UNIX_REQUESTED =
     new PermissionState("UNIX_REQUESTED");
   public final static PermissionState UNIX_CLAIMED = new PermissionState("UNIX_CLAIMED");

   public String toString() {
     return name;
   }
}

     The refactoring also replaces SystemPermission ’s state field with one called permissionState , which is of type PermissionState :

public class SystemPermission...
   private PermissionState permissionState;

  public SystemPermission(SystemUser requestor, SystemProfile profile) {
    ...

     setState(PermissionState.REQUESTED);
    ...
  }

  public  PermissionState  getState() {
    return  permissionState ;
  }

   private void setState(PermissionState state) {
     permissionState = state;
   }

  public void claimedBy(SystemAdmin admin) {
     if (!getState().equals(PermissionState.REQUESTED)
      && !getState().equals(PermissionState.UNIX_REQUESTED))
        return;
     ...
  }

  etc...

2.   PermissionState now contains six constants, all of which are instances of PermissionState . To make each of these constants an instance of a subclass of PermissionState , I apply Extract Subclass [ F ] six times to produce the result shown in the following diagram.

Example

     Because no client will ever need to instantiate PermissionState , I declare it to be abstract:

public  abstract  class PermissionState...

     The compiler is happy with all of the new code, so I press on.

3.  Next, I find a method on SystemPermission that changes the value of permission based on state transition logic. There are three such methods in SystemPermission : claimedBy() , deniedBy() , and grantedBy() . I start by working with claimedBy() . I must copy this method to PermissionState , making enough changes to get it to compile and then replacing the body of the original claimedBy() method with a call to the new PermissionState version:

public class SystemPermission...
   private  void setState(PermissionState state) {  // now has package-level visibility
    permissionState = state;
  }

  public void claimedBy(SystemAdmin admin) {
     permissionState.claimedBy(admin, this);
  }

   void willBeHandledBy(SystemAdmin admin) {
     this.admin = admin;
   }

abstract class PermissionState...
   public void claimedBy(SystemAdmin admin, SystemPermission permission) {
     if (!permission.getState().equals(REQUESTED) &&
         !permission.getState().equals(UNIX_REQUESTED))
       return;
     permission.willBeHandledBy(admin);
     if (permission.getState().equals(REQUESTED))
       permission.setState(CLAIMED);
     else if (permission.getState().equals(UNIX_REQUESTED)) {
       permission.setState(UNIX_CLAIMED);
     }
   }

     After I compile and test to see that the changes worked, I repeat this step for deniedBy() and grantedBy() .

4.  Now I choose a state that SystemPermission can enter and identify which PermissionState methods make this state transition to other states. I’ll start with the REQUESTED state. This state can only transition to the CLAIMED state, and the transition happens in the PermissionState.claimedBy() method. I copy that method to the PermissionRequested class:

class PermissionRequested extends PermissionState...
   public void claimedBy(SystemAdmin admin, SystemPermission permission) {
     if (!permission.getState().equals(REQUESTED) &&
         !permission.getState().equals(UNIX_REQUESTED))
       return;
     permission.willBeHandledBy(admin);
     if (permission.getState().equals(REQUESTED))
       permission.setState(CLAIMED);
     else if (permission.getState().equals(UNIX_REQUESTED)) {
       permission.setState(UNIX_CLAIMED);
     }
   }
}

     A lot of logic in this method is no longer needed. For example, anything related to the UNIX_REQUESTED state isn’t needed because we’re only concerned with the REQUESTED state in the PermissionRequested class. We also don’t need to check whether our current state is REQUESTED because the fact that we’re in the PermissionRequested class tells us that. So I can reduce this code to the following:

class PermissionRequested extends Permission...
  public void claimedBy(SystemAdmin admin, SystemPermission permission) {
     permission.willBeHandledBy(admin);
     permission.setState(CLAIMED);
  }
}

     As always, I compile and test to make sure I didn’t break anything. Now I repeat this step for the other five states. Let’s look at what is required to produce the PermissionClaimed and PermissionGranted states.

     The CLAIMED state can transition to DENIED , GRANTED , or UNIX_REQUESTED . The deniedBy() or grantedBy() methods take care of these transitions, so I copy those methods to the PermissionClaimed class and delete unnecessary logic:

class PermissionClaimed extends PermissionState...
  public void deniedBy(SystemAdmin admin, SystemPermission permission) {
     if (!permission.getState().equals(CLAIMED) &&
         !permission.getState().equals(UNIX_CLAIMED))
       return;
    if (!permission.getAdmin().equals(admin))
      return;
    permission.setIsGranted(false);
    permission.setIsUnixPermissionGranted(false);
    permission.setState(DENIED);
    permission.notifyUserOfPermissionRequestResult();
  }

  public void grantedBy(SystemAdmin admin, SystemPermission permission) {
     if (!permission.getState().equals(CLAIMED) &&
        ! permission.getState().equals(UNIX_CLAIMED))
       return;
    if (!permission.getAdmin().equals(admin))
      return;

     if (permission.getProfile().isUnixPermissionRequired()
      && permission.getState().equals(UNIX_CLAIMED))
       permission.setIsUnixPermissionGranted(true);
     else if (permission.getProfile().isUnixPermissionRequired()
         && !permission.isUnixPermissionGranted()) {
      permission.setState(UNIX_REQUESTED);
      permission.notifyUnixAdminsOfPermissionRequest();
      return;
    }
    permission.setState(GRANTED);
    permission.setIsGranted(true);
    permission.notifyUserOfPermissionRequestResult();
  }

     For PermissionGranted , my job is easy. Once a SystemPermission reaches the GRANTED state, it has no further states it can transition to (i.e., it’s at an end state). So this class doesn’t need to implement any transition methods (e.g., claimedBy() ). In fact, it really needs to inherit empty implementations of the transition methods, which is exactly what will happen after the next step in the refactoring.

5.  In PermissionState , I can now delete the bodies of claimedBy() , deniedBy() , and grantedBy() , leaving the following:

abstract class PermissionState {
  public String toString();
  public void claimedBy(SystemAdmin admin, SystemPermission permission) {}
  public void deniedBy(SystemAdmin admin, SystemPermission permission) {}
  public void grantedBy(SystemAdmin admin, SystemPermission permission) {}
}

I compile and test to confirm that the states continue to behave correctly. They do. The only remaining question is how best to celebrate this successful refactoring to the State pattern.

Replace Implicit Tree with Composite

You implicitly form a tree structure, using a
primitive representation, such as a String.

Replace your primitive representation with a Composite.

Replace Implicit Tree with Composite

Motivation

Data or code forms an implicit tree when it’s not explicitly structured as a tree but may be represented as a tree. For example, the code that creates the XML data in the previous code sketch outputs values like this:

String expectedResult =
  "<orders>" +
    "<order id=’321’>" +
      "<product id=’f1234’ color=’red’ size=’medium’>" +
        "<price currency=’USD’>" +
          "8.95" +
        "</price>" +
        "Fire Truck" +
      "</product>" +
      "<product id=’p1112’ color=’red’>" +
        "<price currency=’USD’>" +
          "230.0" +
        "</price>" +
        "Toy Porsche Convertible" +
      "</product>" +
    "</order>" +
  "</orders>";

The structure of this XML may be represented as the following tree.

Motivation

Conditional logic can also form an implicit tree. Consider the conditional logic in the following code, which queries products from a repository:

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;
  }

The structure of this conditional logic may also be represented as a tree.

Motivation

The implicit trees in these examples are different in nature, yet both may be modeled by using a Composite [ DP ]. What’s the primary motivation for such a refactoring? To make the code simpler to work with and less bloated.

For example, producing XML as a Composite is simpler and requires less code when you don’t have to repeatedly format and close tags: a Composite tag can do that work for you. Transforming the above conditional logic to a Composite has a similar motivation, with one twist: the refactoring makes sense only when there is a proliferation of similar conditional logic:

public class ProductFinder...
  public List byColor(Color color)...
     if (product.getColor() == color)...

  public List byColorAndBelowPrice(Color color, float price)...
     if (product.getPrice() < price && product.getColor() == color)...

  public List byColorAndAbovePrice(Color color, float price) {
     if (product.getColor() == color && product.getPrice() > price)...

  public List byColorSizeAndBelowPrice(Color color, int size, float price)...
     if (product.getColor() == color &&
         product.getSize() == size &&
         product.getPrice() < price)...

The above methods may be generalized to a single query method by representing each product query as a Composite. Replace Implicit Language with Interpreter (269) documents this transformation, which includes the implementation of a Composite.

Data-based implicit trees, like the earlier XML example, suffer from a tight coupling between the code that builds the implicit tree and how the tree is represented. Refactoring to a Composite loosens this coupling; however, the resulting client code is then coupled to the Composite. Sometimes you need another level of indirection to loosen such coupling. For example, on one project client code sometimes needed a Composite for building XML and sometimes needed to produce XML via a DOM . This led to the refactoring Encapsulate Composite with Builder (96) .

Implicit tree creation may be sufficient if your system doesn’t create many trees or the trees are small and manageable. You can always refactor to a Composite when it becomes hard to work with your implicit trees or your code begins to bloat because of implicit tree construction. The choice may also involve where you are in the evolution of new code. On a recent project, I was tasked with generating an HTML page from XML data using an XSLT processor. For this task, I needed to generate XML that would be used in the XSLT transformation. I knew I could use a Composite to build that XML, but I instead choose to build it by using an implicit tree. Why? Because I was more interested in going fast and facing every technical hurdle involved in doing the XSLT transformation than I was in producing good XML tree construction code. After completing the XSLT transformation, I went back to refactor the primitive tree construction code to use a Composite because that code was going to be emulated in many areas of the system.

Benefits and Liabilities

+  Encapsulates repetitive instructions like formatting, adding, or removing nodes.

+  Provides a generalized way to handle a proliferation of similar logic.

+  Simplifies construction responsibilities of a client.

–  Complicates a design when it’s simpler to construct implicit trees.

Mechanics

The mechanics presented in this section feature two paths for implementing this refactoring. One path, which is standard throughout the book, involves applying refactorings on an implicit tree to gradually refactor it to a Composite, while the other way involves performing test-driven development [ Beck, TDD ] to gradually refactor the implicit tree to a Composite. Both paths work well. I tend to use the test-driven approach when an implicit tree, like the XML in the earlier example, doesn’t lend itself well to applying refactorings like Extract Class [ F ].

1.  Identify an implicit leaf , a part of the implicit tree that could be modeled with a new class. This new class will be a leaf node (called Composite:Leaf in Design Patterns [ DP ]). Create a leaf node class by applying refactorings like Extract Class [ F ] or by doing test-driven development—whichever is easier given your context.

     If the implicit leaf has attributes, produce equivalents for these attributes in the leaf node, such that the representation of the entire leaf node, including its attributes, matches that of the implicit leaf.

Image   Compile and test.

2.  Replace every occurrence of the implicit leaf with an instance of the leaf node, such that the implicit tree now relies on the leaf node instead of the implicit leaf.

Image   Compile and test that the implicit tree still functions correctly.

3.  Repeat steps 1 and 2 for any additional parts of the implicit tree that represent an implicit leaf. Make sure that all leaf nodes you create share a common interface. You can create this interface by applying Extract Superclass [ F ] or Extract Interface [ F ].

4.  Identify an implicit parent , a part of the implicit tree that acts as a parent to implicit leaves. The implicit parent will become a parent node class (called Composite [ DP ]). Develop this class by applying refactorings or doing test-driven development—again, use whichever approach is easier in your context.

     Clients must be able to add leaf nodes to the parent node either through a constructor or an add(…) method. The parent node must treat all children identically (i.e., via their common interface). The parent node may or may not implement the common interface. If clients must be able to add parent nodes to parent nodes (as is mentioned in step 6) or if you don’t want client code to distinguish between a leaf node and a parent node (as is the motivation for Replace One/Many Distinctions with Composite , 224 ), make the parent node implement the common interface.

5.  Replace every occurrence of the implicit parent with code that uses a parent node instance, outfitted with the correct leaf node instances.

Image   Compile and test that the implicit tree still functions correctly.

6.  Repeat steps 4 and 5 for all additional implicit parents. Make it possible to add a parent node to a parent node only if your implicit parents support similar behavior.

Example

The code that produces the implicit tree in the code sketch at the beginning of this refactoring section comes from a shopping system. In that system, there is an OrdersWriter class, which has a getContents() method. Before proceeding with the refactoring, I first break the large getContents() method into smaller methods by applying Compose Method (123) and Move Accumulation to Collecting Parameter (313) :

public class OrdersWriter {
  private Orders orders;

  public OrdersWriter(Orders orders) {
    this.orders = orders;
  }

  public String getContents() {
    StringBuffer xml = new StringBuffer();
     writeOrderTo(xml);
    return xml.toString();
  }

   private void writeOrderTo(StringBuffer xml) {
     xml.append("<orders>");
     for (int i = 0; i < orders.getOrderCount(); i++) {
       Order order = orders.getOrder(i);
       xml.append("<order");
       xml.append(" id=’");
       xml.append(order.getOrderId());
       xml.append("’>");
       writeProductsTo(xml, order);
       xml.append("</order>");
     }
     xml.append("</orders>");
   }

   private void writeProductsTo(StringBuffer xml, Order order) {
     for (int j=0; j < order.getProductCount(); j++) {
       Product product = order.getProduct(j);
       xml.append("<product");
       xml.append(" id=’");
       xml.append(product.getID());
       xml.append("’");
       xml.append(" color=’");
       xml.append(colorFor(product));
       xml.append("’");
       if (product.getSize() != ProductSize.NOT_APPLICABLE) {
         xml.append(" size=’");
         xml.append(sizeFor(product));
         xml.append("’");
       }
       xml.append(">");
       writePriceTo(xml, product);
       xml.append(product.getName());
       xml.append("</product>");
     }
   }

   private void writePriceTo(StringBuffer xml, Product product) {
     xml.append("<price");
     xml.append(" currency=’");
     xml.append(currencyFor(product));
     xml.append("’>");
     xml.append(product.getPrice());
     xml.append("</price>");
   }

Now that getContents() has been refactored, it’s easier to see additional refactoring possibilities. One reader of this code noticed that the methods writeOrderTo(…) , writeProductsTo(…) , and writePriceTo(…) all loop through the domain objects Order , Product , and Price in order to extract data from them for use in producing XML. This reader wondered why the code doesn’t just ask the domain objects for their XML directly, rather than having to build it externally to the domain objects. In other words, if the Order class had a toXML() method and the Product and Price classes had one as well, obtaining XML for an Order would simply involve making one call to an Order’s toXML() method. That call would obtain the XML from the Order , as well as the XML from whatever Product instances were part of the Order and whatever Price was associated with each Product . This approach would take advantage of the existing structure of the domain objects, rather than recreating that structure in methods like writeOrderTo(…) , writeProductsTo(…) , and writePriceTo(…) .

As nice as this idea sounds, it isn’t a good design when a system must create many XML representations of the same domain objects. For example, the code we’ve been looking at comes from a shopping system that requires diverse XML representations for the domain objects:

   <order id=’987’ totalPrice=’14.00’>
     <product id=’f1234’ price=’9.00’ quantity=’1’>
       Fire Truck
     </product>
     <product id=’f4321’ price=’5.00’ quantity=’1’>
       Rubber Ball
     </product>
   </order>

   <orderHistory>
     <order date=’20041120’ totalPrice=’14.00’>
       <product id=’f1234’>
       <product id=’f4321’>
     </order>
   </orderHistory>

   <order id=’321’>
     <product id=’f1234’ color=’red’ size=’medium’>
       <price currency=’USD’>
         8.95
       </price>
       Fire Truck
     </product>
   </order>

Producing the above XML would be difficult and awkward using a single toXML() method on each domain object because the XML is so different in each case. Given such a situation, you can either choose to do the XML rendering external to the domain objects (as the writeOrderTo(…) , writeProductsTo(…) , and writePriceTo(…) methods do), or you can pursue a Visitor solution (see Move Accumulation to Visitor , 320 ).

For this shopping system, which generates a lot of diverse XML for the same domain objects, refactoring to Visitor makes a lot of sense. However, at the moment, the creation of the XML is still not simple; you have to get the formatting just right and remember to close every tag. I want to simplify this XML generation prior to refactoring to Visitor. Because the Composite pattern can help simplify the XML generation, I proceed with this refactoring.

1.  To identify an implicit leaf, I study fragments of test code, such as this one:

String expectedResult =
"<orders>" +
  "<order id=’321’>" +
    "<product id=’f1234’ color=’red’ size=’medium’>" +
      "<price currency=’USD’>" +

        "8.95" +
      "</price>" +
      "Fire Truck" +
    "</product>" +
  "</order>" +
"</orders>";

     Here, I face a decision: Which should I treat as an implicit leaf, the <price>…</price> tag or its value, 8.95 ? I choose the <price>…</price> tag because I know that the leaf node class I’ll create to correspond with the implicit leaf can easily represent the tag’s value, 8.95 .

     Another observation I make is that every XML tag in the implicit tree has a name, an optional number of attributes (name/value pairs), optional children, and an optional value. I ignore the optional children part for the moment (we’ll get to that in step 4). This means that I can produce one general leaf node to represent all implicit leaves in the implicit tree. I produce this class, which I call TagNode , using test-driven development. Here’s a test I write after already writing and passing some simpler tests:

public class TagTests extends TestCase...
   private static final String SAMPLE_PRICE = "8.95";
   public void testSimpleTagWithOneAttributeAndValue() {
     TagNode priceTag = new TagNode("price");
     priceTag.addAttribute("currency", "USD");
     priceTag.addValue(SAMPLE_PRICE);
     String expected =
       "<price currency=" +
       "’" +
       "USD" +
       "’>" +
       SAMPLE_PRICE +
       "</price>";
     assertEquals("price XML", expected, priceTag.toString());
   }

     Here’s the code to make the test pass:

public class TagNode {
   private String name = "";
   private String value = "";
   private StringBuffer attributes;

   public TagNode(String name) {
     this.name = name;
     attributes = new StringBuffer("");
   }

   public void addAttribute(String attribute, String value) {
     attributes.append(" ");

     attributes.append(attribute);
     attributes.append("=’");
     attributes.append(value);
     attributes.append("’");
   }

   public void addValue(String value) {
     this.value = value;
   }

   public String toString() {
     String result;
     result =
       "<" + name + attributes + ">" +
       value +
       "</" + name + ">";
     return result;
   }

2.  I can now replace the implicit leaf in the getContents() method with a TagNode instance:

public class OrdersWriter...
  private void writePriceTo(StringBuffer xml, Product product) {
     TagNode priceNode = new TagNode("price");
     priceNode.addAttribute("currency", currencyFor(product));
     priceNode.addValue(priceFor(product));
     xml.append(priceNode.toString());
     xml.append("<price");
     xml.append(" currency=’");
     xml.append(currencyFor(product));
     xml.append("’>");
     xml.append(product.getPrice());
     xml.append("</price>");
  }

     I compile and run tests to ensure that the implicit tree is still rendered correctly.

3.  Because TagNode models all of the implicit leaves in the XML, I do not need to repeat steps 1 and 2 to convert additional implicit leaves to leaf nodes, nor do I need to ensure that all newly created leaf nodes share a common interface—they already do.

4.  Now I identify an implicit parent by studying fragments of test code. I find that a <product> tag is a parent for a <price> tag, an <order> tag is a parent for a <product> tag, and an <orders> tag is a parent for an <order> tag. Yet because each of these implicit parents is already so similar in nature to the implicit leaf identified earlier, I see that I can produce a parent node by adding child-handling support to TagNode . I follow test-driven development to produce this new code. Here’s the first test I write:

public void testCompositeTagOneChild() {
   TagNode productTag = new TagNode("product");
   productTag.add(new TagNode("price"));
   String expected =
     "<product>" +
       "<price>" +
       "</price>" +
     "</product>";
   assertEquals("price XML", expected, productTag.toString());
}

     And here’s code to pass that test:

public class TagNode...
   private List children;

  public String toString() {
    String result;
    result = "<" + name + attributes + ">";
     Iterator it = children().iterator();
     while (it.hasNext()) {
       TagNode node = (TagNode)it.next();
       result += node.toString();
     }
    result += value;
    result += "</" + name + ">";
    return result;
  }

   private List children() {
     if (children == null)
       children = new ArrayList();
     return children;
   }

   public void add(TagNode child) {
     children().add(child);
   }

     Here’s a slightly more robust test:

public void testAddingChildrenAndGrandchildren() {
    String expected =
    "<orders>" +
      "<order>" +
         "<product>" +
         "</product>" +
      "</order>" +
    "</orders>";

    TagNode ordersTag = new TagNode("orders");
    TagNode orderTag = new TagNode("order");
    TagNode productTag = new TagNode("product");
    ordersTag.add(orderTag);
    orderTag.add(productTag);
    assertEquals("price XML", expected, ordersTag.toString());
}

     I continue writing and running tests until I’m satisfied that TagNode can behave as a proper parent node. When I’m done, TagNode is a class that can play all three participants in the Composite pattern:

Example

5.  Now I replace every occurrence of the implicit parent with code that uses a parent node instance, outfitted with the correct leaf node instance(s). Here’s an example:

public class OrdersWriter...
  private void writeProductsTo(StringBuffer xml, Order order) {
    for (int j=0; j < order.getProductCount(); j++) {
      Product product = order.getProduct(j);
       TagNode productTag = new TagNode("product");
       productTag.addAttribute("id", product.getID());
       productTag.addAttribute("color", colorFor(product));
      if (product.getSize() != ProductSize.NOT_APPLICABLE)
         productTag.addAttribute("size", sizeFor(product));
       writePriceTo(productTag, product);
       productTag.addValue(product.getName());
      xml.append( productTag.toString() );
    }
  }

   private void writePriceTo(TagNode productTag, Product product) {
    TagNode priceTag = new TagNode("price");
    priceTag.addAttribute("currency", currencyFor(product));
    priceTag.addValue(priceFor(product));
     productTag.add(priceTag);
  }

     I compile and run tests to ensure that the implicit tree still renders itself correctly.

6.  I repeat steps 4 and 5 for all remaining implicit parents. This yields the following code, which is identical to the after code in the code sketch on the first page of this refactoring, except that the code is broken up into smaller methods:

public class OrdersWriter...
  public String getContents() {
    StringBuffer xml = new StringBuffer();
    writeOrderTo(xml);
    return xml.toString();
  }

  private void writeOrderTo(StringBuffer xml) {
    TagNode ordersTag = new TagNode("orders");
    for (int i = 0; i < orders.getOrderCount(); i++) {
      Order order = orders.getOrder(i);
      TagNode orderTag = new TagNode("order");
      orderTag.addAttribute("id", order.getOrderId());
      writeProductsTo(orderTag, order);
      ordersTag.add(orderTag);
    }
    xml.append(ordersTag.toString());
  }

  private void writeProductsTo(TagNode orderTag, Order order) {
    for (int j=0; j < order.getProductCount(); j++) {
      Product product = order.getProduct(j);
      TagNode productTag = new TagNode("product");
      productTag.addAttribute("id", product.getID());
      productTag.addAttribute("color", colorFor(product));
      if (product.getSize() != ProductSize.NOT_APPLICABLE)
        productTag.addAttribute("size", sizeFor(product));
      writePriceTo(productTag, product);
      productTag.addValue(product.getName());
      orderTag.add(productTag);
    }
  }

  private void writePriceTo(TagNode productTag, Product product) {
    TagNode priceNode = new TagNode("price");
    priceNode.addAttribute("currency", currencyFor(product));
    priceNode.addValue(priceFor(product));
    productTag.add(priceNode);
  }

Replace Conditional Dispatcher with Command

Conditional logic is used to dispatch requests and execute actions.

Create a Command for each action. Store the Commands
in a collection and replace the conditional logic with
code to fetch and execute Commands.

Replace Conditional Dispatcher with Command

Motivation

Many systems receive, route, and handle requests. A conditional dispatcher is a conditional statement (such as a switch ) that performs request routing and handling. Some conditional dispatchers are well suited for their jobs; others aren’t.

Conditional dispatchers that are well suited for their jobs tend to route a small number of requests to small chunks of handler logic. Such dispatchers can often be viewed on a monitor without having to scroll to see all of the code. The Command pattern usually doesn’t provide a useful replacement for these kinds of conditional dispatchers.

On the other hand, if your conditional dispatcher is small, it may still not be a good fit for your system. The two most common reasons to refactor from a conditional dispatcher to a Command-based solution are the following.

1.   Not enough runtime flexibility : Clients that rely on the conditional dispatcher develop a need to dynamically configure it with new requests or handler logic. Yet the conditional dispatcher doesn’t allow for such dynamic configurations because all of its routing and handling logic is hard-coded into a single conditional statement.

2.   A bloated body of code : Some conditional dispatchers become enormous and unwieldy as they evolve to handle new requests or as their handler logic becomes ever more complex with new responsibilities. Extracting the handler logic into different methods doesn’t help enough because the class that contains the dispatcher and extracted handler methods is still too large to work with.

The Command pattern provides an excellent solution to such problems. To implement it, you simply place each piece of request-handling logic in a separate “command” class that has a common method, like execute() or run() , for executing its encapsulated handler logic. Once you have a family of such commands, you can use a collection to store and retrieve instances of them; add, remove, or change instances; and execute instances by invoking their execution methods.

Routing requests and executing diverse behavior in a uniform way may be so central to a design that you may find yourself using the Command pattern early, rather than refactoring to it later. Many of the server-side, Web-based systems I’ve built have used the Command pattern to produce a standard way to route requests, execute actions, or forward actions to other actions. The Example section shows how to refactor to such a solution.

The authors of Design Patterns [ DP ] explain how the Command pattern is often used to support an undo/redo capability. A question that often arises in extreme programming ( XP ) circles is what to do when you aren’t sure whether a system will need undo/redo. Do you just implement the Command pattern in case the need arises? Or is that a violation of “You aren’t gonna need it,” an XP principle that cautions against adding functionality to code based on speculation, not genuine need. If I’m not sure whether a system needs the Command pattern, I generally don’t implement it, for I find that it isn’t that hard to refactor to this pattern when the need arises. However, if your code is getting into a state in which it will be harder and harder to refactor to the Command pattern and there’s a good chance you’ll soon need an undo/redo capability, it may make sense to refactor it to use Command before doing so will be impossibly hard. It’s a bit like taking out an insurance plan.

The Command pattern is easy to implement, versatile, and incredibly useful. This refactoring captures only one area in which it is useful. Because Command can solve other tricky problems, there could easily be additional refactorings to it.

Benefits and Liabilities

+  Provides a simple mechanism for executing diverse behavior in a uniform way.

+  Enables runtime changes regarding which requests are handled and how.

+  Requires trivial code to implement.

–  Complicates a design when a conditional dispatcher is sufficient.

Mechanics

1.  On a class containing a conditional dispatcher, find code that handles a request and apply Extract Method [ F ] on that code until you have an execution method , a method that invokes the code’s behavior.

Image   Compile and test.

2.  Repeat step 1 to extract all remaining chunks of request-handling code into execution methods.

3.  Apply Extract Class [ F ] on each execution method to produce a concrete command , a class that handles a request. This step usually implies making the execution method on the concrete command public. If the execution method in the new concrete command is too large or not quickly understandable, apply Compose Method (123) .

Image   Compile and test.

     After you’ve finished creating all of your concrete commands, look for duplicated code in them. If you find some, see if you can remove it by applying Form Template Method (205) .

4.  Define a command , an interface or abstract class that declares an execution method that is the same for every concrete command. To implement this step, you’ll need to analyze your concrete commands to learn what’s unique or similar about them. Find answers to the following questions.

•  What parameter(s) must be passed to a common execution method?

•  What parameter(s) could be passed during a concrete command’s construction?

•  What information could a concrete command obtain by calling back on a parameter, rather than having data passed direcly to the concrete command?

•  What is the simplest signature for an execution method that is the same for every concrete command?

     Consider producing an early version of your command by applying Extract Superclass [ F ] or Extract Interface [ F ] on a concrete command.

Image   Compile.

5.  Make every concrete command implement or extend your command and update all client code to work with each concrete command via the command type.

Image   Compile and test.

6.  On the class that contains the conditional dispatcher, define and populate a command map , a map that contains instances of each concrete command, keyed by a unique identifier (e.g., a command name) that may be used at runtime to fetch a command.

     If you have many concrete commands, you’ll have a lot of code that adds concrete command instances to your command map. In that case, consider making your concrete commands implement the Plugin pattern, from Patterns of Enterprise Application Architecture [ Fowler, PEAA ]. This will make it possible for them to be loaded simply by supplying the appropriate configuration data (such as a list of the names of the command classes or, even better, a directory where the classes live).

Image   Compile.

7.  On the class that contains the conditional dispatcher, replace the conditional code for dispatching requests with code to fetch the correct concrete command and execute it by calling its execution method. This class is now an Invoker [ DP , 236].

Image   Compile and test.

Example

The example code we’ll look at comes from a system I cowrote to create and organize Industrial Logic’s HTML-based catalogs. Ironically, this system made heavy use of the Command pattern from its earliest evolutions. I decided to rewrite the sections of the system that used the Command pattern to not use the Command pattern in order to produce the kind of bloated, Command-thirsty code that I so frequently encounter in the field.

In the altered code, a class named CatalogApp is responsible for dispatching and executing actions and returning responses. It performs this work within one large conditional statement:

public class CatalogApp...
  private HandlerResponse executeActionAndGetResponse(String actionName, Map parameters)...
    if (actionName.equals(NEW_WORKSHOP)) {
      String nextWorkshopID = workshopManager.getNextWorkshopID();
      StringBuffer newWorkshopContents =
        workshopManager.createNewFileFromTemplate(
          nextWorkshopID,
          workshopManager.getWorkshopDir(),
          workshopManager.getWorkshopTemplate()
        );
      workshopManager.addWorkshop(newWorkshopContents);
      parameters.put("id",nextWorkshopID);
      executeActionAndGetResponse(ALL_WORKSHOPS, parameters);
    } else if (actionName.equals(ALL_WORKSHOPS)) {
      XMLBuilder allWorkshopsXml = new XMLBuilder("workshops");
      WorkshopRepository repository =
        workshopManager.getWorkshopRepository();
      Iterator ids = repository.keyIterator();
      while (ids.hasNext()) {
        String id = (String)ids.next();
        Workshop workshop = repository.getWorkshop(id);
        allWorkshopsXml.addBelowParent("workshop");
        allWorkshopsXml.addAttribute("id", workshop.getID());

        allWorkshopsXml.addAttribute("name", workshop.getName());
        allWorkshopsXml.addAttribute("status", workshop.getStatus());
        allWorkshopsXml.addAttribute("duration",
          workshop.getDurationAsString());
      }
      String formattedXml = getFormattedData(allWorkshopsXml.toString());
      return new HandlerResponse(
        new StringBuffer(formattedXml),
        ALL_WORKSHOPS_STYLESHEET
      );
    } ...many more "else if" statements

The complete conditional spans several pages—I’ll spare you the details. The first leg of the conditional handles the creation of a new workshop. The second leg, which happens to be called by the first leg, returns XML that contains summary information for all of Industrial Logic’s workshops. I’ll show how to refactor this code to use the Command pattern.

1.  I start by working on the first leg of the conditional. I apply Extract Method [ F ] to produce the execution method getNewWorkshopResponse() :

public class CatalogApp...
  private HandlerResponse executeActionAndGetResponse(String actionName, Map parameters)...
    if (actionName.equals(NEW_WORKSHOP)) {
       getNewWorkshopResponse(parameters);
    } else if (actionName.equals(ALL_WORKSHOPS)) {
      ...
    } ...many more "else if" statements

   private HandlerResponse getNewWorkshopResponse(Map parameters) throws Exception {
     String nextWorkshopID = workshopManager.getNextWorkshopID();
     StringBuffer newWorkshopContents =
       workshopManager.createNewFileFromTemplate(
         nextWorkshopID,
         workshopManager.getWorkshopDir(),
         workshopManager.getWorkshopTemplate()
       );
     workshopManager.addWorkshop(newWorkshopContents);
     parameters.put("id",nextWorkshopID);
     return executeActionAndGetResponse(ALL_WORKSHOPS, parameters);
   }

     The compiler and test code are happy with the newly extracted method.

2.  I now go on to extract the next chunk of request-handling code, which deals with listing all workshops in the catalog:

public class CatalogApp...
  private HandlerResponse executeActionAndGetResponse(String actionName, Map parameters)...
    if (actionName.equals(NEW_WORKSHOP)) {
      getNewWorkshopResponse(parameters);

    } else if (actionName.equals(ALL_WORKSHOPS)) {
       getAllWorkshopsResponse();
    } ...many more "else if" statements

   public HandlerResponse getAllWorkshopsResponse() {
     XMLBuilder allWorkshopsXml = new XMLBuilder("workshops");
     WorkshopRepository repository =
       workshopManager.getWorkshopRepository();
     Iterator ids = repository.keyIterator();
     while (ids.hasNext()) {
       String id = (String)ids.next();
       Workshop workshop = repository.getWorkshop(id);
       allWorkshopsXml.addBelowParent("workshop");
       allWorkshopsXml.addAttribute("id", workshop.getID());
       allWorkshopsXml.addAttribute("name", workshop.getName());
       allWorkshopsXml.addAttribute("status", workshop.getStatus());
       allWorkshopsXml.addAttribute("duraction",
         workshop.getDurationAsString());
     }
     String formattedXml = getFormattedData(allWorkshopsXml.toString());
     return new HandlerResponse(
       new StringBuffer(formattedXml),
       ALL_WORKSHOPS_STYLESHEET
     );
   }

     I compile, test, and repeat this step for all remaining chunks of request-handling code.

3.  Now I begin creating concrete commands. I first produce the NewWorkshopHandler concrete command by applying Extract Class [ F ] on the execution method getNewWorkshopResponse() :

public class NewWorkshopHandler {
   private CatalogApp catalogApp;

   public NewWorkshopHandler(CatalogApp catalogApp) {
     this.catalogApp = catalogApp;
   }

   public HandlerResponse getNewWorkshopResponse(Map parameters) throws Exception {
     String nextWorkshopID = workshopManager().getNextWorkshopID();
     StringBuffer newWorkshopContents =
       WorkshopManager().createNewFileFromTemplate(
         nextWorkshopID,
         workshopManager().getWorkshopDir(),
         workshopManager().getWorkshopTemplate()
       );
     workshopManager().addWorkshop(newWorkshopContents);
     parameters.put("id", nextWorkshopID);
     catalogApp.executeActionAndGetResponse(ALL_WORKSHOPS, parameters);
   }

   private WorkshopManager workshopManager() {
     return catalogApp.getWorkshopManager();
   }
}

      CatalogApp instantiates and calls an instance of NewWorkshopHandler like so:

public class CatalogApp...
   public  HandlerResponse executeActionAndGetResponse(
    String actionName, Map parameters) throws Exception {
    if (actionName.equals(NEW_WORKSHOP)) {
       return new NewWorkshopHandler(this).getNewWorkshopResponse(parameters);
    } else if (actionName.equals(ALL_WORKSHOPS)) {
      ...
    } ...

     The compiler and tests confirm that these changes work fine. Note that I made executeActionAndGetResponse(…) public because it’s called from NewWorkshopHandler .

     Before I go on, I apply Compose Method (123) on NewWorkshopHandler ’s execution method:

public class NewWorkshopHandler...
   public HandlerResponse getNewWorkshopResponse(Map parameters) throws Exception {
     createNewWorkshop(parameters);
     return catalogApp.executeActionAndGetResponse(
       CatalogApp.ALL_WORKSHOPS, parameters);
   }

   private void createNewWorkshop(Map parameters) throws Exception {
     String nextWorkshopID = workshopManager().getNextWorkshopID();
     workshopManager().addWorkshop(newWorkshopContents(nextWorkshopID));
     parameters.put("id",nextWorkshopID);
   }

   private StringBuffer newWorkshopContents(String nextWorkshopID) throws Exception {
     StringBuffer newWorkshopContents = workshopManager().createNewFileFromTemplate(
       nextWorkshopID,
       workshopManager().getWorkshopDir(),
       workshopManager().getWorkshopTemplate()
     );
     return newWorkshopContents;
   }

     I repeat this step for additional execution methods that ought to be extracted into their own concrete commands and turned into Composed Methods. AllWorkshopsHandler is the next concrete command I extract. Here’s how it looks:

public class AllWorkshopsHandler...
   private CatalogApp catalogApp;

   private static String ALL_WORKSHOPS_STYLESHEET="allWorkshops.xsl";
   private PrettyPrinter prettyPrinter = new PrettyPrinter();

   public AllWorkshopsHandler(CatalogApp catalogApp) {
     this.catalogApp = catalogApp;
   }

   public HandlerResponse getAllWorkshopsResponse() throws Exception {
     return new HandlerResponse(
       new StringBuffer(prettyPrint(allWorkshopsData())),
       ALL_WORKSHOPS_STYLESHEET
     );
   }

   private String allWorkshopsData() ...

   private String prettyPrint(String buffer) {
     return prettyPrinter.format(buffer);
   }

     After performing this step for every concrete command, I look for duplicated code across all of the concrete commands. I don’t find much duplication, so there is no need to apply Form Template Method (205) .

4.  I must now create a command (as defined in the Mechanics section, an interface or abstract class that declares an execution method that every concrete command must implement). At the moment, every concrete command has an execution method with a different name, and the execution methods take a different number of arguments (namely, one or none):

   if (actionName.equals(NEW_WORKSHOP)) {
     return new NewWorkshopHandler(this). getNewWorkshopResponse(parameters);
   } else if (actionName.equals(ALL_WORKSHOPS)) {
     return new AllWorkshopsHandler(this). getAllWorkshopsResponse();
   } ...

     Making a command will involve deciding on:

•  A common execution method name

•  What information to pass to and obtain from each handler

     The common execution method name I choose is execute (a name that’s often used when implementing the Command pattern, but by no means the only name to use). Now I must decide what information needs to be passed to and/or obtained from a call to execute() . I survey the concrete commands I’ve created and learn that a good many of them:

•  Require information contained in a Map called parameters

•  Return an object of type HandlerResponse

•  Throw an Exception

     This means that my command must include an execution method with the following signature:

public HandlerResponse execute(Map parameters) throws Exception

     I create the command by performing two refactorings on NewWorkshopHandler . First, I rename its getNewWorkshopResponse(…) method to execute(…) :

public class NewWorkshopHandler...
   public HandlerResponse  execute (Map parameters) throws Exception

     Next, I apply the refactoring Extract Superclass [ F ] to produce an abstract class called Handler :

public abstract class Handler {
   protected CatalogApp catalogApp;

   public Handler(CatalogApp catalogApp) {
     this.catalogApp = catalogApp;
   }

   public abstract HandlerResponse execute(Map parameters) throws Exception;
}

public class NewWorkshopHandler  extends Handler ...
  public NewWorkshopHandler(CatalogApp catalogApp) {
     super(catalogApp);
  }

     The compiler is happy with the new class, so I move on.

5.  Now that I have the command (expressed as the abstract Handler class), I’ll make every handler implement it. I do this by making them all extend Handler and implement the execute() method. When I’m done, the handlers may now be invoked identically:

   if (actionName.equals(NEW_WORKSHOP)) {
     return new NewWorkshopHandler(this). execute(parameters);
   } else if (actionName.equals(ALL_WORKSHOPS)) {
     return new AllWorkshopsHandler(this). execute(parameters);
   } ...

     I compile and run the tests to find that everything is working.

6.  Now comes the fun part. CatalogApp ’s conditional statement is merely acting like a crude Map . It would be better to turn it into a real map by storing an instance of my command in a command map. To do that, I define and populate handlers , a Map keyed by handler name:

public class CatalogApp...
   private Map handlers;
  public CatalogApp(...) {
    ...
     createHandlers();
    ...
  }

   public void createHandlers() {
     handlers = new HashMap();
     handlers.put(NEW_WORKSHOP, new NewWorkshopHandler(this));
     handlers.put(ALL_WORKSHOPS, new AllWorkshopsHandler(this));
     ...
   }

     Because I don’t have too many handlers, I don’t resort to implementing a Plugin, as described in the Mechanics section. The compiler is happy with the new code.

7.  Finally, I replace CatalogApp ’s large conditional statement with code that looks up a handler by name and executes it:

public class CatalogApp...
  public HandlerResponse executeActionAndGetResponse(
    String handlerName, Map parameters) throws Exception {
     Handler handler = lookupHandlerBy(handlerName);
     return handler.execute(parameters);
  }

   private Handler lookupHandlerBy(String handlerName) {
     return (Handler)handlers.get(handlerName);
   }

     The compiler and test code are happy with this Command-based solution. CatalogApp now uses the Command pattern to execute an action and get back a response. This design makes it easy to declare a new handler, name it, and register it in the command map so that it may be invoked at runtime to perform an action.