XP Home

Refactor the PIA Class

 

Before we do any refactoring we need to run the unit tests just to be sure we are at 100%. We will rely on the judgment of the unit tests to tell us if we have made a mistake while refactoring.
What we want to do here is make the code more self explanatory. We will change the parameter to the setInputBits() method from aBitMask to theInputBits. We can create a method inputs(). We can use the inputs() method in both read() and write(). We can create a method outputs() to further simplify write(). We can also create a method outputBits() to explain what ~inputBits

means to us. And last we should make the write() method synchronized for multithreading.
Between each change we run our unit tests. Each time we create a new method, each time we change a name. But for the sake of brevity we will just show you our completed code.

package simulator.r4;

public class PIA
{public static int register = 0;
public static int inputBits = 0;

public static int read()
{return inputs();}

public static void write(int theNewOutputs)
{register = inputs() + outputs(theNewOutputs);}

public static void setInputs(int theInputBits)
{inputBits = theInputBits;}

private static int inputs()
{return register & inputBits;}

private static int outputs(int theOutputs)
{return theOutputs & outputBits();}

private static int outputBits()
{return ~inputBits;};}
Now let's run those unit tests one last time now that we are done refactoring. We have correctly refactored our code making it easier to understand. Next let's work on the simulator. Spike Solution

ExtremeProgramming.org home | The Simulator |

Copyright 1999 by Don Wells.