Chapter 3

Ob ject-Oriented Design

A cursory explanation of ob ject-oriented programming tends to emphasize the

++

syntactic features of languages suchasC or Delphi, as opp osed to their older,

non ob ject-oriented versions, C or Pascal. Thus, an explanation usually turns

rather quickly to issues such as classes and inheritance, message passing, and

virtual and static metho ds. But such a description will miss the most imp ortant

p oint of ob ject-oriented programming, which has nothing to do with syntax.

Working in an ob ject-oriented language that is, one that supp orts inheri-

tance, message passing, and classes is neither a necessary nor sucient condi-

tion for doing ob ject-oriented programming. As we emphasized in Chapters 1

and 2, the most imp ortant asp ect of OOP is the creation of a universe of largely

autonomous interacting agents. But how do es one come up with such a system?

The answer is a design technique driven by the determination and delegation of

resp onsibilities. The technique describ ed in this chapter is termed responsibility-

1

driven design.

3.1 Resp onsibility Implies Noninterference

As anyone can attest who can rememb er b eing a child, or who has raised children,

resp onsibility is a sword that cuts b oth ways. When you make an ob ject b e

it a child or a system resp onsible for sp eci c actions, you exp ect a

certain b ehavior, at least when the rules are observed. But just as imp ortant,

resp onsibility implies a degree of indep endence or noninterference. If you tell a

child that she is resp onsible for cleaning her ro om, you do not normally stand

1

The past few years have seen a p oli eration of ob ject-oriented design techniques. See

the section on further reading at the end of this chapter for p ointers to some of the

alternatives. I have selected Resp onsibility-driven design, develop ed by Reb ecca Wirfs-

bro ck [Wirfs-Bro ck 1989b , Wirfs-Bro ck 1990 ] b ecause it is one of the simplest, and it facilitates

the transition from design to programming. Also in this chapter I intro duce some of the nota-

tional techniques made p opular by the Uni ed Mo delling Language, or UML. However, space

do es not p ermit a complete intro duction to UML, nor is it necessary for an understanding of

subsequent material in the b o ok. 49

50 CHAPTER 3. OBJECT-ORIENTED DESIGN

over her and watch while that task is b eing p erformed{that is not the nature of

resp onsibility. Instead, you exp ect that, having issued a directive in the correct

fashion, the desired outcome will b e pro duced.

Similarly, in the owers example from Chapter 1, when Chris gave the request

to the Florist to deliver owers to Robin, it was not necessary to stop to think

ab out how the request would be serviced. The orist, having taken on the

resp onsibility for this service, is free to op erate without interference on the part

of the customer Chris.

The di erence b etween conventional programming and ob ject-oriented pro-

gramming is in many ways the di erence between actively sup ervising a child

while she p erforms a task, and delegating to the child resp onsibility for that

p erformance. Conventional programming pro ceeds largely by doing something

to something else{mo difying a record or up dating an array, for example. Thus,

one p ortion of co de in a software system is often intimately tied, by control and

data connections, to many other sections of the system. Such dep endencies can

come ab out through the use of global variables, through use of p ointer values, or

simply through inappropriate use of and dep endence on implementation details

of other p ortions of co de. A resp onsibility-driven design attempts to cut these

links, or at least make them as unobtrusive as p ossible.

This notion might at rst seem no more subtle than the concepts of infor-

mation hiding and mo dularity, which are imp ortant to programming even in

conventional languages. But resp onsibility-driven design elevates information

hiding from a technique to an art. This principle of information hiding b ecomes

vitally imp ortant when one moves from programming in the small to program-

ming in the large.

One of the ma jor b ene ts of ob ject-oriented programming o ccurs when soft-

ware subsystems are reused from one pro ject to the next. For example, a sim-

ulation manager such as the one we will develop in Chapter 7 mightwork for

b oth a simulation of balls on a billiards table and a simulation of sh in a sh

tank. This ability to reuse co de implies that the software can have almost no

domain-sp eci c comp onents; it must totally delegate resp onsibility for domain-

sp eci c b ehavior to application-sp eci c p ortions of the system. The ability to

create such reusable co de is not one that is easily learned{it requires exp erience,

careful examination of case studies paradigms, in the original sense of the word,

and use of a programming language in which such delegation is natural and easy

to express. In subsequentchapters, we will present several such examples.

3.2 Programming in the Small and in the Large

The di erence b etween the development of individual pro jects and of more siz-

able software systems is often describ ed as programming in the small versus

programming in the large.

Programming in the small characterizes pro jects with the following attributes:

 Co de is develop ed by a single programmer, or p erhaps by a very small

3.3. WHY BEGIN WITH BEHAVIOR? 51

collection of programmers. A single individual can understand all asp ects

of a pro ject, from top to b ottom, b eginning to end.

 The ma jor problem in the software development pro cess is the design and

development of algorithms for dealing with the problem at hand.

Programming in the large, on the other hand, characterizes software pro jects

with features such as the following:

 The software system is develop ed by a large team, often consisting of p eople

with many di erent skills. There may b e graphic artists, design exp erts, as

well as programmers. Individuals involved in the sp eci cation or design of

the system may di er from those involved in the co ding of individual com-

p onents, who may di er as well from those involved in the integration of

various comp onents in the nal pro duct. No single individual can b e con-

sidered resp onsible for the entire pro ject, or even necessarily understands

all asp ects of the pro ject.

 The ma jor problem in the software development pro cess is the management

of details and the communication of information b etween diverse p ortions

of the pro ject.

While the b eginning student will usually be acquainted with programming

in the small, asp ects of many ob ject-oriented languages are b est understo o d as

resp onses to the problems encountered while programming in the large. Thus,

some appreciation of the diculties involved in developing large systems is a

helpful prerequisite to understanding OOP.

3.3 Why Begin with Behavior?

Why b egin the design pro cess with an analysis of b ehavior? The simple answer

is that the b ehavior of a system is usually understo o d long b efore any other

asp ect.

Earlier software development metho dologies those p opular b efore the ad-

vent of ob ject-oriented techniques concentrated on ideas suchascharacterizing

the basic data structures or the overall structure of function calls, often within

the creation of a formal sp eci cation of the desired application. But structural

elements of the application can be identi ed only after a considerable amount

of problem analysis. Similarly, a formal sp eci cation often ended up as a do cu-

ment understo o d by neither programmer nor client. But behavior is something

that can b e describ ed almost from the moment an idea is conceived, and often

unlike a formal sp eci cation can b e describ ed in terms meaningful to b oth the

programmers and the client.

Resp onsibility-Driven Design RDD, develop ed by Reb ecca Wirfs-Bro ck, is

an ob ject-oriented design technique that is driven by an emphasis on b ehavior

at all levels of development. It is but one of many alternative ob ject-oriented

52 CHAPTER 3. OBJECT-ORIENTED DESIGN

' $

P

P

H

P

H

P



P

H

 P

H

H H

H

H H

Welcome

H

H H

H

to the

H H

P

P

I IKH

P H H

H

P



H

H H

the

H

P

H

H

H

H

H P H



H

H

H

H

Interactive

P H

P

H

H

H

H

H

P

H

H

H

H

Intelligent H

H

P

H

H



H

H

H

P

H

H

H

H

H

Kitchen

 P

H

H

H

H

H

H

H

H

H

H

H

Help er

H

H

H

H

H

H

H

H

H

H

H

H

Press Return

H

to b egin

H

H

H

H

H

H

& 

 

 

22222222





 



222222222

 



 

2222222



 



Figure 3.1: { View of the InteractiveIntelligent Kitchen Help er.

design techniques. We will illustrate the application of Resp onsibility-Driven

Design with a case study.

3.4 A Case Study in RDD

Imagine you are the chief software architect in a ma jor computer rm. One day

your b oss walks into your oce with an idea that, it is hop ed, will b e the next

ma jor success in your pro duct line. Your assignmentistodevelop the Interactive

Intel ligent Kitchen Helper Figure 3.1.

The task given to your software team is stated in very few words written

on what app ears to b e the back of a slightly-used dinner napkin, in handwriting

that app ears to b e your b oss's.

3.4.1 The Interactive Intelligent Kitchen Help er

Brie y, the InteractiveIntelligent Kitchen Help er I IKH is a PC-based appli-

cation that will replace the index-card system of recip es found in the average

kitchen. But more than simply maintaining a database of recip es, the kitchen

help er assists in the planning of meals for an extended p erio d, saya week. The

3.4. A CASE STUDY IN RDD 53

user of the I IKH can sit down at a terminal, browse the database of recip es,

and interactively create a series of menus. The I IKH will automatically scale the

recip es to anynumb er of servings and will print out menus for the entire week,

for a particular day, or for a particular meal. And it will print an integrated

gro cery list of all the items needed for the recip es for the entire p erio d.

As is usually true with the initial descriptions of most software systems,

the sp eci cation for the I IKH is highly ambiguous on a number of imp ortant

p oints. It is also true that, in all likeliho o d, the eventual design and development

of the software system to supp ort the I IKH will require the e orts of several

programmers working together. Thus, the initial goal of the design team must

be to clarify the ambiguities in the description and to outline how the pro ject

can be divided into comp onents to be assigned for development to individual

team memb ers.

The fundamental cornerstone of ob ject-oriented programming is to charac-

terize software in terms of behavior; that is, actions to be p erformed. We will

see this rep eated on many levels in the development of the I IKH. Initially, the

team will try to characterize, at a very high level of abstraction, the b ehavior

of the entire application. This then leads to a description of the b ehavior of

various software subsystems. Only when all b ehavior has b een identi ed and

describ ed will the team pro ceed to the co ding step. In the next

several sections we will trace the tasks the software design team will p erform in

pro ducing this application.

3.4.2 Working through Scenarios

The rst task is to re ne the sp eci cation. As we have already noted, initial

sp eci cations are almost always ambiguous and unclear on anything except the

most general p oints. There are several goals for this step. One ob jective is

to get a b etter handle on the \lo ok and feel" of the eventual pro duct. This

information can then b e carried back to the client in this case, your b oss to see

if it is in agreement with the original conception. It is likely, p erhaps inevitable,

that the sp eci cations for the nal application will change during the creation of

the software system, and it is imp ortant that the design b e develop ed to easily

accommo date change and that p otential changes b e noted as early as p ossible.

Equally imp ortant, at this p ointvery high level decisions can b e made concerning

the structure of the eventual software system. In particular, the activities to b e

p erformed can b e mapp ed onto comp onents.

In order to uncover the fundamental b ehavior of the system, the design team

rst creates a number of scenarios. That is, the team acts out the running of

the application just as if it already p ossessed a working system. An example

scenario is shown in Figure 3.2.

54 CHAPTER 3. OBJECT-ORIENTED DESIGN

Simple Browsing

Alice Smith sits down at her computer and starts the I IKH. When the program

b egins, it displays a graphical image of a recip e box, and identi es itself as the

I IKH, pro duct of I IKH incorp orated. Alice presses the return button to b egin.

In resp onse to the key press, Alice is given a choice of a numb er of options. She

elects to browse the recip e index, lo oking for a recip e for Salmon that she wishes to

prepare for dinner the next day. She enters the keyword Salmon, and is shown in

resp onse a list of various recip es. She rememb ers seeing an interesting recip e that

used dill-weed as a avoring. She re nes the search, entering the words Salmon and

dill-weed. This narrows the searchtotwo recip es.

She selects the rst. This brings up a new window in which an attractive picture

of the nished dish is displayed, along with the list of ingredients, preparation steps,

and exp ected preparation time. After examining the recip e, Alice decides it is not

the recip e she had in mind. She returns to the search result page, and selects the

second alternative.

Examining this dish, Alice decides this is the one she had in mind. She requests

a printing of the recip e, and the output is sp o oled to her printer. Alice selects

\quit" from a program menu, and the application quits.

Figure 3.2: An Example Scenario

3.5. CRC CARDS{RECORDING RESPONSIBILITY 55

3.4.3 Identi cation of Comp onents

The engineering of a complex physical system, such as a building or an auto-

mobile engine, is simpli ed by dividing the design into smaller units. So, to o,

the engineering of software is simpli ed by the identi cation and development

of software comp onents. A component is simply an abstract entity that can

p erform tasks{that is, ful ll some resp onsibilities. At this p oint, it is not nec-

essary to know exactly the eventual representation for a comp onent or how a

comp onent will p erform a task. A comp onentmay ultimately b e turned into a

function, a structure or class, or a collection of other comp onents. At this level

of development there are just two imp ortantcharacteristics:

 A comp onentmust have a small well-de ned set of resp onsibilities.

 A comp onent should interact with other comp onents to the minimal extent

p ossible.

We will shortly discuss the reasoning b ehind the second characteristic. For the

momentwe are simply concerned with the identi cation of comp onent resp onsi-

bilities.

3.5 CRC Cards{Recording Resp onsibility

As the design team walks through the various scenarios they have created, they

identify the comp onents that will be p erforming certain tasks. Every activity

that must take place is identi ed and assigned to some comp onent as a resp on-

sibility.

Comp onent Name Collab orators

List of

Description of the

other components

resp onsibilities assigned

to this comp onent

56 CHAPTER 3. OBJECT-ORIENTED DESIGN

As part of this pro cess, it is often useful to represent comp onents using small

index cards. Written on the face of the card is the name of the software comp o-

nent, the resp onsibilities of the comp onent, and the names of other comp onents

with which the comp onentmust interact. Such cards are sometimes known as

CRC Comp onent, Resp onsibility, Collab orator cards, and are asso ciated with

each software comp onent. As resp onsibilities for the comp onent are discovered,

they are recorded on the face of the CRC card.

3.5.1 Give Comp onents a Physical Representation

While working through scenarios, it is useful to assign CRC cards to di erent

memb ers of the design team. The memb er holding the card representing a com-

p onent records the resp onsibilities of the asso ciated software comp onent, and

acts as the \surrogate" for the software during the scenario simulation. He or

she describ es the activities of the software system, passing \control" to another

memb er when the software system requires the services of another comp onent.

An advantage of CRC cards is that they are widely available, inexp ensive,

and erasable. This encourages exp erimentation, since alternative designs can b e

tried, explored, or abandoned with little investment. The physical separation of

the cards encourages an intuitive understanding of the imp ortance of the logical

separation of the various comp onents, helping to emphasize the cohesion and

coupling whichwe will describ e shortly. The constraints of an index card are

also a go o d measure of approximate complexity{a comp onent that is exp ected to

p erform more tasks than can t easily in this space is probably to o complex, and

the team should nd a simpler solution, p erhaps bymoving some resp onsibilities

elsewhere to divide a task b etween two or more new comp onents.

3.5.2 The What/Who Cycle

As we noted at the b eginning of this discussion, the identi cation of comp onents

takes place during the pro cess of imagining the execution of a working system.

Often this pro ceeds as a cycle of what/who questions. First, the design team

identi es what activity needs to b e p erformed next. This is immediately followed

by answering the question of who p erforms the action. In this manner, designing

a software system is much like organizing a collection of p eople, such as a club.

Any activity that is to b e p erformed must b e assigned as a resp onsibility to some

comp onent.

A p opular bump er sticker states that phenomena can and will sp ontaneously

o ccur. The bump er sticker uses a slightly shorter phrase. We know, however,

that in real life this is seldom true. If any action is to take place, there must b e

an agent assigned to p erform it. Just as in the running of a club any action to b e

p erformed must b e assigned to some individual, in organizing an ob ject-oriented

program all actions must b e the resp onsibility of some comp onent. The secret

to go o d ob ject-oriented design is to rst establish an agent for each action.

3.6. COMPONENTS AND BEHAVIOR 57

3.5.3 Do cumentation

At this p oint the development of do cumentation should b egin. Two do cuments

should b e essential parts of any software system: the user manual and the system

design do cumentation. Work on b oth of these can commence even b efore the

rst line of co de has b een written.

The user manual describ es the interaction with the system from the user's

p oint of view; it is an excellent means of verifying that the development team's

conception of the application matches the client's. Since the decisions made in

creating the scenarios will closely match the decisions the user will b e required to

make in the eventual application, the development of the user manual naturally

dovetails with the pro cess of walking through scenarios.

Before any actual co de has b een written, the mindset of the software team

is most similar to that of the eventual users. Thus, it is at this p oint that the

develop ers can most easily anticipate the sort of questions to which a novice

user will need answers. A user manual is also an excellent to ol to verify that

the programming team is lo oking at the problem in the same way that the client

intended. A client seldom presents the programming team with a complete and

formal sp eci cation, and thus some reassurance and two-way communication

early in the pro cess, b efore actual programming has b egun, can prevent ma jor

misunderstandings.

The second essential do cument is the design do cumentation. The design

do cumentation records the ma jor decisions made during software design, and

should thus be pro duced when these decisions are fresh in the minds of the

creators, and not after the fact when many of the relevant details will have b een

forgotten. It is often far easier to write a general global description of the software

system early in the development. To o so on, the fo cus will move to the level of

individual comp onents or mo dules. While it is also imp ortant to do cument the

mo dule level, to o much concern with the details of each mo dule will make it

dicult for subsequent software maintainers to form an initial picture of the

larger structure.

CRC cards are one asp ect of the design do cumentation, but many other

imp ortant decisions are not re ected in them. Arguments for and against any

ma jor design alternatives should b e recorded, as well as factors that in uenced

the nal decisions. A log or diary of the pro ject schedule should b e maintained.

Both the user manual and the design do cuments are re ned and evolveover time

in exactly the same way the software is re ned and evolves.

3.6 Comp onents and Behavior

To return to the I IKH, the team decides that when the system b egins, the user

will b e presented with an attractive informative window see Figure 3.1. The

resp onsibility for displaying this window is assigned to a comp onent called the

Greeter. In some as yet unsp eci ed manner p erhaps by pull-down menus, button

58 CHAPTER 3. OBJECT-ORIENTED DESIGN

Greeter Collab orators

Database Manager

Display Informative Initial Message

Plan Manager

O er User Choice of Options

Pass Control to either

Recip e Database Manager

Plan Manager for pro cessing

Figure 3.3: {CRC card for the Greeter.

or key presses, or use of a pressure-sensitive screen, the user can select one of

several actions. Initially, the team identi es just ve actions:

1. Casually browse the database of existing recip es, but without reference to

any particular meal plan.

2. Add a new recip e to the database.

3. Edit or annotate an existing recip e.

4. Review an existing plan for several meals.

5. Create a new plan of meals.

These activities seem to divide themselves naturally into two groups. The

rst three are asso ciated with the recip e database; the latter two are asso ciated

with menu plans. As a result, the team next decides to create comp onents

corresp onding to these two resp onsibilities. Continuing with the scenario, the

team elects to ignore the meal plan management for the moment and moveon

to re ne the activities of the Recip e Database comp onent. Figure 3.3 shows the

initial CRC card representation of the Greeter.

Broadly sp eaking, the resp onsibility of the recip e database comp onent is

simply to maintain a collection of recip es. We have already identi ed three

elements of this task: The recip e comp onent database must facilitate browsing

the library of existing recip es, editing the recip es, and including new recip es in the database.

3.6. COMPONENTS AND BEHAVIOR 59

3.6.1 Postp oning Decisions

There are a numb er of decisions that must eventually b e made concerning how

b est to let the user browse the database. For example, should the user rst

b e presented with a list of categories, such as \soups," \salads," \main meals,"

and \desserts"? Alternatively, should the user b e able to describ e keywords to

narrow a search, p erhaps by providing a list of ingredients, and then see all the

recip es that contain those items \Almonds, Strawb erries, Cheese", or a list

of previously inserted keywords \Bob's favorite cake"? Should scroll bars b e

used or simulated thumb holes in a virtual b o ok? These are fun to think ab out,

but the imp ortant p oint is that such decisions do not need to b e made at this

p oint see Section 3.6.2, \Preparing for Change". Since they a ect only a single

comp onent, and do not a ect the functioning of any other system, all that is

necessary to continue the scenario is to assert that by some means the user can

select a sp eci c recip e.

3.6.2 Preparing for Change

It has b een said that all that is constant in life is the inevitability of uncertainty

and change. The same is true of software. No matter how carefully one tries

to develop the initial sp eci cation and design of a software system, it is almost

certain that changes in the user's needs or requirements will, sometime during

the life of the system, force changes to b e made in the software. Programmers

and software designers need to anticipate this and plan accordingly.

 The primary ob jective is that changes should a ect as few comp onents

as p ossible. Even ma jor changes in the app earance or functioning of an

application should b e p ossible with alterations to only one or two sections

of co de.

 Try to predict the most likely sources of change and isolate the e ects

of such changes to as few software comp onents as p ossible. The most

likely sources of change are interfaces, communication formats, and output

formats.

 Try to isolate and reduce the dep endency of software on hardware. For

example, the interface for recip e browsing in our application may dep end

in part on the hardware on which the system is running. Future releases

maybe p orted to di erent platforms. A go o d design will anticipate this

change.

 Reducing coupling between software comp onents will reduce the dep en-

dence of one up on another, and increase the likeliho o d that one can be

changed with minimal e ect on the other.

 In the design do cumentation maintain careful records of the design pro cess

and the discussions surrounding all ma jor decisions. It is almost certain

60 CHAPTER 3. OBJECT-ORIENTED DESIGN

that the individuals resp onsible for maintaining the software and designing

future releases will b e at least partially di erent from the team pro ducing

the initial release. The design do cumentation will allow future teams to

know the imp ortant factors b ehind a decision and help them avoid sp ending

time discussing issues that have already b een resolved.

3.6.3 Continuing the Scenario

Each recip e will b e identi ed with a sp eci c recip e comp onent. Once a recip e is

selected, control is passed to the asso ciated recip e ob ject. A recip e must contain

certain information. Basically,it consists of a list of ingredients and the steps

needed to transform the ingredients into the nal pro duct. In our scenario, the

recip e comp onentmust also p erform other activities. For example, it will display

the recip e interactively on the terminal screen. The user may b e given the ability

to annotate or change either the list of ingredients or the instruction p ortion.

Alternatively, the user may request a printed copy of the recip e. All of these

actions are the resp onsibility of the Recip e comp onent. For the moment, we will

continue to describ e the Recip e in singular form. During design we can think of

this as a prototypical recip e that stands in place of a multitude of actual recip es.

We will later return to a discussion of singular versus multiple comp onents.

Having outlined the actions that must take place to p ermit the user to browse

the database, we return to the recip e database manager and pretend the user

has indicated a desire to add a new recip e. The database manager somehow

decides in which category to place the new recip e again, the details of how this

is done are unimp ortant for our development at this p oint, requests the name of

the new recip e, and then creates a new recip e comp onent, p ermitting the user to

edit this new blank entry. Thus, the resp onsibilities of p erforming this new task

are a subset of those we already identi ed in p ermitting users to edit existing

recip es.

Having explored the browsing and creation of new recip es, we return to the

Greeter and investigate the development of daily menu plans, which is the Plan

Manager's task. In some way again, the details are unimp ortant here the

user can save existing plans. Thus, the Plan Manager can either be started

by retrieving an already develop ed plan or by creating a new plan. In the

latter case, the user is prompted for a list of dates for the plan. Each date is

asso ciated with a separate Date comp onent. The user can select a sp eci c date for

further investigation, in which case control is passed to the corresp onding Date

comp onent. Another activity of the Plan Manager is printing out the recip es for

the planning p erio d. Finally, the user can instruct the Plan Manager to pro duce

a gro cery list for the p erio d.

The Date comp onent maintains a collection of meals as well as any other an-

notations provided by the user birthday celebrations, anniversaries, reminders,

and so on. It prints information on the display concerning the sp eci ed date.

By some means again unsp eci ed, the user can indicate a desire to print all

the information concerning a sp eci c date or cho ose to explore in more detail a

3.6. COMPONENTS AND BEHAVIOR 61

 

Greeter

 

H

H

H

H

   

Plan Manager Recip e Database

   

Q

 @

Q

@

 

 Q

Q

 Q

   

Date

H

H

H

 

Recip e

Meal

   

Figure 3.4: { Communication b etween the six comp onents in the I IKH.

sp eci c meal. In the latter case, control is passed to a Meal comp onent.

The Meal comp onent maintains a collection of augmented recip es, where the

augmentation refers to the user's desire to double, triple, or otherwise increase a

recip e. The Meal comp onent displays information ab out the meal. The user can

add or remove recip es from the meal, or can instruct that information ab out the

meal b e printed. In order to discover new recip es, the user must b e p ermitted

at this p oint to browse the recip e database. Thus, the Meal comp onent must

interact with the recip e database comp onent. The design team will continue

in this fashion, investigating every p ossible scenario. The ma jor category of

scenarios we have not develop ed here is exceptional cases. For example, what

happ ens if a user selects a number of keywords for a recip e and no matching recip e

is found? How can the user cancel an activity, suchasentering a new recip e, if

he or she decides not to continue? Each p ossibilitymust b e explored, and the

resp onsibilities for handling the situation assigned to one or more comp onents.

Having walked through the various scenarios, the software design team even-

tually decides that all activities can b e adequately handled by six comp onents

Figure 3.4. The Greeter needs to communicate only with the Plan Manager and

the Recip e Database comp onents. The Plan Manager needs to communicate only

with the Date comp onent; and the Date agent, only with the Meal comp onent.

The Meal comp onent communicates with the Recip e Manager and, through this

agent, with individual recip es.

3.6.4 Interaction Diagrams

While a description such as that shown in Figure 3.4 may describ e the static re-

lationships b etween comp onents, it is not very go o d for describing their dynamic

interactions during the execution of a scenario. A b etter to ol for this purp ose is

an interaction diagram. Figure 3.5 shows the b eginning of an interaction diagram

for the interactive kitchen help er. In the diagram, time moves forward from the

62 CHAPTER 3. OBJECT-ORIENTED DESIGN

Recip e

Greeter Database Planner Comment

-

Message browse

-

Message display



Return from display



Return from browse

-

Message makePlan

Figure 3.5: { An Example interaction diagram.

top to the b ottom. Each comp onent is represented by a lab eled vertical line. A

comp onent sending a message to another comp onent is represented by a hori-

zontal arrow from one line to another. Similarly, a comp onent returning control

and p erhaps a result value back to the caller is represented by an arrow. Some

authors use two di erent arrow forms, such as a solid line to represent message

passing and a dashed line to represent returning control. The commentary on

the right side of the gure explains more fully the interaction taking place.

With a time axis, the interaction diagram is able to describ e b etter the se-

quencing of events during a scenario. For this reason, interaction diagrams can

b e a useful do cumentation to ol for complex software systems.

3.7 Software Comp onents

In this section we will explore a software comp onent in more detail. As is true

of all but the most trivial ideas, there are many asp ects to this seemingly simple

concept.

3.7.1 Behavior and State

Wehave already seen how comp onents are characterized by their b ehavior, that

is, by what they can do. But comp onents may also hold certain information.

Let us take as our prototypical comp onent a Recip e structure from the I IKH.

One way to view such a comp onent is as a pair consisting of behavior and state.

 The behavior of a comp onent is the set of actions it can p erform. The

complete description of all the b ehavior for a comp onent is sometimes

3.7. SOFTWARE COMPONENTS 63

called the protocol. For the Recip e comp onent this includes activities such

as editing the preparation instructions, displaying the recip e on a terminal

screen, or printing a copy of the recip e.

 The state of a comp onent represents all the information held within it

at a given p oint of time. For our Recip e comp onent the state includes the

ingredients and preparation instructions. Notice that the state is not static

and can change over time. For example, by editing a recip e a b ehavior

the user can make changes to the preparation instructions part of the

state.

It is not necessary that all comp onents maintain state information. For ex-

ample, it is p ossible that the Greeter comp onent will not have any state since

it do es not need to remember any information during the course of execution.

However, most comp onents will consist of a combination of b ehavior and state.

3.7.2 Instances and Classes

The separation of state and b ehavior p ermits us to clarify a p oint we avoided

in our earlier discussion. Note that in the real application there will probably

b e many di erent recip es. However, all of these recip es will perform in the same

manner. That is, the b ehavior of each recip e is the same; it is only the state{

the individual lists of ingredients and instructions for preparation{that di ers

between individual recip es. In the early stages of development our interest is in

characterizing the b ehavior common to all recip es; the details particular to any

one recip e are unimp ortant.

The term class is used to describ e a set of ob jects with similar b ehavior. We

will see in later chapters that a class is also used as a syntactic mechanism in

almost all ob ject-oriented languages. An individual representative of a class is

known as an instance. Note that b ehavior is asso ciated with a class, not with an

individual. That is, all instances of a class will resp ond to the same instructions

and p erform in a similar manner. On the other hand, state is a prop ertyofan

individual. We see this in the various instances of the class Recip e. They can all

p erform the same actions editing, displaying, printing but use di erent data

values.

3.7.3 Coupling and Cohesion

Two imp ortant concepts in the design of software comp onents are coupling and

cohesion. Cohesion is the degree to which the resp onsibilities of a single com-

p onent form a meaningful unit. High cohesion is achieved by asso ciating in a

single comp onent tasks that are related in some manner. Probably the most

frequentway in which tasks are related is through the necessity to access a com-

mon data value. This is the overriding theme that joins, for example, the various

resp onsibilities of the Recip e comp onent.

64 CHAPTER 3. OBJECT-ORIENTED DESIGN

Coupling, on the other hand, describ es the relationship between software

comp onents. In general, it is desirable to reduce the amount of coupling as

much as p ossible, since connections b etween software comp onents inhibit ease of

development, mo di cation, or reuse.

In particular, coupling is increased when one software comp onentmust access

data values{the state{held by another comp onent. Such situations should almost

always b e avoided in favor of moving a task into the list of resp onsibilities of the

comp onent that holds the necessary data. For example, one might conceivably

rst assign resp onsibility for editing a recip e to the Recip e Database comp onent,

since it is while p erforming tasks asso ciated with this comp onent that the need to

edit a recip e rst o ccurs. But if we did so, the Recip e Database agentwould need

the ability to directly manipulate the state the internal data values representing

the list of ingredients and the preparation instructions of an individual recip e.

It is b etter to avoid this tight connection bymoving the resp onsibility for editing

to the recip e itself.

3.7.4 Interface and Implementation{Parnas's Principles

The emphasis on characterizing a software comp onentby its b ehavior has one

extremely imp ortant consequence. It is p ossible for one programmer to know

howto use a comp onent develop ed by another programmer, without needing to

knowhow the comp onentisimplemented. For example, supp ose each of the six

comp onents in the I IKH is assigned to a di erent programmer. The programmer

developing the Meal comp onent needs to allow the I IKH user to browse the

database of recip es and select a single recip e for inclusion in the meal. To do

this, the Meal comp onent can simply invoke the browse b ehavior asso ciated with

the Recip e Database comp onent, which is de ned to return an individual Recip e.

This description is valid regardless of the particular implementation used by the

Recip e Database comp onent to p erform the actual browsing action.

The purp oseful omission of implementation details b ehind a simple interface

is known as information hiding. Wesay the comp onent encapsulates the b ehav-

ior, showing only how the comp onent can be used, not the detailed actions it

p erforms. This naturally leads to two di erent views of a software system. The

interface view is the face seen by other programmers. It describ es what a soft-

ware comp onent can p erform. The implementation view is the face seen by the

programmer working on a particular comp onent. It describ es how a comp onent

go es ab out completing a task.

The separation of interface and implementation is p erhaps the most imp or-

tant concept in . Yet it is dicult for students to understand,

or to motivate. Information hiding is largely meaningful only in the context of

multip erson programming pro jects. In such e orts, the limiting factor is often

not the amount of co ding involved, but the amount of communication required

between the various programmers and b etween their resp ective software systems.

As we will describ e shortly, software comp onents are often develop ed in parallel

by di erent programmers, and in isolation from each other.

3.8. FORMALIZE THE INTERFACE 65

There is also an increasing emphasis on the reuse of general-purp ose software

comp onents in multiple pro jects. For this to b e successful, there must b e minimal

and well-understo o d interconnections b etween the various p ortions of the system.

As we noted in the previous chapter, these ideas were captured by computer

scientist David Parnas in a pair of rules, known as Parnas's principles:

 The develop er of a software comp onentmust provide the intended user with

all the information needed to make e ective use of the services provided

by the comp onent, and should provide no other information.

 The develop er of a software comp onent must be provided with all the

information necessary to carry out the given resp onsibilities assigned to

the comp onent, and should b e provided with no other information.

A consequence of the separation of interface from implementation is that a

programmer can exp eriment with several di erent implementations of the same

structure without a ecting other software comp onents.

3.8 Formalize the Interface

We continue with the description of the I IKH development. In the next several

steps the descriptions of the comp onents will b e re ned. The rst step in this

pro cess is to formalize the patterns and channels of communication.

A decision should b e made as to the general structure that will b e used to im-

plement each comp onent. A comp onent with only one b ehavior and no internal

state may b e made into a function{for example, a comp onent that simply takes

a string of text and translates all capital letters to lowercase. Comp onents with

many tasks are probably more easily implemented as classes. Names are given to

each of the resp onsibilities identi ed on the CRC card for each comp onent, and

these will eventually b e mapp ed onto metho d names. Along with the names, the

typ es of any arguments to be passed to the function are identi ed. Next, the

information maintained within the comp onent itself should b e describ ed. All in-

formation must b e accounted for. If a comp onent requires some data to p erform

a sp eci c task, the source of the data, either through argument or global value,

or maintained internally by the comp onent, must b e clearly identi ed.

3.8.1 Coming up with Names

Careful thought should b e given to the names asso ciated with various activities.

Shakesp eare said that a name change do es not alter the ob ject b eing describ ed,

but certainly not all names will conjure up the same mental images in the listener.

As government bureaucrats have long known, obscure and idiomatic names can

make even the simplest op eration sound intimidating. The selection of useful

names is extremely imp ortant, as names create the vo cabulary with which the

eventual design will b e formulated. Names should b e internally consistent, mean-

ingful, preferably short, and evo cativein the context of the problem. Often a

66 CHAPTER 3. OBJECT-ORIENTED DESIGN

considerable amount of time is sp ent nding just the right set of terms to de-

scrib e the tasks p erformed and the ob jects manipulated. Far from b eing a barren

and useless exercise, prop er naming early in the design pro cess greatly simpli es

and facilitates later steps.

The following general guidelines have b een suggested:

 Use pronounceable names. As a rule of thumb, if you cannot read a name

out loud, it is not a go o d one.

 Use capitalization or underscores to mark the b eginning of a new word

reader," rather than the within a name, such as \CardReader" or \Card

less readable \cardreader."

 Examine abbreviations carefully. An abbreviation that is clear to one p er-

son may b e confusing to the next. Is a \TermPro cess" a terminal pro cess,

something that terminates pro cesses, or a pro cess asso ciated with a termi-

nal?

 Avoid names with several interpretations. Do es the empty function tell

whether something is empty, or empty the values from the ob ject?

 Avoid digits within a name. They are easy to misread as letters 0 as O,

1asl,2asZ,5asS.

 Name functions and variables that yield Bo olean values so they describ e

clearly the interpretation of a true or false value. For example, \Printer-

IsReady" clearly indicates that a true value means the printer is working,

whereas \PrinterStatus" is much less precise.

 Take extra care in the selection of names for op erations that are costly and

infrequently used. By doing so, errors caused by using the wrong function

can b e avoided.

Once names have b een develop ed for each activity, the CRC cards for each

comp onent are redrawn, with the name and formal arguments of the function

used to elicit each b ehavior identi ed. An example of a CRC card for the Date

is shown in Figure 3.6. What is not yet sp eci ed is how each comp onent will

p erform the asso ciated tasks.

Once more, scenarios or role playing should be carried out at a more de-

tailed level to ensure that all activities are accounted for, and that all necessary

information is maintained and made available to the resp onsible comp onents.

3.9 Designing the Representation

At this p oint, if not b efore, the design team can be divided into groups, each

resp onsible for one or more software comp onents. The task now is to transform

the description of a comp onent into a software system implementation. The

3.10. IMPLEMENTING COMPONENTS 67

Date Collab orators

Plan Manager

Maintain information ab out sp eci c date

Meal

Dateyear, month, day{create new date

DisplayAndEdit{display date information

in window allowing user to edit entries

BuildGro ceryListList &{add items from

all meals to gro cery list

Figure 3.6: { Revised CRC card for the Date comp onent.

ma jor p ortion of this pro cess is designing the data structures that will b e used by

each subsystem to maintain the state information required to ful ll the assigned

resp onsibilities.

It is here that the classic data structures of come into play.

The selection of data structures is an imp ortant task, central to the software

design pro cess. Once they have b een chosen, the co de used by a comp onentin

the ful llment of a resp onsibility is often almost self-evident. But data structures

must be carefully matched to the task at hand. A wrong choice can result in

complex and inecient programs, while an intelligentchoice can result in just

the opp osite.

It is also at this p oint that descriptions of b ehavior must be transformed

into algorithms. These descriptions should then b e matched against the exp ec-

tations of each comp onent listed as a collab orator, to ensure that exp ectations

are ful lled and necessary data items are available to carry out each pro cess.

3.10 Implementing Comp onents

Once the design of each software subsystem is laid out, the next step is to

implement each comp onent's desired b ehavior. If the previous steps were cor-

rectly addressed, each resp onsibilityorbehavior will b e characterized by a short

description. The task at this step is to implement the desired activities in a com-

puter language. In a later section we will describ e some of the more common

68 CHAPTER 3. OBJECT-ORIENTED DESIGN

heuristics used in this pro cess.

If they were not determined earlier say, as part of the sp eci cation of the

system, then decisions can now b e made on issues that are entirely self-contained

within a single comp onent. A decision wesaw in our example problem was how

b est to let the user browse the database of recip es.

As multip erson programming pro jects b ecome the norm, it b ecomes increas-

ingly rare that any one programmer will work on all asp ects of a system. More

often, the skills a programmer will need to master are understanding how one

section of co de ts into a larger framework and working well with other memb ers

of a team.

Often, in the implementation of one comp onent it will b ecome clear that

certain information or actions might b e assigned to yet another comp onent that

will act \b ehind the scene," with little or no visibility to users of the software

abstraction. Such comp onents are sometimes known as facilitators. We will see

examples of facilitators in some of the later case studies.

An imp ortant part of analysis and co ding at this p ointischaracterizing and

do cumenting the necessary preconditions a software comp onent requires to com-

plete a task, and verifying that the software comp onent will p erform correctly

when presented with legal input values.

3.11 Integration of Comp onents

Once software subsystems have b een individually designed and tested, they can

be integrated into the nal pro duct. This is often not a single step, but part of

a larger pro cess. Starting from a simple base, elements are slowly added to the

system and tested, using stubs{simple dummy routines with no b ehavior or with

very limited b ehavior{for the as yet unimplemented parts.

For example, in the development of the I IKH, it would b e reasonable to start

integration with the Greeter comp onent. To test the Greeter in isolation, stubs are

written for the Recip e Database manager and the daily Meal Plan manager. These

stubs need not do any more than print an informative message and return. With

these, the comp onent development team can test various asp ects of the Greeter

system for example, that button presses elicit the correct resp onse. Testing of

an individual comp onent is often referred to as unit testing.

Next, one or the other of the stubs can b e replaced by more complete co de.

For example, the team might decide to replace the stub for the Recip e Database

comp onent with the actual system, maintaining the stub for the other p ortion.

Further testing can b e p erformed until it app ears that the system is working as

desired. This is sometimes referred to as integration testing.

The application is nally complete when all stubs have b een replaced with

working comp onents. The ability to test comp onents in isolation is greatly facili-

tated by the conscious design goal of reducing connections b etween comp onents,

since this reduces the need for extensive stubbing.

During integration it is not uncommon for an error to b e manifested in one

3.12. MAINTENANCE AND EVOLUTION 69

software system, and yet to b e caused by a co ding mistakein another system.

Thus, testing during integration can involve the discovery of errors, which then

results in changes to some of the comp onents. Following these changes the com-

p onents should b e once again tested in isolation b efore an attempt to reintegrate

the software, once more, into the larger system. Reexecuting previously devel-

op ed test cases following a change to a software comp onent is sometimes referred

to as regression testing.

3.12 Maintenance and Evolution

It is tempting to think that once a working version of an application has b een

delivered the task of the software development team is nished. Unfortunately,

that is almost never true. The term describ es activities

subsequent to the delivery of the initial working version of a software system. A

wide variety of activities fall into this category.

 Errors, or bugs, can be discovered in the delivered pro duct. These must

be corrected, either in up dates or corrections to existing releases or in

subsequent releases.

 Requirements maychange, p erhaps as a result of government regulations

or standardization among similar pro ducts.

 Hardware maychange. For example, the system maybemoved to di erent

platforms, or input devices, such as a p en-based system or a pressure-

sensitive touch screen, may b ecome available. Output technology may

change{for example, from a text-based system to a graphical window-based

arrangement.

 User exp ectations may change. Users may exp ect greater functionality,

lower cost, and easier use. This can o ccur as a result of comp etition with

similar pro ducts.

 Better do cumentation may b e requested by users.

A go o d design recognizes the inevitabilityofchanges and plans an accommo-

dation for them from the very b eginning.

Chapter Summary

In this chapter wehave presentedavery abbreviated intro duction to the basic

ideas of ob ject-oriented mo deling and design. References in the following section

can b e consulted for more detailed discussion of this topic.

Ob ject-oriented design di ers from conventional software design in that the

driving force is the assignment of resp onsibilities to di erent software comp o-

nents. No action will take place without an agent to p erform the action, and

70 CHAPTER 3. OBJECT-ORIENTED DESIGN

hence every action must b e assigned to some memb er of the ob ject community.

Conversely, the b ehavior of the memb ers of the community taken together must

b e sucienttoachieve the desired goal.

The emphasis on behavior is a hall-mark of ob ject-oriented programming.

Behavior can b e identi ed in even the most rudimentary descriptions of a system,

long b efore any other asp ect can be clearly discerned. By constantly b eing

driven by b ehavior, resp onsibility driven design moves smo othly from problem

description to to co de development to nished application.

Further Reading

Resp onsibility-driven design was develop ed and rst describ ed by Reb ecca Wirfs-

Bro ck [Wirfs-Bro ck 1989b, Wirfs-Bro ck 1990]. There are many other ob ject-

oriented design techniques, such as that of Jacobson [Jacobson 1994] or Rum-

baugh [Rumbaugh 1991], but I like resp onsibility-driven design b ecause it is

among the simplest to explain, and is therefore a go o d intro duction to ob ject-

oriented design and mo deling.

Much of the most recentwork in the eld of ob ject-oriented design has cen-

tered on UML, the Uni edModeling Language. I are not going to discuss UML

in detail in this b o ok, although I do use some of their notation in describing

class diagrams. A good intro duction to UML is [Bo o ch 1999]. A slightly simpler

explanation is found in [Alhir 1998].

Other good b o oks on ob ject-oriented design include [Rumbaugh 1991] and

[Henderson-Sellers 1992].

CRC cards were develop ed by Beck [Beck 1989]. A more in-depth b o ok-

length treatment of the idea is [Bellin 1997].

Parnas's principles were rst presented in [Parnas 1972].

The guidelines on names presented in Section 3.8.1 are from [Keller 1990].

The Shakesp eare reference in that same section is to Romeo and Juliet, Act I I,

Scene 2:

What's in a name?

That whichwe call a rose,

byany other name would smell as sweet;

So Romeo would, were he not Romeo call'd,

retain that dear p erfection whichheowes without that title.

Self Study Questions

1. What are the key features of resp onsibility-driven design?

2. What are some key di erences b etween programming in-the-small and pro- gramming in-the-large?

EXERCISES 71

3. Why can a design technique based on b ehavior b e applied more easily to

p o orly-de ned problems than can, say, a design approach based on data

structures?

4. What is a scenario?

5. What are the basic elements of a comp onent?

6. What is a CRC card? What do the letters stand for?

7. What is the what/who cycle?

8. Why should a user manual b e develop ed b efore co ding b egins?

9. What are the ma jor sources of change that can be exp ected during the

lifetime of most long-lived software applications?

10. What information is conveyed byaninteraction diagram?

11. What are Parnas's principles?

12. Why is the selection of good names an imp ortant asp ect of a successful

software design e ort? What are some guidelines for cho osing names?

13. What is integration testing?

14. What is software maintenance?

Exercises

1. Describ e the resp onsibilities of an organization that includes at least six

typ es of memb ers. Examples of such organizations are a scho ol students,

teachers, principal, janitor, a business secretary, president, worker, and a

club president, vice-president, memb er. For each member typ e, describ e

the resp onsibilities and the collab orators.

2. Create a scenario for the organization you describ ed in Exercise 1 using an

interaction diagram.

3. For a common game such as solitaire or twenty-one, describ e a software

system that will interact with the user as an opp osing player. Example

comp onents include the deck and the discard pile.

4. Describ e the software system to control an ATM Automated Teller Ma-

chine. Giveinteraction diagrams for various scenarios that describ e the

most common uses of the machine.