Saturday, February 28, 2009

Challenge Two - State Design Pattern

In Programming Without Ifs Challenge One we identified the varying behavior which depended on the state of the calculator, and abstracted it with the introduction of a Strategy Design Pattern. Then when the calculator switched from the pre-operator mode to the post-operator mode, the calculator model also switched to the appropriate strategy. Thus, the calculator model was not kept in a state of ignorance. It didn't need to employ conditional logic to ask itself what state it was in to decide what to do - it already knew. The logic for switching between the strategies, ie., knowing when a change of state occurred and what to do about it, stayed on the calculator model. Our refactoring just implemented it in a different way. In Programming Without Ifs Challenge Two, we use the State Design Pattern, which moves the knowledge for what to do to the classes that characterize the state machine. Challenge Two involves programming a stopwatch.

Consider the scheme of the stopwatch interface shown below.

The stopwatch is started by clicking on the Start/Stop button. The watch is started as evidenced by the time label and the 'HOLD' button is activated. The watch can now be stopped or suspended as shown in the figure below.

The suspended mode is for timing splits. By clicking on the 'HOLD' button again, the watch will catch up to it's original timing and subsequent suspensions can again occur indefinitely. The watch can be stopped by clicking on 'START/STOP' from either the suspended mode or the running mode. After stopping the watch, the 'RESET' button will be activated as shown below.

After clicking on 'RESET' the watch will return to its starting mode as shown in the first schematic. A state diagram for the stopwatch is shown below.

Download for the code for the stopwatch with conditional logic and refactor such that no conditional logic is used to manage the state dependencies of the application. It may be necessary to create more states than shown in the state diagram above.

No comments:

Post a Comment