The refactorings in this section are low-level transformations used by the higher-level refactorings in the catalog. These refactorings fit well with the refactorings in Refactoring [ F ].

Chain Constructors (340) is about removing duplication in constructors by having them call each other. This refactoring is used by the refactoring Replace Constructors with Creation Methods (57) .

Unify Interfaces (343) is useful when you need a superclass and/or interface to share the same interface as a subclass. The usual motivation for applying this refactoring is to make it possible to treat objects polymorphically. The refactorings Move Embellishment to Decorator (144) and Move Accumulation to Visitor (320) both make use of this refactoring.

Extract Parameter (346) is useful when a field is assigned to a locally instantiated value and you’d rather have that value supplied by a parameter. While this can be useful in many situations, the refactoring Move Embellishment to Decorator (144) uses this refactoring just after the application of Replace Inheritance with Delegation [ F ].

Chain Constructors

You have multiple constructors that contain duplicate code.

Chain the constructors together to obtain the least
amount of duplicate code.

Chain Constructors

Motivation

Code that’s duplicated across two or more of a class’s constructors is an invitation for trouble. If someone adds a new variable to a class and updates a constructor to initialize the variable, but then neglects to update the other constructors— bang , say hello to your next defect. The more constructors you have in a class, the more duplication will hurt you. It is therefore a good idea to reduce or remove duplication in your constructors.

We often accomplish this refactoring with constructor chaining: specific constructors call more general-purpose constructors until a final constructor is reached. If you have one constructor at the end of every chain, it is a catch-all constructor because it handles every constructor call. A catch-all constructor often accepts more parameters than other constructors.

If you find that having many constructors on your class detracts from its usability, consider applying Replace Constructors with Creation Methods (57) .

Mechanics

1.  Find two constructors that contain duplicate code. Determine whether one can call the other such that duplicate code can be safely (and, hopefully, easily) deleted from one of these constructors. Then make the one constructor call the other constructor such that duplicate code is reduced or eliminated.

Image   Compile and test.

2.  Repeat step 1 for all constructors in the class, including ones you’ve already touched, in order to obtain as little duplication across all constructors as possible.

3.  Change the visibility of any constructors that may not need to be public.

Image   Compile and test.

Example

For this example I’ll use the scenario shown in the code sketch at the beginning of this refactoring. A single Loan class has three constructors to represent different types of loans, as well as tons of bloated and ugly duplication:

public Loan(float notional, float outstanding, int rating, Date expiry) {
   this.strategy = new TermROC();
   this.notional = notional;
   this.outstanding = outstanding;

this.rating = rating;
   this.expiry = expiry;
}

public Loan(float notional, float outstanding, int rating, Date expiry, Date maturity) {
   this.strategy = new RevolvingTermROC();
   this.notional = notional;
   this.outstanding = outstanding;
   this.rating = rating;
   this.expiry = expiry;
   this.maturity = maturity;
}

public Loan(CapitalStrategy strategy, float notional, float outstanding, int rating,
         Date expiry, Date maturity) {
   this.strategy = strategy;
   this.notional = notional;
   this.outstanding = outstanding;
   this.rating = rating;
   this.expiry = expiry;
   this.maturity = maturity;
}

Let’s see what happens when I refactor this code.

1.  I study the first two constructors. They do contain duplicate code, but so does that third constructor. I consider which constructor it would be easier for the first constructor to call. I see that it could call the third constructor with a minimum amount of work. So I change the first constructor to be:

public Loan(float notional, float outstanding, int rating, Date expiry) {
    this(new TermROC(), notional, outstanding, rating, expiry, null);
}

Image   I compile and test to see that the change works.

2.  I repeat step 1 to remove as much duplication as possible. This leads me to the second constructor. It appears that it too can call the third constructor, as follows:

public Loan(float notional, float outstanding, int rating, Date expiry, Date maturity) {
    this(new RevolvingTermROC(), notional, outstanding, rating, expiry, maturity);
}

     I’m now aware that the third constructor is my class’s catch-all constructor because it handles all of the construction details.

3.  I check all callers of the three constructors to determine whether I can change the public visibility of any of them. In this case, I can’t. (Take my word for it—you can’t see the code that calls these methods.)

Image   I compile and test to complete the refactoring.

Unify Interfaces

You need a superclass and/or interface to have
the same interface as a subclass.

Find all public methods on the subclass that are missing on the
superclass/interface. Add copies of these missing methods to
the superclass, altering each one to perform null behavior.

Unify Interfaces

Motivation

To process objects polymorphically, the classes of the objects need to share a common interface, whether a superclass or an actual interface. This refactoring addresses the case when a superclass or interface needs to have the same interface as a subclass.

I came across the need for this refactoring on two separate occasions. Once when I was applying Move Embellishment to Decorator (144) , an emerging Decorator [ DP ] needed the same interface as a subclass. The easiest way to make that happen was to apply Unify Interfaces . Similarly, during an application of the refactoring Move Accumulation to Visitor (320) , duplicate code could be removed if certain objects shared the same interface, which Unify Interfaces made possible.

After applying this refactoring on a superclass and subclass, I sometimes apply Extract Interface [ F ] on the superclass to produce a stand-alone interface. I usually do this when an abstract base class contains state fields and I don’t want implementors of the common base class, such as a Decorator, to inherit those fields. See Move Embellishment to Decorator (144) for an example.

Unify Interfaces is often a temporary step on the way to somewhere else. For example, after you perform this refactoring, you may perform a sequence of refactorings that allows you to remove methods you added while unifying your interfaces. Other times, a default implementation of a method on an abstract base class may no longer be needed after applying Extract Interface [ F ].

Mechanics

Find a missing method , a public method on the subclass that isn’t declared on the superclass and/or interface.

1.  Add a copy of the missing method to the superclass/interface. If you’re adding the missing method to a superclass, modify its body to perform null behavior.

Image   Compile.

     Repeat until the superclass/interface and subclass share the same interface.

Image   Test that all code related to the superclass works as expected.

Example

I need to unify the interfaces of a subclass called StringNode and its superclass, AbstractNode . StringNode inherits most of its public methods from AbstractNode , with the exception of one method:

public class StringNode extends AbstractNode...
    public void accept(textExtractor: TextExtractor) {
       // implementation details…
    }
}

1.  I add a copy of the accept(…) method to AbstractNode , modifying its body to provide null behavior:

public abstract class AbstractNode...
    public void accept(textExtractor: TextExtractor) {
    }

     At this point, the interfaces of AbstractNode and StringNode have been unified. I compile and test to ensure that everything works fine. It does.

Extract Parameter

A method or constructor assigns a field
to a locally instantiated value.

Assign the field to a parameter supplied by a client by
extracting one-half of the assignment statement to a parameter.

Extract Parameter

Motivation

Sometimes you want to assign a field inside an object to a value provided by another object. If the field is already assigned to a local value, you can extract one-half of the assignment statement to a parameter so that a client can supply the field’s value rather than the host object.

I needed this refactoring after performing Replace Inheritance with Delegation [ F ]. At the end of that refactoring, a delegating class contains a field for an object it delegates to (the delegatee). The delegating class assigns this delegate field to a new instance of the delegate. Yet I needed a client object to supply the delegate’s value. Extract Parameter allowed me to simply extract the delegate instantiation code to a parameter value supplied by a client.

Mechanics

1.  The assignment statement for the field must be in a constructor or method before you can do this refactoring. If it isn’t already in a constructor or method, move it to one.

2.  Apply Add Parameter [ F ] to pass in the value for the field, using the field’s type as the type for the parameter. Make the parameter’s value be the value the field is assigned to within its host object. Alter the assignment statement so the field is assigned to the new parameter.

Image   Compile and test.

     When you have finished this refactoring, you may wish to remove unused parameters by applying Remove Parameter [ F ].

Example

This example comes from a step I perform during the refactoring Move Embellishment to Decorator (144) . The HTML Parser’s DecodingNode class contains a field called delegate that is assigned to a new instance of StringNode inside DecodingNode ’s constructor:

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

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

Given this code, I apply this refactoring as follows.

1.  Since delegate is already assigned to a value within DecodingNode ’s contructor, I can move to the next step.

2.  I apply Add Parameter [ F ] and use a default value of new StringNode(textBuffer, textBegin, textEnd) . I then alter the assignment statement so that it assigns delegate to the parameter value, newDelegate :

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

   public DecodingNode(StringBuffer textBuffer, int textBegin, int textEnd,
                        Node newDelegate ) {
      delegate =  newDelegate;
   }

     This change involves updating the client, StringNode , to pass in the value for newDelegate :

public class StringNode...
   ...
   return new DecodingNode(...,
      new StringNode(textBuffer, textBegin, textEnd)
   );

     I compile and test to confirm that everything still works just fine.

     After completing this refactoring, I will apply Remove Parameter [ F ] several times, so that the constructor for DecodingNode becomes:

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

   public DecodingNode( StringBuffer textBuffer, int textBegin, int textEnd,
                        Node newDelegate ) {
      delegate =  newDelegate;
   }

     And that’s it for this short and sweet refactoring.