Home > Articles > Software Development & Management

Refactoring to Patterns: Simplification

You can often simplify code by considering a completely different solution. Joshua Kerievsky presents refactorings that offer different solutions for simplifying methods, state transitions, and tree structures.
This chapter is from the book

This chapter is from the book

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.

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.

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.

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