Home > Articles > Software Development & Management > Agile

What Is Refactoring?

Going to Work

When you considered the sample code, what smells did you find? Here is what I saw:

  • Long class

  • Long method

  • Variables could be local to method

  • Useless method comment

  • Could we read template once, instead of each time?

  • The code is tied to using the file system

  • Questionable use of "!=" for string compare

  • Use of StringBuffer without append

  • Reallocating StringBuffer in loop

  • The close() methods are not in catch or finally clause

  • Inconsistent/unclear exception handling

  • Lots of string addition

  • Almost-duplicate code in handling "%CODE%" and "%ALTCODE%"

  • Lots of extraneous new String()s

  • Magic numbers (6 and 9) and symbols

  • Lots of temporary variables

The worst smell is that long substitute() method, so use Extract Method to break it up. Many of the refactorings we use are available online in the catalog at http://www.refactoring.com.

First, pull out readTemplate() as a new method:

String readTemplate() {
  String templateDir = System.getProperty(TEMPLATE_DIR, "");
  StringBuffer sb = new StringBuffer("");
  try {
    FileReader fr=new FileReader(templateDir+"template.html");
    BufferedReader br = new BufferedReader(fr);
    String line;
    while(((line=br.readLine())!="")&&line!=null) 
      sb = new StringBuffer(sb + line + "\n");
    br.close();
    fr.close();
  } catch (Exception e) {
  }
  sourceTemplate = new String(sb);
  return sourceTemplate;
}

Even though the change is so simple it could not possibly fail, run the test! (And of course, the first time I ran the test, it failed because I forgot to call my new function, highlighting the importance of the mechanics.)

Notice also that we're not immediately chopping the routine into three or four pieces all at once; we're working one step at a time. We'll develop a steady rhythm: change some code, run the test, change some code, run the test. We never go far without verifying what we've done. If we make a mistake, it must be in the last thing we did.

Let's get the template name in one place (via Introduce Explaining Variable), replacing templateDir with

    String templateName = System.getProperty(TEMPLATE_DIR,"")
        + "template.html";

(Run the test.) Then eliminate the fr variable (Inline Temp):

    BufferedReader br = null;
        ...
    br = new BufferedReader(newFileReader(templateName));

(and drop fr.close().) (Run the test.)

Now we're in a position to fix one of the bugs we noticed: the stream is not properly closed in case of errors.

  try {
    ...
  } catch (Exception ex) {
  } finally {
    if (br != null) try {br.close();} 
        catch (IOException ioe_ignored) {}
  }

(Run the test.)

Next look at another potential problem, the != string test. We verify (by looking around and asking around) that the template reader was not intended to stop at blank lines or anything like that, so this condition is meaningless.

    String line = br.readLine();
    while (line != null) {
        sb = new StringBuffer(sb + line + "\n");
        line = br.readLine();
    }

(Run the test.) Martin Fowler (1999) points out that it is safer to keep bug-fixing and refactoring separate. He would create a new test case to demonstrate the bug, complete refactoring, and only then go back to fix it. In this small example, we'll just proceed with the fixed code.

Consider the assignment to sb. It is redundant: there's no reason to create a new StringBuffer each time, when we can just add to the one we already have. Also, we can use append() to eliminate the string addition (Replace String with StringBuffer).

    sb.append(line);
    sb.append('\n');

(Run the test.)

Instead of sourceTemplate = new String(sb); let's push the work of creating the string onto the StringBuffer: sourceTemplate = sb.toString();. (Run the test.)

The routine both assigns to "sourceTemplate" and returns it. Let's move the responsibility for the assignment to the caller and just return sb.toString() instead. Declare the return type as String. (Reapportion Work between Caller and Callee.) (Run the test.)

For exceptions, let's declare the routine as throwing IOException and delete the empty catch clause; the caller will have to deal with any exceptions. This causes a change (untested! hmm...) in behavior because no partial template will be returned in case of error. We'll confirm by looking and asking whether this is OK. (Run the test.)

Our routine now appears as follows:

String readTemplate() throws IOException {
    String templateName = System.getProperty(TEMPLATE_DIR, "")
                           + "template.html";
    StringBuffer sb = new StringBuffer("");
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader(templateName));
        String line = br.readLine();
        while (line != null) {
            sb.append(line);
            sb.append('\n');
            line = br.readLine();
        }
    } finally {
        if (br != null) try {br.close();} 
                        catch (IOException ioe_ignored) {}
    }
    return sb.toString();
}

The next thing I don't like is that the routine decides both where to find the template and how to read it, leaving it coupled to the file system. This may be a problem in the future (if templates were to come from somewhere else), but it's also a problem now: our test has to use an external file. I'm not sure of the right approach, so we'll defer this problem.

Substitute for "%CODE%"

The routine is still too long. We also still have the near-duplicate code for substitutions.

So next we'll Extract Method for replacing "%CODE%".

String substituteForCode(String template, String reqId) {
  int templateSplitBegin = template.indexOf("%CODE%");
  int templateSplitEnd = templateSplitBegin + 6;
  String templatePartOne = new String(
    template.substring(0, templateSplitBegin));
  String templatePartTwo = new String(
     template.substring(templateSplitEnd, template.length()));
  code = new String(reqId);
  template = new String(templatePartOne+code+templatePartTwo);
  return template;
}

Then we'll adjust the variable declarations left in substitute(). (Run the test.)

The first thing I notice is the string "%CODE%" and the value 6 (the length of the pattern). Pull out the pattern and use it (Replace Magic Number with Calculation).

  String pattern = "%CODE%";
  int templateSplitBegin = template.indexOf(pattern);
  int templateSplitEnd = templateSplitBegin+pattern.length();

(Run the test.)

We create a lot of new Strings too: all those new String() constructions are redundant, because their arguments are Strings already (Remove Redundant Constructor Calls).

String templatePartOne =
      template.substring(0,templateSplitBegin);
  String templatePartTwo =
      template.substring(templateSplitEnd, template.length());
  code = reqId;
  return templatePartOne + code + templatePartTwo;

(Run the test.)

We'll eventually want to address the remaining string addition (on the return statement), but let's take care of "%ALTCODE%" first.

Substitute for "%ALTCODE%"

Let's do the same Extract Method and simplification for the other case, and see where we are.

void substituteForAltcode(String template, String code,
                           PrintWriter out) {
  String pattern = "%ALTCODE%";
  int templateSplitBegin = template.indexOf(pattern);
  int templateSplitEnd = templateSplitBegin+pattern.length();

  String templatePartOne = template.substring(
                0, templateSplitBegin);
  String templatePartTwo = template.substring(
               templateSplitEnd, template.length());
  altcode = code.substring(0,5) + "-" + code.substring(5,8);
  out.print(templatePartOne + altcode + templatePartTwo);
  }

This code is so similar to substituteForCode(), it's clear we should be able to unify the two routines. But there are three diff-erences: they look for different patterns, they substitute different values, and they write to different streams. Drive them toward duplication by passing in the patterns and replacements as arguments (Parameterize Method).

void substituteForAltCode(String template, String pattern,
  String replacement, PrintWriter out) {
  int templateSplitBegin = template.indexOf(pattern);

  int templateSplitEnd = templateSplitBegin+pattern.length();

  String templatePartOne = template.substring(
        0, templateSplitBegin);

  String templatePartTwo = template.substring(
        templateSplitEnd, template.length());
  out.print(templatePartOne + replacement + templatePartTwo);
}
        ...
  altcode = reqId.substring(0,5) + "-" + reqId.substring(5,8);
    substituteForAltCode(template, "%ALTCODE%", altcode, out);

(Run the test.)

We can address the excessive string addition by using a series of print() calls (Replace String Addition with Output), and we'll pull the buffer flush up as well.

    out.print(templatePartOne);
    out.print(replacement);
    out.print(templatePartTwo);
    out.flush();

(Run the test.)

The big difference now is that "%CODE%" results in a String, and "%ALTCODE%" is written to a PrintWriter. These can be reconciled via the class java.io.StringWriter. So make substituteForCode() take an argument PrintWriter out, and create and pass in a new PrintWriter(new StringWriter()) as its stream (Unify String and I/O). (Run the test.)

How did I know to look for a class such as StringWriter? First, I could have talked to a co-worker and found it; there's usually someone who knows the odd corners you don't. (In XP, you start with your pair partner; if your partner doesn't know, the rest of the team is in the same room.) Second, I've used enough systems to know that many have a way to let you treat strings as I/O, and vice versa. Third, I could have learned it when I read once through the core APIs when learning the language. Finally, it is documented and can be found when needed.

We see that the two routines are now identical: eliminate _substituteForAltcode(), and just call substituteForCode() twice (Merge Identical Routines). (Run the test.)

Back to readTemplate()

We were able to verify (by asking our customer) that it would be acceptable to read the template once at startup, rather than once per call to substitute(). We can declare the constructor to throw IOException, and make the call to readTemplate() there.

sourceTemplate = readTemplate(
        System.getProperty(TEMPLATE_DIR, ""));

(Run the test.)

This helps eliminate some strings we would otherwise create.

At last, we can address that old thorn: direct reading of a file to load the template. The readTemplate() routine currently takes a directory name and constructs a file. Instead, we'll pass in a Reader and let that do the work. First pull up construction of the FileReader into the constructor (Reapportion Work between Caller and Callee).

public CodeReplacer() throws IOException {
    String templateName = 
System.getProperty(TEMPLATE_DIR, "") + "template.html";
    sourceTemplate = readTemplate(
                         new FileReader(templateName));
}

public String readTemplate(Reader reader) 
                     throws IOException {
    ...
}

(Run the test.)

Next introduce a constructor that takes a Reader, which the caller is responsible for forming. (They will probably use the getProperty() code that was there before.)

public CodeReplacer(Reader reader) throws IOException {
  sourceTemplate = readTemplate(reader);
}

(Run the test.)

I'll put a testing hat back on and modify my test. We can simplify testTemplateLoadedProperly(), because we no longer need to do a substitution to see the template just to load it. Also, instead of setting up with the file template.html, we'll test using a StringReader. This helps decouple our tests from the environment.

final static String templateContents =
                      "xxx%CODE%yyy%ALTCODE%zzz\n";
        ...
  replacer = new CodeReplacer(new StringReader(
                               templateContents));
        ...
public void testTemplateLoadedProperly() {
  assertEquals(templateContents, replacer.sourceTemplate);
}

(Run the test.)

Finally, the close() call in substitute() is a little out of place. Because the caller of the object opens the stream, we'd like the caller to be responsible for closing the stream as well. We'll modify _substitute() and its callers (Reapportion Work between Caller and Callee).

(Run the test one last time.)

Final Result

Here's the complete new version of CodeReplacer.java:

import java.io.*;
import java.util.*;
/** Replace %CODE% with requested id, and 
%ALTCODE% w/"dashed" version of id.*/

public class CodeReplacer {
    String sourceTemplate;

    public CodeReplacer(Reader reader) throws IOException {
        sourceTemplate = readTemplate(reader);
    }

    String readTemplate(Reader reader) throws IOException {
        BufferedReader br = new BufferedReader(reader);
        StringBuffer sb = new StringBuffer();
        try {
            String line = br.readLine();
            while (line!=null) {
                sb.append(line);
                sb.append("\n");
                line = br.readLine();
            }
        } finally {
            try {if (br != null) br.close();} 
           catch (IOException ioe_ignored) {}
        }
        return sb.toString();
    }

    void substituteCode (String template, String pattern,
                         String replacement, Writer out)
                           throws IOException {
        int templateSplitBegin = template.indexOf(pattern);
        int templateSplitEnd = 
             templateSplitBegin + pattern.length();
        out.write(template.substring(0, templateSplitBegin));
        out.write(replacement);
        out.write(template.substring(
                   templateSplitEnd, template.length()));
        out.flush();
    }

    public void substitute(String reqId, PrintWriter out)
                    throws IOException {
        StringWriter templateOut = new StringWriter();
        substituteCode(sourceTemplate, "%CODE%", 
                       reqId, templateOut);

        String altId = reqId.substring(0,5) + "-" + 
                          reqId.substring(5,8);
        substituteCode(templateOut.toString(), "%ALTCODE%",
                       altId, out);
    }
}

Here's CodeReplacerTest.java:

import java.io.*;
import junit.framework.*;

public class CodeReplacerTest extends TestCase {
    final static String templateContents = 
                    "xxx%CODE%yyy%ALTCODE%zzz\n";

    CodeReplacer replacer;

    public CodeReplacerTest(String testName)
    {super(testName);}

    protected void setUp() {
        try {
            replacer = new CodeReplacer(new StringReader(
                                         templateContents));
        } catch (Exception ex) {
            fail("CodeReplacer couldn't load");
        }
    }

    public void testTemplateLoadedProperly() {
        assertEquals(templateContents,
                     replacer.sourceTemplate);
    }

    public void testSubstitution() {
        StringWriter stringOut = new StringWriter();
        PrintWriter testOut = new PrintWriter (stringOut);
        String trackingId = "01234567";
        
        try {
            replacer.substitute(trackingId, testOut);
            testOut.close();
        } catch (IOException ex) {
            fail ("testSubstitution exception - " + ex);
        }

        assertEquals("xxx01234567yyy01234-567zzz\n",
                     stringOut.toString());
    }

}

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020