artima.com

Chapter 1 of API Design
The Object
Guideline 4. Think of objects as machines
by Bill Venners

Part 16 of 21

The Role of State Machines

On occasion, software requirements are specified with formal state machines. For example, the Java Telephony API specification includes a state-transition diagram that defines the states through which a single call can progress. Nevertheless, software requirements are most often specified with human language descriptions, not with state machines.

The complexity of most objects makes it impractical to define their behavior solely in terms of state machines. The stamp dispenser's behavior can be specified in terms of a state machine primarily because it is a contrived example. The requirements of a real-world stamp dispenser would be far more complex, and therefore far less practical to describe in terms of a state machine.

Moreover, the state transition diagram of Figure 4-1 does not completely describe the behavior of a StampDispenser. Class StampDispenser also contains a listeners instance variable, a HashSet that can contain zero to many StampDispenserListener objects. StampDispenser instances actually have more than four possible states. Because of listeners, the number of possible states a StampDispenser could have is undefined, basically infinite. This is the case with many mutable objects: they have in effect an infinite number of possible states.

I bring up state machines to flesh out the object-as-machine metaphor -- to give you a better feel for the kind of machine you are designing when you design an object. Mutable service-oriented objects act like state machines, often with an infinite number of possible states. Like any machine, an object has a user interface. Because object users are always programmers, an object's user interface is its programmer interface, its API. An object's interface in general consists of a set of accessible methods, constructors, and constants. These are the buttons, knobs, and displays that allow programmers to use the object. Invoking a method on an object corresponds to sending a message to a state machine. When a method is invoked, the object, like the state machine, potentially performs actions and changes state.

I will discuss the relationship between objects and state machines further in the context of the state pattern in Guideline ?. The topic of taming complexity in API design is a recurring theme throughout this book. But the guidelines of Chapter ? (5, Semantics) in particular should help you create interfaces that programmers will find understandable and useful.

Part 16 of 21

API Design | Contents | Book List | Printer Friendly Version | Previous | Next

Last Updated: Friday, April 26, 2002
Copyright © 1996-2002 Artima Software, Inc. All Rights Reserved.
URL: http://www.artima.com/apidesign/object16.html
Artima.com is created by Bill Venners