XP Home

Refactor the Simulator Itself

 

Now it is the Simulator's turn for some refactoring. So let's run those unit tests and get started. The first thing I want to do is add a method called isSwitchedOff(). Now I can change both isBoilerSwitchedOff() and isReliefValveSwitchedOff() to use it. At this point I compile and run the unit tests to be sure my small change is correct.
Then I continue by changing wasBoilerJustSwitchedOff() and wasReliefValveJustSwitchedOff() to use isSwitchedOff() directly. Now I can delete both isBoilerSwitchedOff() and isReliefValveSwitchedOff(). Again I run the unit tests to verify this small change is correct.

I can now do the same with the "on" methods as well. After each small change I run the tests before continuing.
This refactoring eliminates several of the switch specific methods. Last I will create a Switch interface to keep track of all those bit masks.

package simulator.r13;

public class Simulator extends Thread implements Switches
{SimulationInterface gui;
private boolean boilerIsOn = false, reliefValveIsOn = false;

public Simulator (SimulationInterface aGUI)
{super();
gui = aGUI;}

public void run()
{while (true)
{checkBoilerSwitch();
checkReliefValveSwitch();
sleepOneTenthSecond();};}

private void checkBoilerSwitch()
{if (wasJustSwitchedOn(BoilerSwitch, boilerIsOn)) turnOnBoiler();
if (wasJustSwitchedOff(BoilerSwitch, boilerIsOn)) turnOffBoiler();}

private void checkReliefValveSwitch()
{if (wasJustSwitchedOn(ReliefValveSwitch, reliefValveIsOn)) turnOnReliefValve();
if (wasJustSwitchedOff(ReliefValveSwitch, reliefValveIsOn)) turnOffReliefValve();}

private void turnOnBoiler()
{gui.boilerOn();
boilerIsOn = true;}

private void turnOffBoiler()
{gui.boilerOff();
boilerIsOn = false;}

private void turnOnReliefValve()
{gui.reliefValveOn();
reliefValveIsOn = true;}

private void turnOffReliefValve()
{gui.reliefValveOff();
reliefValveIsOn = false;}

private boolean wasJustSwitchedOn(int aSwitch, boolean isOnNow)
{return isSwitchedOn(aSwitch) && !isOnNow;}

private boolean wasJustSwitchedOff(int aSwitch, boolean isOnNow)
{return isSwitchedOff(aSwitch) && isOnNow;}

private boolean isSwitchedOff(int aSwitch)
{return (PIA.register & aSwitch) == 0;}

private boolean isSwitchedOn(int aSwitch)
{return !isSwitchedOff(aSwitch);}

private void sleepOneTenthSecond()
{try
{sleep(100);}
catch (InterruptedException exception)
{};};}

package simulator.r13;

public interface Switches
{static final int BoilerSwitch = 0x1000;
static final int ReliefValveSwitch = 0x2000;}
This looks like enough for now. If complexity creeps in again we will do more refactoring. Let's run those unit tests one last time to make sure we are ready to continue. How do we continue? Of course, another unit test. Spike Solution

ExtremeProgramming.org home | A Spike Solution | Another Unit Test |

Copyright 1999 by Don Wells.