The Furnace Example


The Furnace Example

Let's look at a more interesting example. Consider the software that might control the regulator of a furnace. The software can read the current temperature from an I/O channel and instruct the furnace to turn on or off by sending commands to a different I/O channel. The structure of the algorithm might look something like Listing 11-2.

Listing 11-2. Simple algorithm for a thermostat

const byte TERMOMETER = 0x86; const byte FURNACE = 0x87; const byte ENGAGE = 1; const byte DISENGAGE = 0; void Regulate(double minTemp, double maxTemp) {   for(;;)   {     while (in(THERMOMETER) > minTemp)       wait(1);     out(FURNACE,ENGAGE);     while (in(THERMOMETER) < maxTemp)       wait(1);     out(FURNACE,DISENGAGE);   } }

The high-level intent of the algorithm is clear, but the code is cluttered with lots of low-level details. This code could never be reused with different control hardware.

This may not be much of a loss, since the code is very small. But even so, it is a shame to have the algorithm lost for reuse. We'd rather invert the dependencies and see something like Figure 11-5.

Figure 11-5. Generic regulator


This shows that the Regulate function takes two arguments that are both interfaces. The Thermometer interface can be read, and the Heater interface can be engaged and disengaged. This is all the Regulate algorithm needs. Now it can be written as shown in Listing 11-3

This has inverted the dependencies such that the high-level regulation policy does not depend on any of the specific details of the thermometer or the furnace. The algorithm is nicely reusable.

Listing 11-3. Generic regulator

void Regulate(Thermometer t, Heater h,       double minTemp, double maxTemp) {   for(;;)   {     while (t.Read() > minTemp)       wait(1);     h.Engage();     while (t.Read() < maxTemp)       wait(1);     h.Disengage();   } }




Agile Principles, Patterns, and Practices in C#
Agile Principles, Patterns, and Practices in C#
ISBN: 0131857258
EAN: 2147483647
Year: 2006
Pages: 272

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net