9.3. The State of an Object

Many objects have states. The behavior of such an object differs depending on its current condition: the state that it is in. Thinking in terms of states of objects, and what an object can do in each state, can simplify your code.

For example, the state of a file object can be NotOpen, OpenForReading, OpenForWriting, or OpenForReadingAndWriting. A file object in the NotOpen state cannot be read or written. Events, such as the calling of an object's method, can alter the state of the object. Calling the open method for a file object can transform the state into OpenForReading, OpenForWriting, or OpenForReadingAndWriting, or it might leave the state as NotOpen, if the file is unavailable.

9.3.1. State Diagrams

In Sam's system, a CDDisc has the state Rented or NotRented. A CDDisc that is Rented cannot be rented again. You can depict the transition between these states by using a state diagram, such as that shown in Figure 9-2.

Figure 9-2. CDDisc state diagram

State diagrams are not just for developers. They also help users specify system behavior. They help explain how the system's state changes in response to operations, and they can clarify missing specifications. Suppose that Sam wanted to track lost CDDiscs. We prepare a state diagram (shown in Figure 9-3) to demonstrate the transitions between the Lost and InService states and the events that ...

Get Prefactoring now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.