Advertisement | |
|
When I was first struggling to understand object-oriented programming, I happened to leaf through Grady Booch's Object-Oriented Design with Applications (Addison-Wesley, February 1994). In it was a sentence that gave me my first real insight into what an object is: "An object has state, behavior, and identity."
Accompanying the sentence was a diagram that showed three sketches of a hammer. The first sketch, labeled STATE, showed a hammer with an attached sign that read, "Grade I Hammer - Hicory Handle - Steel Head." The second drawing, labeled BEHAVIOR, showed the same hammer bending over to pound a nail. The third sketch, labeled IDENTITY, showed the hammer standing on a pedestal, rising over a sea of other hammers.
Booch's definition and hammer illustration helped me get started designing objects. With time and experience, however, I realized that although in theory every object has state, behavior, and identity, in practice different object designs use state, behavior, and identity differently. Granted, most object designs I've encountered have both interesting state and interesting behavior, as predicted by Booch's definition. I call this most common object service-oriented. I have often encountered objects, however, that have little or no interesting behavior. These objects, which I call messengers, are composed primarily of state. At the other extreme are objects that have little or no interesting state. These objects, which I call performers, are composed primarily of behavior.
Moreover, some objects are immutable. Once
an immutable object's state is established at the beginning
of its lifetime, it never changes. Although every object has a unique
identity, immutable objects are differentiated more often by value
than by identity. For example, two immutable String
s
with the value "Hello, world!"
do indeed
have separate identities -- each one sits at a different address
on the heap. But because their values are the same, their identities
are irrelevant. It doesn't matter which one you pass to System.out.println
.
I came to realize that a spectrum from state
to behavior exists, and that every object design lands somewhere
on that spectrum.
Figure 3-1. The state-behavior spectrum
The basic and most common object design, the service-oriented object, has state, stored in instance variables, and behavior, contained in instance methods. A service-oriented object can be mutable or immutable. You can ask a service-oriented object to provide a service for you by invoking one of its methods. The method provides the service by taking actions, possibly changing the object's state, and returning.
Last Updated: Friday, April 26, 2002
Copyright © 1996-2002 Artima Software, Inc. All Rights Reserved. |
URL: http://www.artima.com/apidesign/object9.html
Artima.com is created by Bill Venners |