A refactoring that improves the protection of existing code must do so in a way that doesn’t alter the behavior of the existing code. All three refactorings in this section do just that. Your motivation for applying them may be to improve protection or it may be a standard refactoring motivation, such as to reduce duplication or to simplify or clarify code.

Replace Type Code with Class (286) helps protect a field from assignments to incorrect or unsafe values. This is particularly important when a field controls what behavior gets executed at runtime because an incorrect assignment could put an object into an invalid state. Replace Type Code with Class (286) uses a class rather than an enum to constrain what values may be assigned to a field. Does an enum provide a better way to implement this refactoring or even render this refactoring out of date? It does not. The main difference between a class and an enum is that you can add behavior to a class. This is important because the class produced during Replace Type Code with Class (286) may need to be extended with behavior as you apply a sequence of refactorings. This is exactly what occurs during the refactoring Replace State-Altering Conditionals with State (166) .

Limit Instantiation with Singleton (296) is useful when you want to control how many instances of a class can be instantiated. Typical motivations for applying this refactoring are to reduce memory usage or improve performance. A poor motivation for refactoring to a Singleton [ DP ] is to give a piece of code access to hard-to-reach information (see Inline Singleton , 114, for a discussion of this). In general, it’s best to apply Limit Instantiation with Singleton (296) only when a profiler informs you that doing so is worthwhile.

Introduce Null Object (301) is a refactoring that helps transform how code is protected from null values. If you have a lot of the same conditional logic that checks for the same null value, you can likely simplify and condense the code by refactoring it to use a Null Object [ Woolf ].

Replace Type Code with Class

A field’s type (e.g., a String or int ) fails to protect it
from unsafe assignments and invalid equality comparisons.

Constrain the assignments and equality comparisons
by making the type of the field a class.

Replace Type Code with Class

Motivation

A primary motivation for refactoring from a type code to a class is to make code type-safe. One way to do that is to constrain the possible values that may be assigned to or equated with a field or variable. Consider the following type-unsafe code:

public void testDefaultsToPermissionRequested() {
   SystemPermission permission = new SystemPermission();
   assertEquals(permission.REQUESTED, permission.state());
   assertEquals("REQUESTED", permission.state());
}

This code creates a SystemPermission object. The constructor for this object sets its state field equal to the SystemPermission.REQUESTED state:

public SystemPermission() {
   state = REQUESTED;
}

Other methods within SystemPermission assign state to system permission states such as GRANTED and DENIED . Given that each of these state types was defined using String constants (like public final static String REQUESTED = "REQUESTED" ) and state was defined as type String , the two assert statements above both pass because the state field, which is accessed via the call to permission.state() , is considered equal to both SystemPermission.REQUESTED and the String , " REQUESTED ."

What’s the problem with this? The problem is that using a String value in this context is error prone. For example, what if an assert statement were accidently written like this:

assertEquals("REQEUSTED", permission.state());

Would that assert pass? No, for the String , "REQEUSTED" , has been accidently misspelled! Using a String as the type for SystemPermission ’s state field also leaves it exposed to errors like this one:

public class SystemPermission...
   public void setState(String newState){
      state = newState;
   }

permission.setState("REQESTED"); // another misspelling of "REQUESTED"

Here, the misspelling of "REQESTED" will not cause a compiler error but will allow a SystemPermission instance to enter an invalid state. Once it enters that invalid state, SystemPermission ’s state transition logic won’t allow it to ever leave that invalid state.

Using a class instead of a String to represent SystemPermission ’s state field will reduce such errors because it ensures that all assignments and comparisons are performed using a family of type-safe constants. These constants are considered to be type-safe because their type, which is a class, protects them from being impersonated by other constants. For example, in the following code, the type-safe constant, REQUESTED , lives in one class and can’t be mistaken for any other value:

public class PermissionState {
   public final static PermissionState REQUESTED = new PermissionState();

Clients that want to perform assignment or equality statements using REQUESTED can only obtain a reference to it by calling PermissionState.REQUESTED .

Using a class to obtain type safety for a family of constants was described by Joshua Bloch as the Type-Safe Enum pattern [ Bloch ]. Joshua does an excellent job of explaining this pattern and how to deal with the serialization/deserialization issues associated with it. Languages that provide native support for what are commonly called “enums” might seem to render this refactoring useless. That isn’t the case, for after you perform this refactoring, you’ll often extend your code to support more behavior, which isn’t possible with enums. For example, the first step in the mechanics for Replace State-Altering Conditionals with State (166) builds upon this refactoring but could not build upon a language-based enum.

Benefits and Liabilities

+  Provides better protection from invalid assignments and comparisons.

–  Requires more code than using unsafe type does.

Mechanics

In the steps below a type-unsafe constant is a constant defined using a primitive or non-class-based type, such as a String or int .

1.  Identify a type-unsafe field , a field declared as a primitive or non-class-based type that is assigned to or compared against a family of type-unsafe constants. Self-encapsulate the type-unsafe field by applying Self Encapsulate Field [ F ].

Image   Compile and test.

2.  Create a new class , a concrete class that will soon replace the type used for the type-unsafe field. Name this class after the kinds of types it will store. For the moment, don’t provide any constructor for the new class.

3.  Choose a constant value that the type-unsafe field is assigned to and/or compared against and define a new version of this constant in your new class by creating a constant that is an instance of the new class. In Java, it’s common to declare this constant to be public final static .

     Repeat this step for all constant values assigned to or compared against the type-unsafe field.

Image   Compile.

     You’ve now defined a family of constants in the new class. If it is important to prevent clients from adding members to that family of constants, declare a single private constructor for the new class or, if your language allows it, mark the new class as final .

4.  In the class that declared the type-unsafe field, create a type-safe field , a field whose type is the new class. Create a setting method for it.

5.  Wherever an assignment is made to the type-unsafe field, add a similar assignment statement to the type-safe field, using the appropriate constant in the new class.

Image   Compile.

6.  Change the getter method for the type-unsafe field so that its return value is obtained from the type-safe field. This requires making the constants in the new class capable of returning the correct value.

Image   Compile and test.

7.  In the class that declared the type-unsafe field, delete the type-unsafe field, the setter method for it, and all calls to the setting method.

Image   Compile and test.

8.  Find all references to the type-unsafe constants and replace them with calls to the corresponding constant in the new class. As part of this step, change the getter method for the type-unsafe field so its return type is the new class and make all changes necessary to callers of the revised getter method.

     Equality logic that once relied on primitives will now rely on comparing instances of the new class. Your language may provide a default way to do such equality logic. If not, write code to ensure that the equality logic works correctly with new class instances.

Image   Compile and test.

     Delete the now unused type-unsafe constants.

Example

This example, which was shown in the code sketch at the beginning of this refactoring and mentioned in the Motivation section, deals with handling permission requests to access software systems. We’ll begin by looking at relevant parts of the class, SystemPermission :

public class SystemPermission {
   private String state;
   private boolean granted;

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

   public SystemPermission() {
      state = REQUESTED;
      granted = false;
   }

   public void claimed() {
      if (state.equals(REQUESTED))
         state = CLAIMED;
   }

   public void denied() {
      if (state.equals(CLAIMED))
         state = DENIED;
   }

   public void granted() {
      if (!state.equals(CLAIMED)) return;
      state = GRANTED;
      granted = true;
   }

   public boolean isGranted() {
      return granted;
   }

   public String getState() {
      return state;
   }
}

1.  The type-unsafe field in SystemPermission is called state . It is assigned to and compared against a family of String constants also defined within SystemPermission . The goal is to make state type-safe by making its type be a class rather than a String .

     I begin by self-encapsulating state :

public class SystemPermission...
   public SystemPermission() {
       setState(REQUESTED);
      granted = false;
   }

   public void claimed() {
      if ( getState() .equals(REQUESTED))
          setState(CLAIMED);
   }

    private void setState(String state) {
       this.state = state;
    }

   public String getState() {  // note: this method already existed
      return state;
   }

   // etc.

     This is a trivial change, and my compiler and tests are happy with it.

2.  I create a new class and call it PermissionState because it will soon represent the state of a SystemPermission instance.

public class PermissionState {
}

3.  I choose one constant value that the type-unsafe field is assigned to or compared against and I create a constant representation for it in PermissionState . I do this by declaring a public final static in PermissionState that is an instance of PermissionState :

public final class PermissionState {
    public final static PermissionState REQUESTED = new PermissionState();
}

     I repeat this step for each constant in SystemPermission , yielding the following code:

public class PermissionState {
    public final static PermissionState REQUESTED = new PermissionState();
    public final static PermissionState CLAIMED = new PermissionState();

    public final static PermissionState GRANTED = new PermissionState();
    public final static PermissionState DENIED = new PermissionState();
}

     The compiler accepts this new code.

     Now I must decide whether I want to prevent clients from extending or instantiating PermissionState in order to ensure that the only instances of it are its own four constants. In this case, I don’t need such a rigorous level of type safety, so I don’t define a private constructor or use the final keyword for the new class.

4.  Next, I create a type-safe field inside SystemPermission , using the PermissionState type. I also create a setter method for it:

public class SystemPermission...
   private String state;
    private PermissionState permission;

    private void setState(PermissionState permission) {
       this.permission = permission;
    }

5.  Now I must find all assignment statements to the type-unsafe field, state , and make similar assignment statements to the type-safe field, permission :

public class SystemPermission...
   public SystemPermission() {
      setState(REQUESTED);
       setState(PermissionState.REQUESTED);
      granted = false;
   }

   public void claimed() {
      if (getState().equals(REQUESTED))  {
         setState(CLAIMED);
          setState(PermissionState.CLAIMED);
       }
   }

   public void denied() {
      if (getState().equals(CLAIMED))  {
         setState(DENIED);
          setState(PermissionState.DENIED);
       }
   }

   public void granted() {
      if (!getState().equals(CLAIMED))
         return;

      setState(GRANTED);
       setState(PermissionState.GRANTED);
      granted = true;
   }

     I confirm that the compiler is OK with these changes.

6.  Next, I want to change the getter method for state to return a value obtained from the type-safe field , permission . Because the getter method for state returns a String , I’ll have to make permission capable of returning a String as well. My first step is to modify PermissionState to support a toString() method that returns the name of each constant:

public class PermissionState {
    private final String name;

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

    public String toString() {
       return 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" );
}

     I can now update the getter method for state :

public class SystemPermission...
   public String getState() {
       return state;
       return permission.toString();
   }

     The compiler and tests confirm that everything is still working.

7.  I can now delete the type-unsafe field, state , SystemPermission calls to its private setter method, and the setter method itself:

public class SystemPermission...
    private String state;
   private PermissionState permission;
   private boolean granted;

   public SystemPermission() {
       setState(REQUESTED);

      setState(PermissionState.REQUESTED);
      granted = false;
   }

   public void claimed() {
      if (getState().equals(REQUESTED))  {
          setState(CLAIMED);
         setState(PermissionState.CLAIMED);
       }
   }

   public void denied() {
      if (getState().equals(CLAIMED))  {
          setState(DENIED);
         setState(PermissionState.DENIED);
       }
   }

   public void granted() {
      if (!getState().equals(CLAIMED))
         return;
       setState(GRANTED);
      setState(PermissionState.GRANTED);
      granted = true;
   }

    private void setState(String state) {
       this.state = state;
    }

     I test that SystemPermission still works as usual. It does.

8.  Now I replace all code that references SystemPermission ’s type-unsafe constants with code that references PermissionState ’s contant values. For example, SystemPermission ’s claimed() method still references the "REQUESTED" type-unsafe constant:

public class SystemPermission...
   public void claimed() {
      if (getState().equals(REQUESTED))  //  equality logic with type-unsafe constant
         setState(PermissionState.CLAIMED);
   }

     I update this code as follows:

public class SystemPermission...
   public  PermissionState  getState() {
      return permission .toString() ;
   }

  public void claimed() {
     if (getState().equals( PermissionState. REQUESTED)) {
        setState(PermissionState.CLAIMED);
  }

     I make similar changes throughout SystemPermission . In addition, I update all callers on getState() so that they now work exclusively with PermissionState constants. For example, here’s a test method that requires updating:

public class TestStates...
   public void testClaimedBy() {
      SystemPermission permission = new SystemPermission();
      permission.claimed();
      assertEquals(SystemPermission.CLAIMED, permission.getState());
   }

     I change this code as follows:

public class TestStates...
   public void testClaimedBy() {
      SystemPermission permission = new SystemPermission();
      permission.claimed();
      assertEquals( PermissionState. CLAIMED, permission.getState());
   }

     After making similar changes throughout the code, I compile and test to confirm that the new type-safe equality logic works correctly.

     Finally, I can safely delete SystemPermission ’s type-unsafe constants because they are no longer being used:

public class SystemPermission...
    public final static String REQUESTED = "REQUESTED";
    public final static String CLAIMED = "CLAIMED";
    public final static String DENIED = "DENIED";
    public final static String GRANTED = "GRANTED";

Now SystemPermission ’s assignments to its permission field and all equality comparions with its permission field are type-safe.

Limit Instantiation with Singleton

Your code creates multiple instances of an object, and
that uses too much memory or slows system performance.

Replace the multiple instances with a Singleton.

Limit Instantiation with Singleton

Motivation

If you want to be a good software designer, don’t optimize code prematurely. Prematurely optimized code is harder to refactor than code that hasn’t been optimized. In general, you’ll discover more alternatives for improving your code before it has been optimized than after.

If you use the Singleton [ DP ] pattern out of habit, because it “makes your code more efficient,” you’re prematurely optimizing. You suffer from Singletonitis and had better follow the advice in Inline Singleton (114) . On the other hand, sometimes it’s a good decision to refactor to a Singleton, as in the following scenario.

•  Users of your system are complaining about system performance.

•  Your profiler tells you that you can improve performance by not instantiating certain objects over and over again.

•  The objects you want to share have no state or contain state that is sharable.

A colleague and I profiled a system that handles security permissions. The system uses the State [ DP ] pattern (see Replace State-Altering Conditionals with State , 166 ). Every state transition leads to the instantiation of a new State object. We profiled the system to check memory usage and performance. While the instantiation of State objects wasn’t the biggest bottleneck in the system, it did contribute to slow performance under a heavy load.

Based on this research, we determined that it made sense to refactor to a Singleton in order to limit the instantiation of stateless State objects. And that’s the general idea behind this refactoring: wait for a good reason to limit instantiation and when you find one, then refactor to a Singleton. Of course, we profiled after implementing the Singleton, and memory usage was much improved.

For other reasons to refactor to a Singleton that don’t involve improving performance, see the wise words provided by Kent Beck, Ward Cunningham, and Martin Fowler earlier in this catalog at Inline Singleton (114) .

Benefits and Liabilities

+  Improves performance.

–  Is easily accessible from anywhere. In many cases, this may indicate a design flaw (see Inline Singleton , 114).

–  Is not useful when an object has state that can’t be shared.

Mechanics

Before you perform this refactoring, make sure the object you want to turn into a Singleton has no state or has state that is sharable. Because most classes that end up becoming Singletons have one constructor, these mechanics assume you have one constructor on your class.

1.  Identify a multiple instance class , a class that gets instantiated more than once by one or more clients. Apply the mechanics from Replace Constructors with Creation Methods (57) even though your class has only one constructor. The return type for your new Creation Method should be the multiple instance class.

Image   Compile and test.

2.  Declare a singleton field , a private static field of type multiple instance class in the multiple instance class and, if possible, initialize it to an instance of the multiple instance class.

     It may not be possible to initialize this field because to do so, you need arguments passed by a client at runtime. In that case, simply define the field and don’t initialize it.

Image   Compile.

3.  Make your Creation Method return the value in the singleton field. If it must be lazily instantiated, do that lazy instantiation in the Creation Method, based on whatever parameters are passed in.

Image   Compile and test.

Example

This example is based on the security code example found in the refactoring Replace State-Altering Conditionals with State (166) . If you study the code produced after applying that refactoring, you’ll find that each State instance is a Singleton. However, these Singleton State instances weren’t created for performance reasons; they resulted from performing the refactoring Replace Type Code with Class (286) .

When I initially refactored to the State pattern on the security code project, I did not apply Replace Type Code with Class (286) . I wasn’t yet aware of how much that refactoring simplifies the later steps in refactoring to the State pattern. My earlier approach to the State refactoring involved instantiating Permission subclasses each time they were needed, paying no regard to the Singleton pattern.

On that project, my colleague and I profiled our code and found several places where it could be optimized. One of those places involved the frequent instantiation of the state classes. So, as part of an overall effort to improve performance, the code to repeatedly instantiate the Permission subclasses was refactored to use the Singleton pattern. I describe the steps here.

1.  There are six State classes, each of which is a multiple instance class because clients instantiate them multiple times. In this example, I’ll work with the PermissionRequested class, which looks like this:

public class PermissionRequested extends Permission {
   public static final String NAME= "REQUESTED";

   public String name() {
      return NAME;
   }

   public void claimedBy(SystemAdmin admin, SystemPermission permission) {
      permission.willBeHandledBy(admin);
      permission.setState(new PermissionClaimed());
   }
}

      PermissionRequested doesn’t define a constructor because it uses Java’s default constructor. Because the first step in the mechanics is to convert its constructor(s) to Creation Methods, I define a Creation Method like so:

public class PermissionRequested extends Permission...
    public static Permission state() {
       return new PermissionRequested();
    }

     You’ll notice that I use Permission as the return type for this Creation Method. I do that because I want all client code to interact with State subclasses via the interface of their superclass. I also update all callers of the constructor to now call the Creation Method:

public class SystemPermission...
   private Permission state;
   public SystemPermission(SystemUser requestor, SystemProfile profile) {
      this.requestor = requestor;
      this.profile = profile;
       state = new PermissionRequested();
       state = PermissionRequested.state();
      ...
   }

     I compile and test to make sure that this trivial change didn’t break anything.

2.  Now I create the singleton field, a private static field of type Permission in PermisionRequested , and initialize it to an instance of PermissionRequested :

public class PermissionRequested extends Permission...
    private static Permission state = new PermissionRequested();

     I compile to confirm that my syntax is correct.

3.  Finally, I change the Creation Method, state() , to return the value in the state field:

public class PermissionRequested extends Permission...
   public static Permission state() {
       return state;
}

     I compile and test once again and everything works. I now repeat these steps for the remaining State classes until all of them are Singletons. At that point, I run the profiler to check how memory usage and performance have been affected. Hopefully, things have improved. If not, I may decide to undo these steps, as I’d always rather work with regular objects than Singletons.

Introduce Null Object

Logic for dealing with a null field or variable
is duplicated throughout your code.

Replace the null logic with a Null Object, an object
that provides the appropriate null behavior.

Introduce Null Object

Motivation

If a client calls a method on a field or variable that is null, an exception may be raised, a system may crash, or similar problems may occur. To protect our systems from such unwanted behavior, we write checks to prevent null fields or variables from being called and, if necessary, specify alternative behavior to execute when nulls are encountered:

if (someObject != null)
   someObject.doSomething();
else
   performAlternativeBehavior();

Repeating such null logic in one or two places in a system isn’t a problem, but repeating it in multiple places bloats a system with unnecessary code. Compared with code that is free of null logic, code that is full of it generally takes longer to comprehend and requires more thinking about how to extend. Null logic also fails to provide null protection for new code. So if new code is written and programmers forget to include null logic for it, null errors can begin to occur.

The Null Object pattern 1 provides a solution to such problems. It removes the need to check whether a field or variable is null by making it possible to always call the field or variable safely. The trick is to assign the field or variable to the right object at the right time. When a field or variable can be null, you can make it refer to an instance of a Null Object, which provides do-nothing, default, or harmless behavior. Later, the field or variable can be assigned to something other than a Null Object. Until that happens, all invocations safely route through the Null Object.

The introduction of a Null Object into a system ought to shrink code size or at least keep it even. If its implementation significantly increases the number of lines of code compared with just using null logic, that’s a good sign that you don’t need a Null Object. Kent Beck tells a story about this in his book Test-Driven Development [ Beck, TDD ]. He once suggested refactoring to a Null Object to his programming partner, Erich Gamma, who quickly calculated the difference in lines of code and explained how refactoring to a Null Object would actually add many more lines of code than they already had with their null logic.

Java’s Abstract Window Toolkit ( AWT ) could have benefited from using a Null Object. Some of its components, like panels or dialog boxes, can contain widgets that get laid out using a layout manager (like FlowLayout , GridLayout , and so forth). Code that dispatched layout requests to a layout manager was filled with checks for a null layout manager ( if (layoutManager != null) ). A better design would have been to use a NullLayout as the default layout manager for all components that used layout managers. If the default layout manager for these components was a NullLayout , the code that dispatched requests to the layout manager could have done so without caring whether it was talking to a NullLayout manager or a real layout manager.

The existence of a Null Object doesn’t guarantee that null logic won’t be written. For example, if a programmer isn’t aware that a Null Object is already protecting the code from nulls, he or she may write null logic for code that won’t ever be null. Finally, if a programmer expects a null to be returned under certain conditions and writes important code to handle that situation, a Null Object implementation could cause unexpected behavior.

My version of this refactoring extends Martin Fowler’s Introduce Null Object [ F ] by supplying mechanics to deal with a common situation: a class is sprinkled with null logic for a field because an instance of the class may attempt to use the field before the field has been assigned to a non-null value. Given such code, the mechanics to refactor to a Null Object are different from those defined in Martin’s mechanics for this refactoring.

Null Objects are often (though not always) implemented by subclassing or by implementing an interface, as shown in the following diagram.

Motivation

Creating a Null Object by subclassing involves overriding all inherited public methods to provide the appropriate null behavior. A risk associated with this approach is that if a new method gets added to the superclass, programmers must remember to override the method with null behavior in the Null Object. If they forget to do this, the Null Object will inherit implementation logic that could cause unwanted behavior at runtime. Making a Null Object implement an interface rather than being a subclass removes this risk.

Benefits and Liabilities

+  Prevents null errors without duplicating null logic.

+  Simplifies code by minimizing null tests.

–  Complicates a design when a system needs few null tests.

–  Can yield redundant null tests if programmers are unaware of a Null Object implementation.

–  Complicates maintenance. Null Objects that have a superclass must override all newly inherited public methods.

Mechanics

These mechanics assume you have the same null logic scattered throughout your code because a field or local variable may be referenced when it is still null. If your null logic exists for any other reason, consider applying Martin Fowler’s mechanics for Introduce Null Object [ F ]. The term source class in the following steps refers to the class that you’d like to protect from nulls.

1.  Create a null object by applying Extract Subclass [ F ] on the source class or by making your new class implement the interface implemented by the source class. If you decide to make your null object implement an interface, but that interface doesn’t yet exist, create it by applying Extract Interface [ F ] on the source class.

Image   Compile.

2.  Look for a null check (client code that invokes a method on an instance of the source class if it is not null, or performs alternative behavior if it is null). Overide the invoked method in the null object so it implements the alternative behavior.

Image   Compile.

3.  Repeat step 2 for other null checks associated with the source class.

4.  Find a class that contains one or more occurrences of the null check and initialize the field or local variable that is referenced in the null check to an instance of the null object. Perform this initialization at the earliest possible time during the lifetime of an instance of the class (e.g., upon instantiation).

     This code should not affect pre-existing code that assigns the field or local variable to an instance of the source class. The new code simply performs an assignment to a null object prior to any other assignments.

Image   Compile.

5.  In the class you selected in step 4, remove every occurrence of the null check.

Image   Compile and test.

6.  Repeat steps 4 and 5 for every class with one or more occurrences of the null check.

If your system creates many instances of the null object, you may want to use a profiler to determine whether it would make sense to apply Limit Instantiation with Singleton (296) .

Example

At a time when most of the world used either Netscape 2 or 3 or Internet Explorer 3 (all of which contained Java version 1.0), my company won a bid to create the Java version of a well-known music and television Web site. The site featured applets with many clickable menus and submenus, animated promotions, music news, and lots of cool graphics. The main Web page featured a frame that was divided into three sections, two of which contained applets.

Example

The company’s staff needed to easily control how the applets behaved when users interacted with them. Staff members wanted to control applet behavior without having to call programmers every time they needed to change a piece of functionality. We were able to accommodate their needs by using the Command pattern [ DP ] and by creating and using a custom mouse event handler class called MouseEventHandler . Instances of MouseEventHandler could be configured (via a script) to execute Commands whenever users moved their mouse over or clicked on regions within image maps.

Background for the Example: Mouse Events in Java 1.0

In Java 1.0, the mouse event model for Java applets relied on inheritance. If you wanted an applet to receive and handle mouse events, you would subclass java.applet.Applet and override the mouse event methods you needed, as shown in the following diagram.

Background for the Example: Mouse Events in Java 1.0

Once your applet was instantiated and running on a Web page, its mouse event methods would be called in response to mouse movements or clicks by a user.

The code worked perfectly except for one problem. During start-up, our applets would load into a browser window and initialize themselves. Part of the initialization process included getting MouseEventHandler objects instantiated and configured. To inform each MouseEventHandler instance about which areas of an applet were clickable and what Commands to run when those areas were clicked, we needed to read data and pass it to each instance. While loading that data didn’t take a lot of time, it did leave a window of time in which our Mouse EventHandler instances weren’t ready to receive mouse events. If a user happened to move or click the mouse on an applet before our custom mouse event handlers were fully instantiated and configured, the browser would bark errors onto the console and the applets would become unstable.

There was an easy fix: find every place where MouseEventHandler instances could be called when they were still null (i.e., not yet instantiated) and write code to insulate them from such calls. This solved the start-up problem, yet we were unhappy with the new design. Now, numerous classes in our system featured an abundance of null checks:

public class NavigationApplet extends Applet...
  public boolean mouseMove(Event event, int x, int y) {
     if (mouseEventHandler != null)
      return mouseEventHandler.mouseMove(graphicsContext, event, x, y );
     return true;
  }

  public boolean mouseDown(Event event, int x, int y) {
     if (mouseEventHandler != null)
      return mouseEventHandler.mouseDown(graphicsContext, event, x, y );
     return true;
  }

  public boolean mouseUp(Event event, int x, int y) {
     if (mouseEventHandler != null)
      return mouseEventHandler.mouseUp(graphicsContext, event, x, y );
     return true;
  }

  public boolean mouseExit(Event event, int x, int y) {
     if (mouseEventHandler != null)
      return mouseEventHandler.mouseExit(graphicsContext, event, x, y );
     return true;
  }

To remove the null checks, we refactored the applets so they used a NullMouseEventHandler at start-up and then switched to using a MouseEventHandler instance when one was ready. Here are the steps we followed to make this change.

1.  We applied Extract Subclass [ F ] to define NullMouseEventHandler , a subclass of our own mouse event handler:

public class NullMouseEventHandler extends MouseEventHandler {
   public NullMouseEventHandler(Context context) {
     super(context);
   }
}

     That code compiled just fine, so we moved on.

2.  Next, we found a null check, like this one:

public class NavigationApplet extends Applet...
  public boolean mouseMove(Event event, int x, int y) {
    if (mouseEventHandler != null)   // null check
      return mouseEventHandler.mouseMove(graphicsContext, event, x, y);
    return true;
  }

     The method invoked in the above null check is mouseEventHandler . mouseMove(…) . The code invoked if mouseEventHandler equals null is the code that the mechanics direct us to implement in an overridden mouseMove(…) method on NullMouseEventHandler . That was easily implemented:

public class NullMouseEventHandler...
   public boolean mouseMove(MetaGraphicsContext mgc, Event event, int x, int y) {
     return true;
   }

     The new method compiled with no problems.

3.  We repeated step 2 for all other occurrences of the null check in our code. We found the null check in numerous methods on three different classes. When we completed this step, NullMouseEventHandler had many new methods. Here are a few of them:

public class NullMouseEventHandler...
   public boolean mouseDown(MetaGraphicsContext mgc, Event event, int x, int y) {
     return true;
   }

   public boolean mouseUp(MetaGraphicsContext mgc, Event event, int x, int y) {
     return true;
   }

   public boolean mouseEnter(MetaGraphicsContext mgc, Event event, int x, int y) {
     return true;
   }

   public void doMouseClick(String imageMapName, String APID) {
   }

     The above code compiled with no difficulties.

4.  Then we initialized mouseEventHandler , the field referenced in the null check within the NavigationApplet class, to an instance of the NullMouseEventHandler :

public class NavigationApplet extends Applet...
  private MouseEventHandler mouseEventHandler  \= new NullMouseEventHandler(null);

     The null that was passed to the NullMouseEventHandler ’s constructor forwarded to the constructor of its superclass, MouseEventHandler . Because we didn’t like passing such nulls around, we altered NullMouseEventHandler ’s constructor to do this work:

public class NullMouseEventHandler extends MouseEventHandler {
  public NullMouseEventHandler( Context context ) {
     super(null);
  }
}

public class NavigationApplet extends Applet...
  private MouseEventHandler mouseEventHandler  \= new NullMouseEventHandler();

5.  Next came the fun part. We deleted all occurrences of the null check in such classes as NavigationApplet :

public class NavigationApplet extends Applet...
  public boolean mouseMove(Event event, int x, int y) {
     if (mouseEventHandler != null)
      return mouseEventHandler.mouseMove(graphicsContext, event, x, y );
     return true;
  }

  public boolean mouseDown(Event event, int x, int y) {
     if (mouseEventHandler != null)
      return mouseEventHandler.mouseDown(graphicsContext, event, x, y);
     return true;
  }

  public boolean mouseUp(Event event, int x, int y) {
     if (mouseEventHandler != null)
      return mouseEventHandler.mouseUp(graphicsContext, event, x, y);
     return true;
  }

  // etc.

     After doing that, we compiled and tested whether the changes worked. In this case, we had no automated tests, so we had to run the Web site in a browser and try repeatedly to cause problems with our mouse as the NavigationApplet applet started up and began running. Everything worked well.

6.  We repeated steps 4 and 5 for other classes that featured the same null check until it had been completely eliminated from all classes that originally contained it.

     Because our system used only two instances of the NullMouseEventHandler , we did not make it a Singleton [ DP ].

  1. Bruce Anderson aptly named this pattern active nothing [ Anderson ] because a Null Object actively performs behavior that does nothing. Martin Fowler described how a Null Object is an example of a broader pattern called Special Case [ Fowler, PEAA ]. Ralph Johnson and Bobby Woolf described how null versions of patterns like Strategy [ DP ], Proxy [ DP ], Iterator [ DP ], and others are often used to eliminate null checks [ Woolf ].