XP Home

Refactor the Simulator Again


What we want to do here is remove the duplication of code. What we see is lots of code that does not use any local variable or methods which are exclusive to the owning class. We see the potential for a new class to eliminate the redundancy. We can try it and see if we like it. But first we run the unit tests to be sure we are at 100% to start. First I can extract out the boiler switch check into a separate class. We can then remove the boiler switch check from the simulator.

package simulator.r16;

public class BoilerSwitchCheck extends Object implements Switches
{private boolean boilerIsOn = false;

public void checkBoilerSwitch(SimulationInterface aGUI)
{if (wasJustSwitchedOn()) turnOnBoiler(aGUI);
if (wasJustSwitchedOff()) turnOffBoiler(aGUI);}

private void turnOnBoiler(SimulationInterface aGUI)
boilerIsOn = true;}

private void turnOffBoiler(SimulationInterface aGUI)
boilerIsOn = false;}

private boolean wasJustSwitchedOn()
{return isSwitchedOn() && boilerIsOff();}

private boolean wasJustSwitchedOff()
{return isSwitchedOff() && boilerIsOn;}

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

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

private boolean boilerIsOff()
{return !boilerIsOn;};}

Now let's run those same unit tests again. They run just fine so we refactored out the new class correctly. We can refactor out the relief valve check and the warmer switch check as well. Our simulator is now reasonably simple.

package simulator.r17;

public class Simulator extends Thread
{SimulationInterface gui;
private BoilerSwitchCheck boiler = new BoilerSwitchCheck();
private ReliefValveCheck reliefValve = new ReliefValveCheck();
private WarmerSwitchCheck warmer = new WarmerSwitchCheck();

public Simulator (SimulationInterface aGUI)
gui = aGUI;}

public void run()
{while (true)

private void sleepOneTenthSecond()
catch (InterruptedException exception)
Let's run the unit tests for this simplified simulator class. We pass the test. Now we have a different problem to solve. We have three classes almost alike. Can we create a single super class to hold most of the common code? I will leave that to you.XP Rules

ExtremeProgramming.org home | A Spike SolutionExtreme Programming Rules | About the Author

Copyright 1999 by Don Wells.