Home > Articles > Software Development & Management

This chapter is from the book

This chapter is from the book

Replace State-Altering Conditionals with State

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.

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.

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.
  2. The context class is known as State: Context and the state superclass as State: State in Design Patterns [DP].

    → Compile.

  3. 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.
  4. → Compile.

  5. 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.
  6. → 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.

  7. 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.
  8. Unrelated logic usually includes verifications of a current state or logic that transitions to unrelated states.

    → Compile and test.

    Repeat for all states the context class can enter.

  9. Delete the bodies of each of the methods copied to the state superclass during step 3 to produce an empty implementation for each method.
  10. → 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:

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:

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:
  2. 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) {
        ...
        setPermission(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...
  3. 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.
  4. 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.

  5. 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:
  6. public class SystemPermission...
      private void setState(PermissionState state) { // now has package-level visibility
        permissionState = state;
      }
       
      public void claimedBy(SystemAdmin admin) {
        state.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().

  7. 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:
  8. 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);
        elseif (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.

  9. In PermissionState, I can now delete the bodies of claimedBy(), deniedBy(), and grantedBy(), leaving the following:
  10. 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.

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