Relationships and Communication Object Model
Ivan Marsic • Rutgers
University 28
object, Figure 1-15b. Unlike a single agent traversing the entire process, we can think of OO approach as organizing many tiny agents into a “bucket brigade,” each carrying its task when
called upon, Figure 1-15c. Here are pseudo-Java code snippets for two objects, KeyChecker and LockCtrl:
Listing 1-1: Object-oriented code for classes KeyChecker left and LockCtrl right. public class KeyChecker {
protected LockCtrl lock_; protected java.util.Hashtable
validKeys_; ...
Constructor public KeyChecker
LockCtrl lc, ... { lock_ = lc;
... }
This method waits for and validates the user-supplied key
public keyEntered String key
{ if
validKeys.containsKeykey {
lock_.unlockid; }
} else { deny access
sound alarm bell? }
} }
public class LockCtrl { protected boolean
state_ = false; unlocked protected LightCtrl switch_;
... Constructor
public LockCtrl LightCtrl sw, ... {
switch_ = sw; ...
} This method sets the lock
state and handles the switch public unlock {
operate the lock device state_ = false;
switch_.turnOn; }
public lockboolean light { operate the lock device
state_ = true; if light {
switch_.turnOff; }
} }
The key developer skill in object-oriented software development is assigning responsibilities to software objects. Preferably, each object should have only one clearly defined task and that is
relatively easy to achieve. The main difficulty in assigning responsibilities arises when an object needs to communicate with other objects in accomplishing a task.
When something goes wrong, you want to know where to look or whom to single out. This is particularly important for a complex system, with many functions and interactions. Object-
oriented approach is helpful because the responsibilities tend to be known. However, the responsibilities must be assigned adequately in the first place. That is why assigning
responsibilities to software objects is probably the most important skill in software development. Some responsibilities are obvious. For example, in Figure 1-15 it is natural to assign the control
of the light switch to the LightCtrl object.
However, assigning the responsibility of communicating messages is harder. For example, who should send the message to the LightCtrl object to turn the switch on? In Figure 1-15, LockCtrl is
Chapter 1 • Introduction
29
charged with this responsibility. Another logical choice is KeyChecker, perhaps even more suitable, because it is the KeyChecker who ascertains the validity of a key and knows whether or
not unlocking and lighting actions should be initiated. More details about assigning responsibilities are presented in Section 2.4 below.