Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
14 views61 pages

Konsep SQ 2

Uploaded by

Putut Budiutomo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views61 pages

Konsep SQ 2

Uploaded by

Putut Budiutomo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

Object-Oriented Design:

Fundamentals
Chapter Twelve

Learning Objectives
After reading this chapter, you should be able to:

Explain the purpose and objectives of


object-oriented design
Develop design class diagrams
Chapter Outline Use CRC cards to define class responsibilities
and collaborations
Object-Oriented Design: Bridging from
Analysis to Implementation Explain important fundamental principles of
object-oriented design
Steps of Object-Oriented Design
Design Classes and the Design Class Diagram
Designing with CRC Cards
Fundamental Principles for Good Design

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
366 PART 5 ■ Advanced Design and Deployment Concepts

Opening case N ew Capital Bank: Part 1

Bill Santora, the project leader responsible for devel- convincing everybody that the project schedule wasn’t
oping an integrated customer account system at New too risky. The upside is that because each iteration is
Capital Bank, just met with the review committee and only four weeks long, we have something to show right
finished a technical review of the new system’s first-cut at the beginning. You don’t know how relieved I am that
design. This first-cut design focused on four fundamen- the design passed the review! The team has done a
tal core use cases and would be implemented in the first lot of work to make sure the design is solid, and we all
development iteration. felt confident.”
New Capital Bank had been using object-oriented “Well, building it incrementally makes a lot of sense
techniques for quite a while, but it had been slower to and certainly seems to be working,” Mary said. “I espe-
adopt some of the newer Agile approaches. Bill had cially liked the diagrams you showed. It was terrific how
been involved in some pilot projects that had used Uni- the three-layer architectural design supported each use
fied Modeling Language (UML) to develop systems case. Even though I don’t consider myself an advanced
using object-oriented techniques. However, this devel- object-oriented technician, I could understand how the
opment project was his first large-scale project that object-oriented design fit into the architecture. I think
would be entirely Agile. you wowed everybody when you demonstrated how
As Bill was collecting his presentation materials, his you could use the same basic design to support both
supervisor, Mary Garcia, spoke to him: “Your technical our internal bank tellers and a Web portal for our cus-
review went very well, Bill,” she said. “The committee tomers. Congratulations.”
found only a few minor items that need to be fixed. And Bill picked up on Mary’s enthusiasm.
even though I am not completely current on the new “How about the design class diagrams?” he asked.
approach, it was easy for me to understand how these “Don’t they give a nice overview of the classes and the
core functions will work. I still find it hard to believe that methods? We use them extensively as a focus for dis-
you will have these four pieces implemented in the next cussion on the team. They really help the programmers
few weeks though.” write good, solid code.”
“Wait a minute,” Bill said, laughing. “It won’t Mary nodded in agreement and added, “By the
be ready for the users then. Getting these four core way, have you scheduled a review with the users?”
functions coded and running doesn’t mean that we Mary asked.
are almost done. This project will still take a year to “No, not yet,” Bill replied. “The architectural design is
complete.” mostly technical stuff, and we aren’t quite ready to meet
“Yes, I know,” Mary said. “But it is nice that we will with the users. The users will help us by verifying our
have something to show after only one month. Not only understanding of the information availability, but much of
do I feel more confident in this project, but the users what we do now is too technical for them to follow.”
love to see things developing.” “I am excited to see the first pieces run,” Mary said.
“I know,” Bill said. “Remember how much grief “It just makes so much sense to be able to test these
I got when I originally laid out this plan based on an core functions during the rest of the project. Let me
iterative approach? It was difficult to detail the project congratulate you again.” Then, they headed off to lunch
schedule for the later iterations, so I had a hard time together.

■■ Overview
In Chapters 3, 4, and 5, you learned how to do object-oriented analysis by devel-
oping functional requirements models. You learned that analysis consists of two
parts: discovery and understanding. Discovery is learning exactly how the user
conducts his activities through probing questions that provide detailed informa-
tion. Understanding is taking the information gleaned from user interviews and
constructing a set of interrelated and comprehensive models. Model building is
an essential part of understanding the user needs and how they influence the
proposed system. However, the objective of analysis models isn’t to describe the
new system, but to understand, in precise terms, the requirements.
In Chapters 6 and 7, you learned about the need and importance of tech-
nology architecture and application software architecture. Chapter 7 distin-
guished the difference between large software components, such as systems or

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 12 ■ Object-Oriented Design: Fundamentals 367

subsystems, and smaller software components, such as classes and methods.


This chapter and the next focus on classes and methods.
This chapter and the next discuss object-oriented design, specifically, on
the internal structure of a software system or subsystem. You will learn how
to develop object-oriented design models based on the requirements models,
which are then used by the programmers to code the system. This chapter first
explains design class diagrams, which are an extension of the problem domain
class diagram with design information added. Next, it explains class responsi-
bility collaboration (CRC) cards to begin teaching the details of use-case-driven,
object-oriented design.
This chapter ends with an important discussion of design principles for good
object-oriented design. Throughout this chapter and the next, you learn not only
the basics of object-oriented design but also the teaching principles underlying it,
so the systems you build are well structured and maintainable. These design prin-
ciples will provide you with a solid foundation for designing systems correctly.

■■ Object-Oriented Design: Bridging from


Analysis to Implementation
So, what is object-oriented design? It is a process by which a set of detailed
object-oriented design models are built, which are then used by the program-
mers to write and test programs for the new system. Systems design is the bridge
between user requirements and programming the new system. One strength of
the object-oriented approach is that the design models are often just extensions
of the requirements models. Obviously, it is much easier to extend an existing
model than to create entirely new design models. Frequently, developers like to
skip the design model step; however, it is a good practice to create design models
and not just jump into coding. Just as a builder doesn’t build something larger
than a doghouse or a shed without a set of blueprints, a good system developer
would never try to develop a large system without a set of design models.
One tenet of Agile, adaptive development approaches emphasized through-
out this text is to create models only if they have meaning and are necessary.
Sometimes, new developers misinterpret this guideline to mean that they don’t
need to develop design models at all. The design models may not be formal-
ized into a comprehensive set of documents and diagrams, but they are certainly
necessary. Developing a system without doing design is comparable to writing
a research paper without an outline. You could just sit down and start writing;
however, if you want a paper that is cohesive, complete, and comprehensive,
you should write an outline first. You could write a complex paper without an
outline, but in all probability, it would be disjointed, hard to follow, and miss-
ing important points—and it would earn a low grade! The outline can be jot-
ted down on paper, but the process of thinking it through and writing it down
allows the writer to ensure that it is cohesive. Systems design provides the same
type of framework.
There are three subheadings in this section. First, you’ll review how an
object-oriented application works. Second, you’ll identify the analysis models
that are used for object-oriented design and indicate how they flow into the
design models. Third, you’ll learn about the design models that support the pro-
grammers. In other words, the following sections discuss the design models used
for programming.

■■ Overview of Object-Oriented Programs


Let’s quickly review how an object-oriented program works. Many of you will
be familiar with these ideas from your programming classes.

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
368 PART 5 ■ Advanced Design and Deployment Concepts

An object-oriented program consists of sets of computing objects. Each


object has data and program logic encapsulated within itself. Analysts define
the structure of the program logic and data fields by defining a class. The class
definition describes the structure or a template of what an executing object
looks like. The object itself doesn’t come into existence until the program begins
instantiation creation of an object to execute. This is called an instantiation of the class—that is, making an
based on the template provided by the instance (an object) based on the template provided by the class definition.
class definition
An object-oriented program consists of a set of these instantiated objects
that cooperate to accomplish a result. These objects work together by sending
each other messages and working in concert to support the functions of the
main program.
Figure 12-1 depicts how an object-oriented program works. The program
includes a window object that displays a form in which to enter a student ID and
other information (message 1). From the user perspective, this object appears as
a form on a screen. After the student ID is entered, the Window object sends a
message (message 2) to the Student class to tell it to create a new Student object
(instance) in the program. The new Student object will know that it needs more
data for some of its attributes based on internal logic in the student class, so it
will send a message to a Database Access object asking for data from the data-
base (message 3). Once it is completely instantiated with all the required data,
the Student object sends the information back to the Window object to display
it on the screen. The student user then enters the updates to her personal infor-
mation (message 4), and another sequence of messages is sent to update the Stu-
dent object in the program, which forwards information to the Database Access
object and writes it to the database.
The important concept you should understand is that an object-oriented
program consists of many objects. Within each object, the program logic exists

Figure 12-1 Object-oriented


event-driven program flow

© Cengage Learning ®

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 12 ■ Object-Oriented Design: Fundamentals 369

in small segments called methods. These methods are “called” or invoked


through messages. In the example in Figure 12-1, there are three objects,
each of which has a unique job to do. These three objects can relate back to
­concepts you learned in Chapter 7 about three-layer architecture. Referring
back to ­Figure 7-11, “Three-layer architecture,” the three-layers translate to the
three objects in Figure 12-1: the Window object (view layer), the Student object
(domain layer), and the Database Access object (data layer).
You can look inside a class and see the program code that corresponds to
the functions performed by the objects once they are instantiated. Figure 12-2
illustrates an example of the program code for a class with its parameters and
methods. Part (a) is the code for Java, and part (b) is the code for VB.NET. The
methods, such as getFullName ( ), are the pieces of executable code that carry
out the functions of the class.

■■ Analysis Models to Design Models


As you remember, during analysis two types of information are captured, which
are used to define the requirements: information about things and informa-
tion about the business processes. A domain model class diagram described the
information about things, and use case descriptions, activity diagrams, and sys-
tem sequence diagrams described the information about the business processes.
In other words, requirements are documented as domain classes and business
processes.
To write a computer program, a programmer needs to know what the
classes are, and what the methods are in those classes. If you think through
Figure 12-1 again, note that the example covers a single use case, perhaps one
called Update student information. This is an important programming concept!
A programmer will work on one use case at a time. She will select a use case and
program the appropriate methods in the required classes to carry out that use
case. Hence, the design models must support that activity. In other words, the
design models must provide the information required to (1) identify the classes
and (2) document the flow of execution—both for a single use case.
Figure 12-3 illustrates how this model building process flows from analy-
sis to design to implementation. Again, note the two types of information—­
information about things, and information about the flow or the process. The
analysis flow models document the flow of the business process, while the design
flow models document the flow of execution through the classes.

■■ Introduction to the Design Models


The primary model used to document the classes and the methods is the design
class diagram. The design class diagram is an extension of the domain model
class diagram that was developed during analysis activities and requirements
definition. Figure 12-4 illustrates a Student class both as the domain class and
as the design class. The primary difference is the addition of the method sig-
natures for the class. A method signature includes the method name, the input
parameters, and the type for the returned value. Notice that the method names
given in the bottom panel of the design class correspond to method names found
in the code in Figures 12-2a and b. You’ll learn more about the design class dia-
gram in the section “Design Classes and Design Class Diagram.”
To document the flow of execution of a particular use case, you use the
information provided in a UML interaction model or a CRC card. Each of the
following three models captures essentially the same information, so you do
not need to use all three for any given use case. For a particular use case, you
would only use one. The three models are a sequence diagram, a communica-
tion diagram, or CRC (class responsibility collaboration) cards. Sequence dia-
grams and communication diagrams are standard UML interaction diagrams.

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
370 PART 5 ■ Advanced Design and Deployment Concepts

Figure 12-2a Example of class definition in Java with several methods

public class Student


{
//attributes
private int studentID;
private String firstName;
private String lastName;
private String street;
private String city;
private String state;
private String zipCode;
private Date dateAdmitted;
private float numberCredits;
private String lastActiveSemester;
private float lastActiveSemesterGPA;
private float gradePointAverage;
private String major;

//constructors
public Student (String inFirstName, String inLastName, String inStreet,
String inCity, String inState, String inZip, Date inDate)
{
firstName = inFirstName;
lastName = inLastName;
...
}
public Student (int inStudentID)
{
//read database to get values
}

//get and set methods


public String getFullName ( )
{
return firstName + " " + lastName;
}
public void setFirstName (String inFirstName)
{
firstName = inFirstName;
}
public float getGPA ( )
{
return gradePointAverage;
}
//and so on

//processing methods
public void updateGPA ( )
{
//access course records and update lastActiveSemester and
//to-date credits and GPA
}
}

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 12 ■ Object-Oriented Design: Fundamentals 371

Figure 12-2b Example of class definition in VB.NET with several methods

Public Class Student

'attributes
Private studentID As Integer
Private firstName As String
Private lastName As String
Private street As String
Private city As String
Private state As String
Private zipCode As String
Private dateAdmitted As Date
Private numberCredits As Single
Private lastActiveSemester As String
Private lastActiveSemesterGPA As Single
Private gradePointAverage As Single
Private major As String

'constructor methods
Public Sub New(ByVal inFirstName As String, ByVal inLastName As String,
ByVal inStreet As String, ByVal inCity As String, ByVal inState As String,
ByVal inZip As String, ByVal inDate As Date)
firstName = inFirstName
lastName = inLastName
...
End Sub

Public Sub New(ByVal inStudentID)


'read database to get values
End Sub

'get and set accessor methods


Public Function GetFullName() As String
Dim info As String
info = firstName & " " & lastName
Return info
End Function

Public Property firstName()


Get
Return firstName
End Get
Set(ByVal Value)
firstName = Value
End Set
End Property

Public ReadOnly Property GPA()


Get
Return gradePointAverage
End Get
End Property

'Processing Methods
Public Function UpdateGPA()
'read the database and update last semester
'and to date credits and GPA
End Function

End Class

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
372 PART 5 ■ Advanced Design and Deployment Concepts

Figure 12-3 Analysis models to design models to programming models

Analysis Models Design Models Programming Models

Information about Problem domain


Design class diagram
Things class diagram

Object-oriented
program classes
Use case Communication with methods
descriptions diagrams

System sequence Sequence


Information about
diagrams diagrams
Process Flow and
Flow of Execution

Activity diagrams CRC cards

Figure 12-4 Student class example with domain class and design class

Domain diagram Student Design class diagram Student

Student Student

studentID -studentID: integer {key} Elaborated


name -name: string attributes
address -address: string
dateAdmitted -dateAdmitted: date
lastSemesterCredits -lastSemesterCredits: number
lastSemesterGPA -lastSemesterGPA: number
totalCreditHours -totalCreditHours: number
totalGPA -totalGPA: number
major -major: string

+createStudent (name, address, major): Student


+createStudent (studentID): Student
+changeName (name)
+changeAddress (address)
+changeMajor (major) Method signatures
+getName ( ): string
+getAddress ( ): string
© Cengage Learning ®

+getMajor ( ): string
+getCreditHours ( ): number
+updateCreditHours ( )
+findAboveHours (int hours): studentArray

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 12 ■ Object-Oriented Design: Fundamentals 373

Figure 12-5 Sequence diagram


for updating student name

:StudentUpdController :Student
Actor

changeName (studentID, name)

changeName (name)

© Cengage Learning ®
nameUpdate

CRC cards are not standard UML, but are very popular for designing simple
systems. This section introduces you to all three.
You first learned about sequence diagrams in Chapter 5 when you learned
about system sequence diagrams (SSD). An SSD only had two actors, the external
actor and the system. A sequence diagram expands the system object to identify
the internal interacting objects. Figure 12-5 illustrates a simple sequence diagram.
Notice that the: System object is no longer included, but two of the internal objects
are shown. Also notice the message arrows between the interacting objects.
A communication diagram is similar to a sequence diagram and serves the
same purpose. Some developers prefer sequence diagrams, whereas others prefer
communication diagrams. Each provides basically the same information, but in
different formats. Each also has strengths and weaknesses. Figure 12-6 illus-
trates a communication diagram for the same use case as Figure 12-5, updating
student name. Chapter 13 elaborates the details and benefits of both sequence
and communication diagrams.
The third model that is used to do detailed object-oriented design and to
provide information for the design class diagram is CRC cards. Even though
the CRC card method is not a standard UML diagraming approach, it provides
a straightforward approach for detailed object-oriented design, especially for
simple use cases, and thus has become popular. (Remember that object-oriented
design is use-case-driven—design is done use case by use case.)
CRC cards include a set of cards, with each card representing a class. ­Developers
use 3 x 5 cards or some other method to document each card. Each card identifies
the class, its responsibilities (i.e., its methods), and the other classes with which it
collaborates. Figure 12-7 shows both front and back sides of one single CRC card.
The card represents a class. The list on the left is the “responsibilities.” The list on
the front right is the other classes with which this class must “collaborate.” In a later
section, “Designing with CRC Cards,” you will learn how to use these cards.

Figure 12-6 Communication diagram for updating student name

1: changeName (studentID, name) 1.2: changeName (name)

: St u de nt U p dCo nt ro l l er :Student

Actor
1.3: nameUpdate

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
374 PART 5 ■ Advanced Design and Deployment Concepts

Figure 12-7 Sample CRC card for


the Student class Student
StudentId
change name Sale name
change address Payment address
change major dateAdmitted
get name lastSemesterCredits
lastSemesterGPA
get address
totalCreditHours
get major
total GPA
get credit hours major

Front of card Back of card

An object-oriented system designer must provide enough detail so a pro-


grammer can write the initial class definitions, including the method code. The
following sections and Chapter 13 explain these models in more depth and
explain how to use them to perform detailed design.

■■ Steps of Object-Oriented Design


The previous section identified the primary models used for object-oriented
design and the source models from analysis activities. As you saw in Figure 12-1,
an object-oriented program will have classes in three separate layers: user inter-
object-oriented design the process to face, problem domain, and database access layers. Thus, object-oriented
identify the set of classes, their methods, and design is the process that identifies and describes the classes within each layer
their messages required to execute a use case and defines the messages that are used to invoke the methods of the involved
classes. Object-oriented design is an analytical, rigorous, and detailed process.
Don’t be discouraged if it takes several tries before you feel comfortable with
this skill.
Another important issue about object-oriented design is that it is “use-case-
driven.” As was discussed earlier, a programmer will code all of the methods
across various classes that are required to implement the flow of execution of a
single use case. Object-oriented design is done the same way. A single use case
is chosen and the appropriate models are constructed or updated to describe the
details of the use case. Note in the definition of object-oriented design, it empha-
sizes this fact of being use-case-driven.
Because the process of object-oriented design is quite rigorous, sometimes
developers are tempted to skip the design step and move directly to program-
ming. In fact, with simple use cases, at times it is easier just to code the use case,
rather than develop a formal use case design. As has been discussed earlier with
Agile development, the objective of development activities should always be to
create accurate, robust software. If a model or diagram will assist in that objec-
tive, then it should be created. If it does not contribute directly to the end result,
then time should not be spent on it. However, you should not just skip modeling
with the assumption that a model is a distraction rather than a necessary step in
creating a solid design for the software.
Figure 12-8 illustrates steps required in object-oriented design. The first
step is to choose a single use case. Then, you create a model, the type of which
depends on the complexity of the use case. The final result is to produce a com-
plete design class diagram with supporting detail as required from interaction
diagrams.
Developers will use different types of models depending on the complexity
of the use case they are designing. This figure identifies three possible model
paths for generating a final design class diagram. The path on the far left, using
CRC cards, is often used for use cases that are straightforward and do not

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 12 ■ Object-Oriented Design: Fundamentals 375

Figure 12-8 Object-oriented design process for a single use case

Use Case Diagram


• Choose a use case

First-Cut
Design Class Diagram

• Identify classes
• Elaborate attributes
• Identify navigation
Simple use cases Complex use cases

Moderately
complex use cases

CRC Cards Communication Diagrams Sequence Diagrams

• Determine responsibilities • Identify messages • Identify messages


• Determine collaborations • Define parameters • Define parameters
• Add multilayer objects • Add multilayer objects

Final Design Class Diagram

• Add and elaborate methods


• Finalize navigation

Package Diagrams

• Configure packages with classes


• Determine dependencies

require extensive design decisions. The middle path, using communication dia-
grams, can be used for use cases that are more complex. The path on the right,
using sequence diagrams, can be used for any use case, no matter the level of
complexity. No matter which technique is used, detailed design does require a
careful thought process to ensure a solid, well-constructed solution.
In any of the three techniques for modeling, the objective is to identify and
define the methods that are required in each class. The final design class dia-
gram documents these required methods. It should be noted that each use case
will have a separate sequence diagram or communication diagram. Furthermore,
the design class diagram is a growing model because as each use case design is
finished, the new methods are added to the existing design class diagram. It is a
composite model containing the method names for all use cases.
Finally, a package diagram can also be added to divide the classes into
components or subsystems that can be implemented as a unit. Some develop-
ers use package diagrams, but many do not. The following section begins the
detailed discussion about design by going into more depth about the design
class diagram.

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
376 PART 5 ■ Advanced Design and Deployment Concepts

■■ Design Classes and the Design Class Diagram


The design class diagram contains the final definition of each class in the final
object-oriented software system. The primary source of information for this dia-
gram is the problem domain model. Hence, the problem domain model serves
as the basis for both database design, as you learned in Chapter 9, and for
the software classes as defined in the design class diagram. First, you need to
understand the diagram itself, and then you’ll learn how it is created during the
design process.
The domain model class diagram shows a set of problem domain classes and
their associations. During analysis, because it is a discovery process, analysts
generally don’t worry much about the details of the attributes. However, because
in object-oriented programming the attributes of a class must be declared as
public or private and each attribute must also be defined by its type, such as
character or numeric, it is important to elaborate on these details as well as
to define the methods and parameters that are passed to the methods and the
return values from methods.
As developers build the design class diagrams, they add many more classes
that were not originally defined in the domain model. Referring to Figure 12-1,
the Input window objects and Database access objects are examples of addi-
tional classes that are not problem domain classes. The classes in a system can
be partitioned into distinct categories, such as user-interface classes or data
access classes. At times, designers may also develop distinct class diagrams by
subsystem. The following section now turns to design class diagram notation
and discusses the design principles used in developing the first iteration of the
design class diagram.

■■ Design Class Stereotypes


UML doesn’t specifically distinguish between design class notation and domain
model class diagram notation. However, practical differences occur simply
because the objective of design modeling is distinct from that of domain model-
ing. Domain modeling shows things in the users’ work environment and the
naturally occurring associations among them. At that point, the classes aren’t
specifically software classes. After you start a design class diagram, though, you
are specifically defining software classes. Because many different types of design
classes are identified during the design process, UML has a special ­notation—
called a stereotype—that allows designers to designate a special type of class.
stereotype a way of categorizing a model A stereotype is simply a way to categorize a model element as a certain type.
element by its characteristics, indicated by A stereotype extends the basic definition of a model element by indicating that
guillemets (« »)
it has some special characteristic you want to highlight. The notation for a ste-
reotype is the name of the type placed within printer’s guillemets, like this:
«control».
Four types of design classes are considered standard stereotypes: an entity
class, a boundary or view class, a controller class, and a data access class.
­Figure 12-9 shows the notation used to identify these four stereotypes.
entity class a design stereotype for a An entity class is the design stereotype for a problem domain class. It typi-
problem domain class cally describes something users deal with when doing their work. Objects of
entity classes usually need to be remembered and are also referred to as persis-
persistent class an entity class whose tent classes. A persistent class is an entity stereotyped class with objects that
objects must continue to exist after a system exist after the program quits. However, persistency is usually not indicated as a
is shut down stereotype. The way to make data persistent is to write it to a file or database so
that it is saved and can be retrieved at a later execution of the software.
boundary or view class a class that
exists on a system’s automation boundary,
A boundary or view class is specifically designed to live on the system’s
such as a user interface or a system automation boundary. In a desktop system, these classes would be the windows
interface class classes or Web pages and all the other classes associated with the user interface.

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 12 ■ Object-Oriented Design: Fundamentals 377

Figure 12-9 Standard stereotypes


found in UML design models «entity» «controller»
Customer UseCaseHandler

«boundary» «dataAccess»
SalelnputWindow SaleDBReader

A boundary class could also be a system interface between a company’s system


and an external system. So a boundary stereotype is either a user or a system
interface class.
controller class a class that medi- A controller class mediates between the boundary classes and the entity
ates between boundary classes and entity classes. In other words, its responsibility is to catch the messages from the bound-
classes, acting as a switchboard between the
ary class objects and send them to the correct entity class objects. It acts as a
­boundary or view layer and domain layer
kind of switchboard between the boundary or view layer and the domain layer.
data access class a class that is used to A data access class is used to retrieve data from and send data to a data-
retrieve data from a database base. Sometimes it is also called a database access class. Rather than insert data-
base access logic, including SQL statements, into the entity class methods, a
separate layer of classes to access the database is often included in the design.

■■ Design Class Notation


Figure 12-10 shows the details within a design class. Refer back to Figure 12-4
to see an example. The name compartment includes the stereotype name, class
name, and superclass name (if any). The lower two compartments contain more
details about the attributes and the methods.
The format that analysts use to define each attribute includes the following:
visibility a notation that indicates (by plus ■■ Visibility—Visibility denotes whether other objects can directly access the
or minus sign) whether an attribute can be attribute. (The values for visibility are a plus sign, which indicates that an
directly accessed by another object attribute is visible, or public, and a minus sign, which indicates that it isn’t
visible, or is private, i.e. “1” 5 visible, “2” 5 invisible.)
■■ Attribute-name
■■ Data-type-expression (such as character, string, integer, number, currency,
or date)
■■ Initial-value, if applicable
■■ Property (within curly braces), such as {key}, if applicable

Figure 12-10 Notation used to Class names. Note


define a design class the camel case
notation.
«StereotypeName»
ClassName::SuperClass

Attributes.
visiblity attribute-name: data-type-expression = initial-value {property}
© Cengage Learning ®

Method signatures.
visiblity method-name (parameter-list): return-type-expression

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
378 PART 5 ■ Advanced Design and Deployment Concepts

The third compartment contains the method signature information.


method signature a notation that shows A method signature shows all the information needed to invoke (or call) the
all the information needed to invoke, or call, method. It shows the format of the message that must be sent, which consists of
the method these attributes:
■■ Method visibility
■■ Method-name
■■ Method-parameter-list (incoming arguments)
■■ Return-type-expression (the type of the return parameter from the method)
The domain model attribute list contains all attributes discovered during
analysis activities. The design class diagram includes more information on attri-
bute types, initial values, and properties. It can also include a stereotype for
clarification. As shown in Figure 12-4 in the Student design class diagram, the
third compartment contains the method signatures for the class. Remember that
UML is meant to be a general object-oriented notation and not specific to any
one language. Thus, the notation won’t be the same as programming method
notation.
The method called findAboveHours (int hours): studentArray, which is
denoted with an underline in Figure 12-4, is a special kind of method. Remem-
ber that in the object-oriented approach, a class is a template to create individual
objects or instances. Most of the methods apply to one instance of the class.
However, analysts frequently need a method to look through all the instances
class-level method a method that is at once. Such a method is called a class-level method and is denoted by
associated with a class instead of with an underline.
objects of the class
In Chapter 4, you learned about generalization/specialization. In the prob-
lem domain model, generalization/specialization becomes inheritance in the
design model and in a programming language. Figure 12-11 shows an example

Figure 12-11 Sale superclass (abstract) with three concrete subclasses showing inheritance

Sale Customer

-saleID: int {key} -accountNo: string {key}


-saleDate: date -name: string
-priorityCode; string -mobilePhone: string
-shipping&Handling: currency -homePhone: string
-tax: float -emailAddress: string
-grandTotal: currency 0..* 1..1 -status: string

+addItem (itemUPCCode) +updateName (name)


+cancelSale (saleID) +updateAddress (address)
+makePayment(amount) +createSale (accountNo)

TelephoneSale::Sale OnlineSale::Sale InStoreSale::Sale


-clerkID: string -URLaddress: string -storeID: string
-lengthOfCall: string -timeOfDay: string -registerID: string
-noOfPhoneSales: int -timeToOrder: int -clerkID: string
© Cengage Learning ®

-noOfWebSales: int -noOfStoreSales: int

+confirmEmail (emailAddress)

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 12 ■ Object-Oriented Design: Fundamentals 379

of design classes with attributes and methods; it shows how inheritance works
for design classes. Each of the three subclasses inherits all the attributes and
methods of the parent Sale class. Hence, each subclass has a saleID, a saleDate,
and so forth. In this example, each subclass also has additional attributes that
are unique to its own specific class. Each of the subclasses also has a unique
attribute that is underlined, such as noOfPhoneSales. As previously mentioned,
class-level attribute an attribute that underlined attributes are class-level attributes and have the same characteris-
contains the same value for all objects in the tics as class-level methods. A class-level attribute is a static variable, and it con-
system tains the same value in all instantiated objects of the same type.
Not only are methods and attributes inherited by the subclasses, but asso-
ciations are also inherited. In Figure 12-11, the Sale object must be associated
with exactly one customer. Each subclass inherits the same association; it must
be associated with exactly one customer. Finally, notice that the title of the Sale
class is italicized. As defined in Chapter 4, an italicized class name indicates that
it is an abstract class—a class that can never be instantiated. In other words,
there are never any Sale class objects. All orders in the system must be instanti-
ated as one of the three subclasses, which are concrete classes, meaning that
every order in the system will be either a TelephoneSale, an OnlineSale, or an
InStoreSale. The purpose of an abstract class is illustrated by the figure. It pro-
vides a central holding place for all the attributes and methods that each of the
three subclasses will need. This example demonstrates one way that OOP imple-
ments reuse. The methods and attributes in the abstract superclass only need to
be written once in order to be reused by each of the subclasses.

■■ Developing the First-Cut Design Class Diagram


To illustrate how to start the design process, this section develops a first-cut
design class diagram based on the domain model. Figure 12-12 is a partial
RMO domain model class diagram, as developed in Chapter 4.

Figure 12-12 Partial RMO Sales


subsystem domain model class Promotion
diagram season
year
description
startDate
endDate PromoOffering
price
specialPrice
1..*
Customer
0..* accountNo {key}
name
ProductItem SaleTrans
mobilePhone
productID {key} date homePhone
vendor transactionType emailAddress
gender amount status
description paymentMethod
1..*
1
1

0..* 0..*
InventoryItem Sale
inventoryID {key} SaleItem
size quantity 1 saleID {key}
0..* saleDate
color price
© Cengage Learning ®

1 priorityCode
options backorderStatus 1..* shipping&Handling
quantityOnHand 1 tax
averageCost grandTotal
reorderQuantity

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
380 PART 5 ■ Advanced Design and Deployment Concepts

The first-cut design class diagram is developed by extending the domain


model class diagram. It requires two steps: (1) adding type and initial value
information to the attributes and (2) adding navigation visibility arrows. As
indicated earlier, object-oriented design is use-case-driven; so, let’s choose a use
case to start with and focus only on classes involved in that use case.

❚❚ Elaboration of Attributes
The elaboration of the attributes is fairly straightforward. The type information
is determined by the designer, based on his or her expertise. In most instances,
all attributes are kept invisible or private and are indicated with minus signs
before them. We also need to add a new compartment to each class for the addi-
tion of method signatures.

❚❚ Navigation Visibility
As stated earlier, an object-oriented system is a set of interacting objects. The
sequence diagrams document which interactions occur between which objects.
However, for one object to interact with another, the first object must be vis-
navigation visibility a design principle in ible to the second object. In this context, navigation visibility refers to the
which one object has a reference to another ability of one object to interact with and send messages to another object.
object and thus can interact with it ­S ometimes, developers refer to navigation visibility as just navigation or vis-
ibility. However, using just the term visibility can cause confusion with attri-
bute or method visibility. We will use either the term navigation visibility or
navigation to distinguish the concept from public and private visibility on
attributes and methods.
Figure 12-13 shows one-way navigation visibility between the Customer
class and the Sale class. It is called “one-way” because Customer can interact
with Sale, but Sale does not have a direct reference back to Customer. The navi-
gation arrow indicates that a Sale object must be visible to the Customer object.
Notice the variable called mySale in the Customer class. This variable refers to a
Sale instance. The mySale attribute is included in the example to provide a way
to actually implement it. This is quite different from the database concept of
including a foreign key. The mySale attribute is not the value of the key to a Sale
object, but it is an actual programming reference to the Sale object. You could
even think of it as having a Sale object embedded within the Customer object.
From a database point of view, you would do exactly the reverse. You would put
a foreign key of the Customer in the Sale data record to capture the one-to-many
relationship. (One customer has many sales.)
Now let’s think about adding navigation visibility to the RMO design class
diagram. Remember that you are designing just the first-cut class diagram, so
you might continue to modify the navigation arrows as the design progresses.

Figure 12-13 Navigation visibility


between Customer and Sale
Customer Sale
-accountNo: string {key} -saleID: int {key}
-name: string -saleDate: date
-mobilePhone: string -priorityCode: string
-homePhone: string -shipping&Handling: currency
-status: string -tax: currency
-mySale: Sale -totalAmt: currency
© Cengage Learning ®

-mountainBucks: int

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 12 ■ Object-Oriented Design: Fundamentals 381

You should ask the following basic question when building navigation visibil-
ity: Which classes need to have references to or be able to access which other
classes? Here are a few general guidelines:
■■ One-to-many associations that indicate a superior/subordinate relationship are
usually navigated from the superior to the subordinate—for example, from
Sale to SaleItem. Sometimes, these relationships form hierarchies of navigation
chains—for example, from Promotion to ProductItem to InventoryItem.
■■ Mandatory associations, where objects in one class can’t exist without
objects of another class, are usually navigated from the independent class to
the dependent class—for example, from Customer to Sale.
■■ When an object needs information from another object, a navigation arrow
might be required, pointing either to the object itself or to its parent in a
hierarchy.
■■ Navigation visibility arrows may be bidirectional—for example, a Sale
object might need to send a message to its Customer object as well as
the reverse.
The very first step you do when creating the first-cut design class diagram
is to add a controller class. You will learn more about controller classes in the
next chapter. Basically, the controller class is a switchboard between the input
screens and the programming logic classes, i.e. the domain classes, for a par-
ticular use case. In our examples, we will always create a controller class for
each use case, and place it between the user-interface classes and the problem
domain classes.
Figure 12-14 is a first-cut design class diagram for the use case Create tele-
phone sale based on the steps described earlier: add a controller class, elaborate
attributes, and identify navigation visibility. To elaborate the attributes, you add
type information and visibility. To add navigation visibility, you first identify
which classes may be involved and then determine the classes that require navi-
gation visibility to other classes. For example, for the Create telephone sale use
case, price information is in the PromoOffering class and description informa-
tion is in the ProductItem class. In most instances, it is unnecessary to put the
navigation visibility reference attribute in the class. (And, in fact, there are some
languages that do not require it.) In other words, the mySale attribute is redun-
dant to the information provided by the arrow. So, even though it was shown
in Figure 12-13 to emphasize the concept of navigation visibility, it is left off in
Figure 12-14 and subsequent figures.
As a reminder, one thing to remember about navigation visibility is that the
classes are programming classes, not database classes. So, we aren’t thinking
about foreign keys in a relational database. We are thinking about object refer-
ences in a programming language.
Figure 12-14 includes SaleHandler as the controller class. As mentioned pre-
viously, a controller class, or use case controller, is a utility class that helps in the
processing of a use case. Notice that it has navigation visibility at the top of the
visibility hierarchy and starts the use case by messaging a customer.
Three points are important to note: First, as design proceeds use case by use
case, you need to ensure that the sequence diagrams support and implement the
navigation visibility that was initially defined. Second, the navigation arrows
need to be updated as design progresses to be consistent with the design details.
Finally, method signatures will be added to each class based on the design deci-
sions made when creating the interaction diagrams for the use cases.
As discussed earlier and shown in Figure 12-8, for use cases that are simple,
a developer will often use CRC cards to design the detail flow of execution for
the use case from one class to another. The next section explains how CRC
cards can be used to design a use case.

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
382 PART 5 ■ Advanced Design and Deployment Concepts

Figure 12-14 First-cut RMO design class diagram for the Create telephone sale use case

SaleTransaction
«controller»
SaleHandler -transactionID: int {key}
-saleDate: date
-transactionType: string
-amount: currency
-payMethod: string

Customer Sale SaleItem


-accountNo: string {key} -saleID: int {key} -saleItemID: int {key}
-name: string -saleDate: date -quantity: int
-mobilePhone: string -priorityCode: string -soldPrice: currency
-homePhone: string -shipping&Handling: currency -shipStatus: string
-status: string -tax: currency -backOrderStatus: string
-totalAmt: currency
-mountainBucks: int

PromoOffering ProductItem InventoryItem

-PromoNo: string -productID: string {key} -inventoryID: string {key}


-ProductID: string -gender: string -size: string
-promoPrice: currency -description: string -color: string
-supplier: string -options: string
-manufacturer: string -quantityOnHand: int

© Cengage Learning ®
-regularPrice: currency -averageCost: currency
-picture: blob -reorderQuantity: int

■■ Designing with CRC Cards


CRC cards a brainstorming and design CRC (class responsibility collaboration) cards are a brainstorming and
technique for designing interactions in use design technique that is quite popular among object-oriented developers. Devel-
cases by assigning responsibilities and opers use this technique during design to help identify responsibilities of the
collaborations for classes
class and the sets of classes that collaborate for a particular use case.
A CRC card is simply a 3 3 5 or 4 3 6 index card with lines that par-
tition it into three areas: class name, responsibility, and collaboration classes.
­Figure 12-15 illustrates the two sides of a CRC card from the RMO CSMS. The
card is partially filled out. Along the top of the card is the name of the class. The
left partition lists the responsibilities for objects in this class. Responsibilities
include information that the class maintains and actions that the class carries
out in support of a particular use case. The right partition lists other classes
with which this class collaborates in support of a particular use case. On the
back of the card, you have the option of listing important attributes that are
required for particular use cases.
The process of developing a CRC model is usually done in a brainstorm-
ing session. A design session using CRC cards already has substantial informa-
tion from which to begin. Before starting the design session, each team member
should have a copy of the domain model class diagram. The use case diagram or
list of use cases also needs to be available. Other detailed information, such as

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 12 ■ Object-Oriented Design: Fundamentals 383

Figure 12-15 Sample CRC card (front and back)

Class name Collaborating classes Attributes

Responsibilities
Customer
accountNo
update name Sale customerName
update address Payment mobilePhone
request purchase history homePhone
status
process sale

© Cengage Learning ®
make payment

Front of card Back of card

activity diagrams, system sequence diagrams, and use case descriptions, should
be provided, along with a stack of blank CRC-formatted index cards.
For each use case that needs to be designed, these steps are repeated:

1. Select a use case. Because the process is to design a single use case, start
with a set of unused CRC cards. The first card to include should be a use
case controller card.
2. Identify the first problem domain class that has responsibility for this use
case. This object will receive the first message from the use case control-
ler. Using the domain model that was developed during analysis, select one
class to take responsibility. Focus only on the problem domain classes. On
the left side of the card, write the object’s responsibility. For example, a
Customer object may take responsibility to make a new sale, so one respon-
sibility may be Create phone sale.
3. Identify other classes that must collaborate with the primary class to com-
plete the use case. In other words, identify the classes that have required
information or that need to be updated in this use case. As you identify a
collaborating class, go to the appropriate CRC card for that class and write
its responsibilities on the cards. Also, on the back of each card, write the
pertinent information about required attributes of each object class.
4. Another helpful step is to include the user-interface classes. If a user is
part of the team and if some preliminary work has been done on the user-
interface requirements, it could be effective to add CRC cards for all user-
interface window classes that are required for the use case. By including
user-interface classes, all the input and output forms can be included in the
design, making it much more complete.
5. Add any other required utility classes that are needed to the solution. For
example, for a three-layer design, data access classes will be part of the
solution. Usually, each persistent domain class will have a data access class
to read and write to the database.

At the end of this process, you will have a small set of CRC cards that col-
laborate to support the use case. This process can be enhanced with several
other activities. First, the CRC cards can be arranged on the table in the order
they are executed or called. In other words, the calling order can be determined
at this time.
To begin, let’s work through a simple use case. Referring back to
­Figure 12-8, we first choose a use case. Next, we create the first-cut design class
diagram with navigation. In Chapter 5, we identified a simple use case called

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
384 PART 5 ■ Advanced Design and Deployment Concepts

Figure 12-16 First-cut design


class diagram for Create
Customer Account
customer account use case
-accountNo: string {key} -accountNo: string {key}
«controller» -name: string -typeOfAccount: string
CustomerHandler -mobilePhone: string -creditCardNo: int
-homePhone: string -creditCardDate: date
-status: string

Address
-accountNo: string {key}
-typeOfAddress: string
-number: string
-street: string
-city: string
-state: string
-postalCode: string

Create customer account. Figure 12-16 is the first-cut design class diagram,
with navigation visibility added. (Remember that this is simply a preliminary
assessment at navigation visibility; it may change as we proceed with the design.)
To create this, we first looked at all those domain classes that had associa-
tion relationships with the Customer class (see Figure 4-24), and selected those
that might be created or updated with this use case. For this use case, we only
selected the Account class and the Address class.
To learn how the CRC cards process works, let’s go through each step
listed above and develop the necessary CRC cards. We will use many other
requirements models that were created in previous chapters for this use case.
In Chapter 5, you saw an activity diagram (refer back to Figure 5-4) and a
system sequence diagram (refer back to Figure 5-10), which document the
results of analysis activities to determine requirements. That information will
also help define the responsibilities of the object classes. So the analysis mod-
els identify what needs to be done, but during design we may make changes
as we implement how to do it. Remember, however, that during design we
may need to make changes based on good design principles and programming
techniques.
1. We have selected the use case Create Customer Account. At this point, we
will call the controller card, CustomerHandler. Figure 12-17 illustrates this
card. The only responsibility that we have identified so far is a method to
create a new Customer object.

Figure 12-17 CRC card for


CustomerHandler CustomerHandler
create Customer Customer

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 12 ■ Object-Oriented Design: Fundamentals 385

Figure 12-18 CRC cards for


controller and Customer CustomerHandler Customer
create Customer Customer

2. The primary class responsible for creating a new customer account could
be the Customer class, so we will add a CRC card for Customer. It makes
sense that a Customer class takes responsibility for creating and updat-
ing anything having to do with customer details such as accounts and
addresses. The Customer class also has the responsibility to instantiate a
new object with a constructor method. Some developers like to include
constructor responsibilities, while others do not. In our example, we will
not include the constructor. The programmers will know that every class
requires at least one constructor. The input information for the constructor
can be found in the SSD, as shown in Figure 5-10. Figure 12-18 illustrates
the completion of step 2.
3. For the third step, we observe from Figure 5-4 and Figure 5-10 that there
are two other messages coming into the system. One message passes
address data and another message passes credit card information. Also
note in Figure 12-16 that there are two other classes involved in this use
case, Address and Account. When creating a new customer, the system
also needs to instantiate a new Account object, and at least one new
Address object, though there may also be multiple address objects created.
­Figure 12-19 illustrates the completion of step 3, except for the attributes,
which are not being shown in this example.
4. For the fourth step, we will add the user-interface classes. Input to this
design step will come from two sources, the parameters on the messages
as seen in Figure 5-10, and the screen designs and layouts designed during
input design. In this instance, let’s assume that the user requirement is to
have a starting screen that captures basic information such as name, phone
numbers, and e-mail addresses. A second input screen will allow enter-
ing address information, multiple times if necessary. A final input screen
will accept credit card information. Because there may be extra processing
required to verify credit information at that point, the user wanted to have
it on a separate input screen. Figure 12-20 illustrates this step in the CRC
design process.
5. For the fifth and final step, we add three more CRC cards for the data-
base access classes—one for each of Customer, Address, and Account.

Figure 12-19 CRC cards for the problem domain classes

Address

CustomerHandler Customer
create Customer Customer create Address Address
create Account Account
Account

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
386 PART 5 ■ Advanced Design and Deployment Concepts

Figure 12-20 CRC cards for Create customer account with input classes identified

CustomerScreen
accept customer info CustomerHandler

Address

AddressScreen CustomerHandler Customer


accept address info CustomerHandler create Customer Customer create Address Address
create Address create Account Account
create Account
Account

CreditcardScreen
accept CC info CustomerHandler

These three CRC cards are labeled CustomerDB, AddressDB, and


AccountDB. We would also need to add collaboration information on
the Customer, Address, and Account cards for these three additional
classes. Each of these three new cards will have responsibilities to update
the appropriate tables in the database. Figure 12-21 illustrates this final
set of CRC cards.
Referring back to our process as described in Figure 12-8, let’s update the
design class diagram with information from the last set of CRC cards. We ini-
tially showed navigation visibility from the controller to Customer, and from
Customer to Account and Address. The CRC cards and the decisions we made
when creating them confirms our initial assumptions. We could include all the
classes, i.e. the user-interface classes and the data access classes, if we so desired;
however, for this example we will only include the domain classes and the con-
troller class. To define complete method signatures, we will use the CRC cards

Figure 12-21 CRC cards for Create customer account with DB classes

AddressDB
write Address

CustomerScreen
accept customer info CustomerHandler

Address
AddressDB

AddressScreen CustomerHandler Customer


accept address info CustomerHandler create Customer Customer create Address Address
create Address create Account Account
create Account CustomerDB Account
AccountDB

CreditcardScreen CustomerDB
write Customer
accept CC info CustomerHandler
AddressDB
write Account

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 12 ■ Object-Oriented Design: Fundamentals 387

Figure 12-22 DCD with method signatures added from CRC cards

«controller»
Customer
CustomerHandler

-accountNo: string {key}


-name: string
-mobilePhone: string
+createCustomer (name, mobilePhone, homePhone) -homePhone: string
+createAddress (type, street, city, state, pcode) -status: string
+createAccount (type, ccNo, ccDate)
+createAddress (no, type, street, city, state, pcode)
+createAccount (no, type, ccNo, ccDate)

Address Account

-accountNo: string {key} -accountNo: string {key}


-typeOfAddress: string -typeOfAccount: string
-number: string -creditCardNo: int
-street: string -creditCardDate: date
-city: string
-state: string
-postalCode: string

and information from the system sequence diagram (SSD). The methods in the
design class diagram are derived from the lists of responsibilities on each card.
In other words, each responsibility should translate to a method. The CRC cards
identify responsibilities, but do not normally include the complete method sig-
natures with parameters and returns. Not having to worry about parameters
simplifies the CRC card process, but it requires that the developer add that
information when the design class diagram is completed. Also, because we have
elected not to include the constructor responsibilities on CRC cards, we have
not included the constructor methods on the final design class diagram. So even
though there are no methods defined for Address or Account, we know that
there are constructor methods that execute when new objects are instantiated. If
we were to define multiple constructor methods with different parameters and
returns, we could add them to this final version of the design class diagram.
Figure 12-22 shows the updated design class diagram of the domain layer with
method signatures added for this use case.
Let’s show one more example. Figure 12-14, which we developed to illus-
trate design class diagram elements, contains the first-cut design class diagram
for the RMO use case Create telephone sale. We will complete this example and
show the set of CRC cards and the final design class diagram.
For this example, it makes sense that the Customer object creates a Sale
object, the Sale object creates SaleItem objects, and SaleItem objects access Pro-
ductItem, InventoryItem, and PromoOffering objects to get required informa-
tion. We had determined this when we created the first-cut design class diagram
in Figure 12-14. Figure 12-23 illustrates a solution set of CRC cards for the use
case Create telephone sale. The process payment responsibility in the Sale class
will cause a SaleTransaction to be created.
To finish the example, let us go back to the design class diagram and update
it based on the design information created during the CRC card brainstorming

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
388 PART 5 ■ Advanced Design and Deployment Concepts

Figure 12-23 CRC cards model for Create telephone sale use case

Sale PromoOffering
add/delete item SaleItem provide price
process payment SaleTransaction

NewSaleWindow
accept input SaleHandler SaleHandler
display results
accept payment start new sale Customer
accept item request Sale SaleItem ProductItem
accept payment
delete item PromoOffering provide description
request backorder ProductItem
Inquire-addItemWindow InventoryItem

accept item-data SaleHandler


Customer
display item info process new sale Sale

SaleTransaction InventoryItem

© Cengage Learning ®
provide quantity
update quantity
order new supply

session. Figure 12-24 shows an updated design class diagram, with methods
navigation visibility updates added. Note that the SaleHandler class needs vis-
ibility to the Sale class to process a payment. Compare the responsibilities iden-
tified on the CRC cards and the method names described in each class. Note the
close correlation. Also remember that we have not included constructors. So for
example, the SaleTransaction has a constructor method, which is not shown, to
process the payment by instantiating a new SaleTransaction object.
Often, when developers begin using CRC cards, they assign many different
responsibilities for a given class. For example, developers might say the SaleItem
class should get the price. In reality, the PromoOffering class provides the price
and the SaleItem only uses it. In other words, it helps to think of responsibili-
ties as being similar to methods—requests to do something rather than random
actions that need to occur.
As method names and navigation visibility are added to the design class
diagram for each use case, the overall diagram grows and becomes the central
repository of all information about every class in the new system. Each set of
CRC cards, or interaction diagrams as shown in the next chapter, can be used
for programming the new system. The overall design class diagram becomes a
source for verification that all use cases have been programmed completely and
accurately.
Now that you have some idea of the design process, let’s go back through
and think about what makes a good design.

■■ Fundamental Principles for Good Design


With something as complex as a software application, there are probably an
infinite number of design and programming solutions that will work. Some solu-
tions will be “good” solutions, while many other solutions would be considered
“bad” solutions. In Online Chapter C, “Project Management Techniques,” the
PMBOK area of Project Quality Management identified several characteristics
of “good” software. Included were several characteristics related to usability of
the software application and fitness for its intended use. Other characteristics
focused on robustness, reliability, and maintainability of the software itself.

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 12 ■ Object-Oriented Design: Fundamentals 389

Figure 12-24 Updated DCD for


Create telephone sale use case «controller» SaleTransaction
SaleHandler
-transactionID: int {key}
-saleDate: date
-transactionType: string
+startNewSale (...)
-amount: currency
+acceptItemRequest (...)
-payMethod: string
+acceptPayment (...)

Customer Sale SaleItem


-accountNo: string {key} -saleID: int {key} -saleItemID: int {key}
-name: string -saleDate: date -quantity: int
-mobilePhone: string -priorityCode: string -soldPrice: currency
-homePhone: string -shipping&Handling: currency -shipStatus: string
-status: string -tax: currency -backOrderStatus: string
-totalAmt: currency
-mountainBucks: int

+processNewSale (...) +addItem (...) +deleteltem (...)


+deleteItem (...) +requestBackorder (...)
+processPayment (...)

PromoOffering ProductItem InventoryItem


-promoNo: string -productID: string {key} -inventoryID: string {key}
-productID: string -gender: string -size: string
-promoPrice: currency -description: string -color: string
-supplier: string -options: string
-manufacturer: string -quantityOnHand: int
-regularPrice: currency -averageCost: currency

© Cengage Learning ®
-picture: blob -reorderQuantity: int

+getPrice (...) +getDescription (...) +getQOH (...)


+updateQOH (...)
+orderSupply (...)

These characteristics determine the quality of the design. In other words, they
indicate the “goodness” of the detailed design and the implementation of the
new system. Although understanding and using the following design principles
will not guarantee a high-quality design, applying these principles will increase
the probability that the design is solid. Ignoring the following principles will
almost certainly ensure a less-than-optimal software design.
The following discussion of good design principles is a launching point for
you to understand how to design high-quality software. However, it is not a
comprehensive discussion. There are many good books and articles on the prin-
ciples of good object-oriented design, which further explain principles and tech-
niques of good design.

■■ Object Responsibility
One of the most fundamental principles of object-oriented design is the idea of
object responsibility a design principle in object responsibility; that is, objects should be responsible for carrying out
which objects are responsible for carrying out system processing. These responsibilities are categorized in two major areas:
system processing knowing and doing. In other words, what is an object expected to know and
what is an object expected to do or to initiate?

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
390 PART 5 ■ Advanced Design and Deployment Concepts

Knowing includes an object’s responsibilities for knowing about its own


data and knowing about other classes with which it must collaborate to carry
out use cases. Obviously, a class should know about its own data, what attri-
butes exist, and how to maintain the information in those attributes. It should
also know where to go to get information when required. For example, dur-
ing the instantiation of an object, data that aren’t passed as parameters may be
required. An object should know about or have navigation visibility for other
objects that can provide the required information. For example, in Figure 12-2,
the first constructor method for the Student class doesn’t receive a studentID
value as a parameter. Instead, the Student class takes responsibility for creat-
ing a new studentID. It will know how to create a studentID according to an
internal algorithm, such as an “autonumber next higher number” algorithm, or
perhaps a globally unique identifier routine.
Doing includes all the activities an object performs to complete a use case.
Some of those activities include receiving and processing messages. Another
activity is to instantiate, or create, new objects that may be required for comple-
tion of a use case. Classes must collaborate to carry out a use case, and some
classes are responsible for coordinating the collaboration. For example, in the
use case Create phone sale, the Sale class has responsibility to create SaleItem
objects. Another class, such as InventoryItem, is only responsible for provid-
ing information about itself. Good design dictates that the developer pay close
attention to recognizing and assigning responsibilities to the appropriate objects.

■■ Separation of Responsibilities or Separation of Concerns


separation of responsibilities a design Separation of responsibilities, also called separation of concerns, is a design
principle that recommends segregating principle that is applied to a group of classes rather than to each class indi-
classes into separate packages or group- vidually. The basic idea of separation of responsibilities is to segregate classes
ings based on a primary focus of processing
responsibility
into packages or groupings based on a primary focus of processing responsi-
bility. Separation of responsibilities is the fundamental principle behind multi-
layer design. In multilayer design, there are user-interface classes, business logic
classes, and data access classes. Each layer has a particular focus or area of
responsibility. Classes that share the same focus or concern are grouped together
in a layer. This design principle allows flexibility in system deployment because
different layers, i.e., a grouping of classes, can be located on different computers
or at different locations.

■■ Protection from Variations


protection from variations a design Another underlying principle of good design is protection from variations—
principle in which parts of a system that are the principle that the parts of a system that are unlikely to change should be seg-
unlikely to change are segregated from those
regated (or protected) from those that will change. As you design systems, you
that will
should try to isolate the parts that will change from those that are more stable.
Protection from variations is a principle that affects the multilayer design
pattern. Designers could mix all the user-interface logic and business logic
together in the same classes. In fact, in early user-oriented, event-driven sys-
tems, such as those built with early versions of Visual Basic and PowerBuilder,
the business logic was included in the view layer classes—often in the Windows
input forms. Many Web applications also combine HTML and business logic.
The problem with this design was that when an interface needed to be updated,
all the business logic had to be rewritten. A better approach is to decouple
the user-interface logic from the business logic. Then, the user interface can
be rewritten without affecting the business logic. In other words, the business
logic—being more stable—is protected from variations in the user interface.
Also, what if updates to the business logic require the addition of new
classes and new methods? For example, if the user interface is included as part
of the business classes, then changing the business logic would impact the user

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 12 ■ Object-Oriented Design: Fundamentals 391

interface. However, building the system with a use case controller allows the
user interface to simply send all its input messages to the use case controller
class. Thus, changes to the methods or classes in the business logic and domain
layer are isolated to the controller class. You will find that protection from vari-
ations affects almost every design decision, so you should watch for and recog-
nize the application of this principle in all design activities.

■■ Indirection
indirection a design principle in which an Indirection is the principle of separating two classes or other system compo-
intermediate class is placed between two nents by placing an intermediate class between them to serve as a link. In other
classes to decouple them but still link them words, instructions don’t go directly from A to B; they are sent through C first.
Or in message terminology, don’t send a message from A to B. Let A send the
message to C and then let C forward it to B.
Although there are many ways to implement protection from variations,
indirection is frequently used for that purpose. Inserting an intermediate object
allows any variation in one system to be isolated in that intermediate object.
Indirection is also useful for many corporate security systems. For example,
many companies have firewalls and proxy servers that receive and send mes-
sages between an internal network and the Internet. A proxy server appears as a
real server—ready to receive such messages as e-mail and HTML page requests.
However, it is a fake server, which catches all the messages and redistributes
them to the recipients. This indirection step allows security controls to be put in
place and protect the system.
A common example of indirection that we have been using throughout is the
insertion of a use case controller. The controller is a separate class that receives
all the inputs and directs it to the appropriate domain classes.

■■ Coupling
This principle, coupling, and the next principle, cohesion, were originally
defined during the early days of software design and programming. However,
both principles continue to be extremely important and applicable to object-
oriented design.
In the previous examples throughout the text of the RMO class diagram,
you have seen that the Customer class and the Sale class are linked together in
coupling a qualitative measure of how an association relationship. Another term for this linking is coupled. Coupling
closely the classes in a design class diagram is a qualitative measure of how closely the classes in a design class diagram are
are linked linked. A simple way to think about coupling is by the number of association
relationships and whole/part relationships on the design class diagram. Previ-
ously, you learned about navigation visibility, which measures what a class can
link to and access. Low coupling is usually better for a system than high cou-
pling. For example, a Customer object can access a Sale object that belongs to
it. However, if it can also directly access the SaleItem, that would be too much
coupling. Only the Sale object should be able to access its own SaleItem objects.
We say that coupling is a qualitative measure because no specific number
measures coupling in a system. It is a global measure that applies to a set of
classes for a particular use case design. It does not measure an individual class.
A designer must develop a feel for coupling—that is, recognize when there is too
much or too little. Coupling is evaluated as a design progresses—use case by use
case. Generally, if each use case design has a reasonable level of coupling, the
entire system will too.
Refer back to Figure 12-1 to observe the flow of messages between the
objects. Obviously, objects that send messages to each other must have visibility
and thus are coupled. For the Input window object to send a message to the Stu-
dent object, it must have visibility, or be coupled, to it. The Input window object
isn’t connected to the Database access object, so those objects aren’t coupled.

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
392 PART 5 ■ Advanced Design and Deployment Concepts

If we designed the system so the Input window object accessed the Database
access object, the overall coupling for this use case would increase; that is, there
would be more connections. Is that good or bad? In this simple example, it
might not be a problem. But for a system with 10 or more classes, too many
connections with visibility can cause high levels of coupling, making the system
more complex and therefore harder to maintain.
So, why is high coupling bad? The main reason is that a change in one class
ripples through the entire system and may cause methods to fail. Therefore,
experienced analysts make every effort to simplify coupling and reduce ripple
effects in the design of a new system.

■■ Cohesion
cohesion a qualitative measure of the Cohesion refers to the consistency of the functions within a single class and is a
focus or unity of purpose within a single class qualitative measure of its focus or unity of purpose. Unlike coupling (where you
want low coupling), classes need to be highly cohesive to be well designed. For
example, in Figure 12-1, you would expect the Student class to have methods—
that is, functions—to enter student information, such as identification number
or name. That would represent a unity of purpose and a highly cohesive class.
But what if that same object also had methods to make classroom assignments
or assign professors to courses? The cohesiveness of the class would be reduced.
Classes with low cohesion have several negative effects. First, they are hard
to maintain. Because they perform many different functions, they tend to be
overly sensitive to changes within the system, suffering from ripple effects.
­S econd, it is hard to reuse such classes because they have many different—and
often unrelated—functions. For example, a button class that processes button
clicks can easily be reused. However, a button class that processes both button
clicks and user log-ins has limited reusability. A final drawback is that classes
with low cohesion are usually difficult to understand. Frequently, their func-
tions are intertwined and their logic is complex.
Although there is no firm metric to measure cohesiveness, we can think
about classes as having very low, low, medium, or high cohesion. Remember,
high cohesion is the most desirable. An example of very low cohesion is a class
that has responsibility for services in different functional areas, such as a class
that accesses both the Internet and a database. These two types of activities are
different and accomplish different purposes. To put them together in one class
causes very low cohesion.
An example of low cohesion is a class that has different responsibilities, but
in related functional areas—for example, a class that handles all database access
for every table in the database. It would be better to have different classes to
access customer information, order information, and inventory information.
Although the functions are the same—that is, they access the database—the
types of data passed and retrieved are very different. Thus, a class that is con-
nected to the entire database isn’t as reusable as one that is only connected to the
Customer table.
An example of medium cohesion is a class that has closely related responsi-
bilities, such as a single class that maintains customer information and customer
account information. A better design would be to define two highly cohesive
classes: One class could be defined for customer information, such as names
and addresses, and another class or set of classes could be defined for customer
accounts, such as balances, payments, credit information, and all financial activ-
ity. If the customer information and the account information are limited, they
could be combined into a single class with medium cohesiveness. Either medium
or highly cohesive classes can be acceptable in systems design.
Now let’s begin the detailed design process by investigating the properties
and details of the design class diagram.

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 12 ■ Object-Oriented Design: Fundamentals 393

Chapter Summary
The ultimate responsibility of system developers is to is refined and expanded as the sequence diagrams are
write computer software that solves a business prob- developed. One method of determining which objects
lem. This chapter focuses on how to configure and collaborate is to use class responsibility collaboration
develop the solution system—that is, how to design (CRC) cards. For simple use cases, a set of CRC cards
the details of the new system. Systems design is the may be sufficient to write code. For more complex use
bridge that puts business requirements in terms that cases, other interaction diagrams are normally used.
the programmers can use to write the software that One reason that we suggest a more formal system
becomes the solution system. of design, rather than just starting to write code is
Using all the requirements models as well as the that the final system is much more robust and main-
architectural design, object-oriented design extends tainable. Design as a rigorous activity builds better
the models so programming can proceed. The objec- systems. Some fundamental principles should be con-
tive of object-oriented design is to determine the sidered as a system is developed; specifically, two criti-
methods within individual classes that are needed to cal ideas are coupling and cohesion. A good system
implement the use cases. The process of design is use- has low coupling between the classes, and each of the
case-driven, in that it is done one use case at a time. classes has high cohesion. Another important principle
The process of object-oriented design can be is “protection from variations,” meaning that some
divided into two major areas: developing a design class parts of the system should be protected from and not
diagram (DCD) and identifying the methods for each tightly coupled to other parts of the system that are
use case via an interaction diagram. The DCD is usu- less stable and subject to change. Being a good devel-
ally developed in two steps. A first-cut DCD is created oper entails learning and following the principles of
based on the domain model class diagram, but then it good design.

Key Terms
boundary or view class data access class object responsibility
class-level attribute entity class persistent class
class-level method indirection protection from variations
cohesion instantiation separation of responsibilities
controller class method signature stereotype
coupling navigation visibility visibility
CRC (class responsibility object-oriented design
collaboration) cards

Review Questions
1. Describe in your own words how an object-­ 7. What do we mean by use-case-driven design?
oriented program works. 8. Explain in your own words what coupling means
2. What is instantiation? and why it is important.
3. List the models that are used for object-oriented 9. Explain what cohesion means and why it is
systems design. important.
4. Explain how domain classes are different from 10. Compare and contrast the ideas of coupling and
design classes. cohesion.
5. What is the difference between a system sequence 11. What is protection from variations, and why is it
diagram and a sequence diagram? important in detailed design?
6. In your own words, list the flow of steps for doing 12. What is meant by object responsibility, and why is
object-oriented design. it important in detailed design?
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
394 PART 5 ■ Advanced Design and Deployment Concepts

13. What is meant by separation of responsibilities? 18. What information is added to the domain model
14. What are (a) persistent classes, (b) entity classes, to derive the first-cut DCD?
(c) boundary classes, (d) controller classes, and 19. Describe navigation visibility. Why is it ­important
(e) data access classes? in detailed design?
15. What are class-level methods and class-level 20. List some typical conditions that dictate in which
attributes? direction navigation visibility occurs.
16. What is a method signature? 21. What information is maintained on CRC cards?
17. Compare and contrast abstract and concrete 22. What is the objective of a CRC card design session?
classes. Give an example of each. 23. How are CRC cards used to update the DCD?

Problems and Exercises


1. In this chapter, we developed a first-cut DCD, view layer classes, the domain layer classes, and
a set of CRC cards, and a final DCD for the the data access layer classes?
Create customer account use case for RMO. 5. Pick an OOP language with which you are famil-
Create the same three drawings for the Ship iar. Find a programming IDE tool that supports
items use case. (Hint: Figure 5-3 contains a use that language. Test its reverse-engineering capa-
case description.) bilities to generate UML class diagrams from
2. Find a company that does object-oriented existing code. Evaluate how well it does and how
design using CRC cards. The information easy the models are to use. Can it input UML
systems unit at your university often uses diagrams and generate skeletal class definitions?
object-oriented techniques. Sit in on a CRC Write a report on how it works and what UML
design brainstorming session. Interview some models it can generate.
of the developers about their feelings regarding 6. Draw a UML design class that shows the follow-
the effectiveness of doing CRC design. Find out ing information:
what documentation remains after the sessions The class name is Boat, and it is a concrete
and how it is used. entity class. All three attributes are private
3. Find a system that was developed by using Java. strings with initial null values. The attribute
If possible, find one that has an Internet user boat identifier has the property of “key.” The
interface and a network-based user interface. Is other attributes are the manufacturer of the
it multilayered—three layers or two layers? Can boat and the model of the boat. There is also
you identify the view layer classes, the domain an integer class-level attribute containing the
layer classes, and the data access layer classes? total count of all boat objects that have been in-
4. Find a system that was developed by using Visual stantiated. Boat methods include creating a new
Studio .NET (Visual Basic or C#). If possible, instance; updating the manufacturer; updating
find one that has an Internet user interface and a the model; and getting the boat identifier, manu-
network-based user interface. Is it multilayered? facturer, and model year. There is a class-level
Where is the business logic? Can you identify the method for getting the count of all boats.

Case Study
The State Patrol Ticket-Processing 1. Draw a DCD for the ticket-processing system based
on the four classes just listed and include attributes,
System (Revisited) association, and multiplicity.
In Chapter 3, you identified use cases and considered the 2. List the classes that would be involved in the use
domain classes for the State Patrol ticket-processing sys- cases and decide which class should be responsible
tem. Review the descriptions in that chapter for the use for collaborating with the other classes for the use
case Record a traffic ticket. Recall that the domain classes case Record a t­ raffic ticket. Consider some possibili-
included Driver, Officer, Ticket, and Court. ties: (1) A Driver object should be responsible for

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 12 ■ Object-Oriented Design: Fundamentals 395

recording his/her ticket, (2) the Officer object should 3. Create a set of CRC cards showing these classes,
be responsible for recording the ticket that he or she responsibilities, and collaborations for the use case.
writes, and (3) a Ticket object should be responsible 4. Draw a DCD based on your CRC cards. Include method
for recording itself. names.

Running Case Studies


Community Board of Realtors®
In Chapter 3 and Chapter 5, you identified and then listing use case. Recall that creating a new list-
modeled use cases for the Multiple Listing Service ing involves an agent, a real estate office, and
(MLS) application. You also identified and modeled a listing. Decide which class should have the
domain classes. Use your solutions from these chapters primary responsibility for collaborating with
to do the following: the other classes and then complete the CRC
cards for the use case.
1. Draw a first-cut design class diagram (DCD) based
on the domain classes for the Create new listing 3. Update the design class diagram with method
use case. names from the CRC cards. For this solution,
do not try to determine entire method signa-
2. Use the CRC cards technique to verify the
tures, just the names.
classes that are involved in the Create new

The Spring Breaks ‘R’ Us Travel Service


In Chapter 3, you identified use cases for the Spring reservation use case. Recall that creating a
Breaks ‘R’ Us Travel Service. In Chapter 4, you iden- booking involves at least a student group, a
tified the classes associated with these use cases. In resort, a week, and a room type. Decide which
Chapter 5, you elaborated those use cases. Using your class should have the primary responsibility for
solutions from these chapters, do the following: collaborating with the other classes and then
complete the CRC cards for the use case.
1. Draw a first-cut design class diagram (DCD) for
the Book a reservation use case. 3. Update the design class diagram with method
names from the CRC cards. For this solution, do
2. Use the CRC cards technique to verify
not try to determine entire method signatures,
the classes that are involved in the Book a
just the names.

On the Spot Courier Services


In Chapter 6, you considered the issues relevant to the the attributes and show navigation visibil-
specification of the hardware equipment and network- ity. You may also need to add more classes
ing requirements. The case description in Chapter 6 from your solution in Chapter 4. It isn’t
also reviewed the three primary types of users for the uncommon for developers to enhance early
system and many of their respective system-supported models as they begin to ­u nderstand system
activities. requirements better. The CRC cards should
In Chapter 5, you developed activity diagrams and include classes for the controller class and
system sequence diagrams for two use cases: Request a any classes for screens you identified in
package pickup and Pickup a package. In Chapter 4, you Chapter 7.
developed a domain model class diagram for the system. 2. Update the DCD with method names from
1. For each of the two use cases, develop a the CRC cards. For this solution, do not try
first-cut DCD and a set of CRC cards. to determine entire method signatures, just
The design class diagram should elaborate the names.

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
396 PART 5 ■ Advanced Design and Deployment Concepts

Figure 12-25 Use cases for the patient and physician actors

View/respond View/respond
to alert. to alert.

View history.

Patient Physician
Set alert
Annotate history.
conditions.

Send message Send message


to physician. to patient.

© Cengage Learning ®
View/hear View/hear
message from message from
physician. patient.

Sandia Medical Devices


Review the original system description in Chapter 2, that an alert will be generated if three or more
additional project information in Chapters 3, 4, 6, 8, consecutive glucose readings are above or below
and 9, and the use case diagram shown in Figure 12-25 those levels. Expand the domain class diagram in
to refamiliarize yourself with the proposed system. Chapter 4 to include this information and then
Complete these tasks: develop a first-cut design class diagram to sup-
port the patient use case View/respond to alert.
1. For the moment, assume that the database
will store two glucose levels for each patient—­ 2. Develop a design solution using CRC cards for
normal minimum and normal maximum—and the View/respond to alert use case.

Further Resource s

Grady Booch, James Rumbaugh, and Ivar Jacobson, Ivar Jacobson, Grady Booch, and James Rumbaugh,
The Unified Modeling Language User Guide. The Unified Software Development Process.
Addison-Wesley, 1999. Addison-Wesley, 1999.
Grady Booch, et al., Object-Oriented Analysis and Philippe Kruchten, The Rational Unified Process, An
Design with Applications (3rd ed.). Addison- Introduction. Addison-Wesley, 2000.
Wesley, 2007. Craig Larman, Applying UML and Patterns: An Intro-
E. Reed Doke, J. W. Satzinger, and S. R. Williams, duction to Object-Oriented Analysis and Design
Object-Oriented Application Development Using and the Unified Process (3rd ed.). ­Prentice Hall,
Java. Course Technology, 2002. 2004.
E. Reed Doke, J. W. Satzinger, and S. R. Williams, Robert Martin C. Agile Software Development,
Object-Oriented Application Development Using Principles, Patterns, and Practices. Prentice Hall,
Microsoft Visual Basic .NET. Course Technology, 2002.
2003. Jeffrey Putz, Maximizing ASP.NET Real World,
Hans-Erik Eriksson, Magnus Penker, Brian Lyons, and Object-Oriented Development. Addison-Wesley,
David Fado, UML 2 Toolkit. John Wiley & Sons, 2004. 2005.
Martin Fowler, UML Distilled: A Brief Guide to the James Rumbaugh, Ivar Jacobson, and Grady Booch,
Standard Object Modeling Language (3rd ed.). The Unified Modeling Language Reference Manual.
Addison-Wesley, 2004. Addison-Wesley, 1999.
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Object-Oriented Design:
Use Case Realization
Chapter Thirteen

Learning Objectives
After reading this chapter, you should be able to:

Explain the different types of objects and


layers in a design
Develop communication diagrams for use
Chapter Outline case realization
Develop sequence diagrams for use case
Object-Oriented Design with Interaction
realization
Diagrams
Develop updated design class diagrams
Use Case Realization with Communication
Diagrams Develop multilayer subsystem packages
Use Case Realization with Sequence Diagrams Explain design patterns and recognize various
specific patterns
Developing a Multilayer Design
Updating and Packaging the Design Classes
Design Patterns

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
398 PART 5 ■ Advanced Design and Deployment Concepts

Opening case N ew Capital Bank: Part 2

The integrated customer account system project for “I really like the approach of first doing a rough de-
New Capital Bank was now two months old. The first sign using CRC cards,” Charlie replied. “It’s nice to have
development iteration had gone pretty well, although a couple of users there with us to verify that our col-
there were a few snags because the team was still learn- laborations are correct. For the simple use cases, we
ing the ins and outs of iterative development projects. can work with the users to lay out the user interface.
Bill Santora, the project leader, was discussing some Between the CRC cards and the user-interface specifi-
of the system’s technical details with Charlie Hensen, cations, we should have enough to program from, espe-
one of his team leaders, in preparation for the iteration cially now that we have the basic structure set up. Then,
retrospective. for the more complex use cases, we can go ahead and
“How is the team feeling about doing detailed do a detailed design with communication diagrams or
­d esign?” Bill asked Charlie, who was one of the early sequence diagrams. The nice thing about these interac-
critics of doing more formal design. “I know some of tion diagrams is that they’re detailed enough for us to
the programmers wanted to just start coding from the hand the designs over to some of the junior program-
use case descriptions that were developed with the mers. It makes them much more effective in their team
users. They weren’t very happy about taking the time to contributions.”
design. Is that still a problem?” “So, would you change our approach or do you think
“It really has worked out quite well,” Charlie said. it’s working the right way?” Bill asked, still looking for
“As you know, I was skeptical at first and thought it ways to improve the process.
would waste a lot of time. Instead, it has allowed us to “Well, it really is working pretty well right now,”
work together better because we know what the other Charlie said. “One thing I really like about it is that we
team members are doing. I also think the system is have a common domain class diagram that everyone
much more solid. We’re all using the same approach, and can access and review. That really helps when you’re
we’ve discovered that there are quite a few classes we ready to insert some code into a class to check and see
share. Of course, we don’t waste a lot of time making what is already there. The central repository for all our
fancy drawings. We do document our designs with tem- code and for the diagrams we do formalize is a great
porary drawings, but that is about as far as we take it.” tool. I wonder if there is a way to get more use out of
“What would you say were the strengths and weak- that tool. Other than that, I would say let’s stick with this
nesses of our approach?” Bill asked, “Or are there ways approach for another iteration and see if it needs chang-
you think we could do it better in this next iteration?” ing after that.”

■■ Overview
In Chapter 12, you learned the objective of object-oriented design and the fun-
damental approach. In Figure 12-3, you learned that design includes informa-
tion about the classes and about the processes. In Figure 12-8, you learned the
approach to (1) select a use case, (2) identify the classes involved and begin the
design class diagram, (3) choose a modeling technique to identify the messages
and methods, and (4) finalize the class methods in the design class diagram.
This chapter pursues object-oriented detailed design in more depth and
formality. This chapter focuses on the foundation principles, which are based
on the concepts of use case realization by using UML interaction diagrams
and design patterns. You will learn how to use communication diagrams and
sequence diagrams to extend the input messages and define internal messages.
These techniques will first focus on the problem domain classes and then extend
to multilayer design.
The last section of this chapter is a brief introduction to design patterns.
As with any engineering discipline, certain procedures have become tried and
proven solutions. Even though object-oriented development is a relatively young
engineering discipline, it offers standard ways to design use cases that lead to
solid, well-constructed solutions. You will learn a few of those standard designs
or patterns.

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 13 ■ Object-Oriented Design: Use Case Realization 399

■■ Object-Oriented Design with Interaction Diagrams


The discussion of CRC cards in Chapter 12 introduced the idea of collaborating
objects to execute various use cases. Design sessions using CRC cards focus on
the problem domain classes and their responsibilities. Even though we did add
multilayer classes to the CRC cards, the actual details of how all the layers and
classes work together was not addressed. Because the CRC card method focuses
on simple use cases, the details of the interactions between classes and layers is
left to the programmer. This chapter describes in depth the detailed design of all
layers of a multilayer system.
In Figure 12-1, there are three objects representing the three layers of a system.
Each object has certain responsibilities. The input window object has the primary
responsibility of formatting and presenting student information on the screen.
The student object represents the middle layer, or business logic layer, for
the use case. This chapter formalizes the process of precisely identifying meth-
ods and defining method signatures, particularly for this layer.
The database access object represents the third layer in the multilayer design.
It is responsible for connecting to the database, reading the student information,
and sending it back to the student object. It is also responsible for writing the
student information back to the database when necessary. This object doesn’t
come from a problem domain class; it is a utility object created by the designer.
Several questions should come to mind as you review a detailed systems design.
First, how do all these objects get created in memory? For example, how and when
does the student object get created? How about the database access object? Other
questions include: Will other objects be necessary? What object represents authen-
tication? What is the life span of each object? Maybe the student object should go
away after the update—but what about the database access object?
use case realization the process The method used to extend the process of detailed design is called use case
of elaborating the detailed design with realization. In use case realization, each use case is taken individually to deter-
interaction diagrams for a particular use case
mine all the classes that collaborate on it. As part of that process, any other util-
ity or support classes are identified. Care is taken during this process to define
the classes so the integrity of the multilayer architectural design is maintained.
As the details of the classes are designed—use case by use case—the design class
diagram is also updated as necessary.
As you saw in Figure 12-8, in addition to CRC cards, there are two other
models that are useful for systems design—communication diagrams and
sequence diagrams. Developing interaction diagrams is at the heart of object-
oriented design. The realization of a use case—determining what objects col-
laborate and the messages they send to each other to carry out the use case—is
done through the development of an interaction diagram. Two types of inter-
communication diagram type of inter­ action diagrams can be used during design: communication diagrams and
action diagram that emphasizes the objects sequence diagrams.
that send and receive messages for a specific
Both communication diagrams and sequence diagrams are a type of UML
use case
interaction diagram. Figure 13-1 is a partial class diagram illustrating this fact.
sequence diagram type of interaction It also shows a few composition classes for each diagram class.
diagram that emphasizes the sequence of Each type of diagram is capable of providing a rigorous method for use case
messages sent between objects for a specific
use case
realization. Interaction diagrams, as the name implies, focus on the interac-
tions between the objects that are required to execute a particular use case. The
interactions between the objects are called messages. These methods translate
directly to the class methods that support the use case. We saw a little bit of
this idea with the “responsibilities” that are identified on CRC cards. However,
interaction diagrams are more formal and precise in defining these interactions
between objects and across layers.
Both communication diagrams and sequence diagrams provide the same
basic information. However, communication diagrams are a little less detailed
and provide a broad “overview” picture of the interactions. Sequence diagrams

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
400 PART 5 ■ Advanced Design and Deployment Concepts

Figure 13-1 Communication diagrams and sequence diagrams are interaction diagrams

Message

InteractionDiagram

Object

Link CommunicationDiagram SequenceDiagram Timeline

are more detailed and allow the designer to visually document the process flow
of the messages. This chapter begins the discussion with communication dia-
grams and then moves to sequence diagrams. First, the following section briefly
discusses the concept of a use case controller.

■■ The Use Case Controller


The previous chapter briefly introduced the concept of a use case controller in
the discussion of CRC cards, but did not elaborate on its use. In reality, a con-
troller class is part of a popular design technique called Model-View-Controller.
(This technique is discussed in more detail in the “Use Case Controller” section
under “Design Patterns.”)
Let us formalize the concept of a use case controller. For any particular use
case, messages come from the external actor to a windows class—that is, an
electronic input form—and then to a problem domain class. One issue in sys-
tems design is the question of which problem domain class should receive input
messages to reduce coupling, maintain highly cohesive domain classes, and pro-
tect from variations between the user interface and the domain layer. (Do you
remember these good design principles discussed in Chapter 12?) Designers often
define intermediary classes that act as buffers between the user interface and the
domain classes. These classes are called use case controllers. For example, the
use case Fill shopping cart might have a controller class named CartHandler.
A use case controller acts as a switchboard, taking input messages and rout-
ing them to the correct domain class. In effect, the use case controller acts as an
intermediary between the outside world and the internal system. What if a par-
ticular window object needs to send messages to several problem domain objects?
Without the use case controller, the input window would need references to all
these domain objects. The coupling between the input window object and the
internal system would be very high; there would be many connections. The cou-
pling between the user-interface objects and the problem domain objects could
be reduced by making a single use case controller object to handle all the input
messages. In this way, domain layer design classes can remain more cohesive by
focusing only on the precise functions that truly belong to that domain object.
The following examples define a controller class for each use case. This is
a common practice, and many development environments (such as Java Struts)
automatically define a controller class for each use case. Of course, this creates
many artifact objects in a system. If there are 100 use cases, there would be
100 use case controller artifact objects. To reduce the number of controllers,
developers sometimes combine the control of several closely related use cases
into a single use case controller. Either approach, if done judiciously, provides a

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 13 ■ Object-Oriented Design: Use Case Realization 401

good solution. A use case controller is a completely artificial class created by the
person doing the system design. Sometimes, such classes are called artifacts or
artifact objects.

■■ Use Case Realization with Communication Diagrams


Adaptive projects that use iteration and Agile modeling techniques minimize the
formality of design diagrams. In this chapter (and possibly for your homework
assignments), the diagrams will be developed using Microsoft Visio. However,
in real projects, hand-drawn diagrams can be scanned and transmitted to all
the team members just as easily. Design diagrams are helpful in communicating
design decisions throughout the team.

■■ Understanding Communication Diagrams


A communication diagram consists of actors, objects, links, and messages.
­F igure 13-2 illustrates how these various components are illustrated on
the diagram.
These components have the following characteristics:
■■ Actor. This represents an external role of the person or thing that initiates
the use case by sending the initial message. The actor will also send any
other messages that are external to the system. These messages can come
into the system through data that is entered on forms. They can also come
electronically by other external devices or systems.
■■ Object. The objects are the instantiated class objects that perform actions
to help carry out the use case. In design diagram terms, they receive the
messages that request services. Objects can both receive messages and send
messages. Note we use object notation—with a colon and underlining—
and not class notation. The execution of a use case is performed by instan-
tiated objects and not classes.
■■ Link. Links are simply the connectors that illustrate the flow of the messages.
These links do not mean the same as the navigation visibility arrows, although
they frequently exist between the same objects. They are only used to show
where the messages flow. Messages can flow in either direction on a link.

Figure 13-2 Symbols used in a communication diagram

An object that
An actor who sends receives a message
the initial message and sends other
messages

1: firstMessage ( ) 2: secondMessage ( )

:Object :Object2

4: finalResponse ( ) 3: returnMessage ( )
Actor
© Cengage Learning ®

A link between A message arrow and


symbols that send or descriptive name
receive messages

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
402 PART 5 ■ Advanced Design and Deployment Concepts

■■ Message. Messages are a primary element of the diagram. A message has


an originating object or actor, and a destination object or actor. A message
is a request for service. A message can also be a return of data from a previ-
ous message. A message will invoke a service in an object. In programming
terms, a message is the same as a procedure call or a method call.
Chapter 5 first presented the idea of a message in the discussion of a system
sequence diagram. Messages in a communication diagram have the same mean-
ing. However, the syntax of the message is slightly different. The syntax con-
tains five elements, all of which are optional. The format of a communication
diagram message is the following:
[true/false condition] sequence-number: return-value: 5 message-name
(parameter-list)
■■ True/false condition. This is a condition that is tested for true or false. If
it is true, then the message is sent; if false, the message is not sent. It only
applies to sending the message. It is optional.
■■ Sequence number. The sequence number is used to identify the order,
or sequence, of the messages. They can be simply numbered by integers.
Developers also often use hierarchical dot notation (i.e., 1.0, 1.2, 2.1.3,
etc.) to denote dependency as well as sequence. For example, if a use case
has two separate input messages, each with several subsequent messages
that travel the same links, they could be uniquely partitioned by using
1.0 and 2.0 series. Note that a colon follows the sequence number.
■■ Return-value. The return value is a value that the message returns after the
completion of the service requested in the forward part of the message. In
programming terms, this is similar to a method return value. Return values
can be returned either with this format (i.e., as part of the message) or as a
separate return message.
■■ Message-name. This is the name of the message. As noted, it usually uses
camel case with the initial letter lowercase. To name the message, it is
usually best to describe the service that is requested from the destination
object. For example, createAccount could be a message name that requests
the specific service from the destination object. Notice that if a return-value
is given, that the two items are separated by a “:=” sign.
■■ Parameter-list. The parameter list contains those items that are being passed
to the destination object via the message. Again, in programming terms,
these are the arguments that would be passed when a method is invoked.
Let’s look at a typical communication diagram and take note of the informa-
tion it provides and its characteristics. Remember that a communication diagram is
useful to design and document use cases of medium complexity. In other words, this
type of diagram works best for use cases that are not too large with many messages.
A major benefit of a communication diagram is that it provides a snapshot view of
the classes and messages. However, a disadvantage is that there is not much space
allowed for messages, so it can easily become cluttered with overlapping information.
Figure 13-3 is a communication diagram for the Create customer account use case.
Refer back to Figure 12-19 and recall the set of CRC cards created for this same use
case. You might want to compare the two solutions, shown in Figure 12-19 and 13-3.
This use case has three input messages: createNewCustomer, enterAddress,
and enterAccount. Figure 13-3 shows those three messages as input messages
coming from the Clerk actor into the :CustomerHandler controller object. Note
the sequence numbers indicate the order of the messages. The first message spec-
ifies the individual parameters that are to be passed with the message. However,
due to space limitations, Figure 13-3 does not show the detail parameters for
message 2 or 3. The programmer would have to look at the class diagram and
determine what information needs to be passed, or he could provide a footnote
to the drawing to provide that additional detail. On the second message, the

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 13 ■ Object-Oriented Design: Use Case Realization 403

Figure 13-3 Communication diagram for Create customer account use case

aAdd:Address
1: createNewCustomer 1.1: aC := createNewCustomer
(name, mobilePh, homePh, email) (name, mobilePh, homePh, email)

2.2: aAdd := createAddress


«controller» (accNo, type, no, street, city, state, zip)
aC:Customer
:CustomerHandler
3.2: aAcc :=createAccount
Clerk 2: *enterAddress (addressInfo) 2.1: enterAddress (addressInfo) (accNo. type, CCNo, CCDate)

3: enterAccount (cc-info) 3.1: enterAccount (cc-info)


aAcc:Account

asterisk between the number and the name indicates that the message may be
sent multiple times. This is called a multiply occurring message.
The next set of messages, 1.1, 2.1, and 3.1, use the hierarchical dot notation
to indicate that they are part of a sequence. Looking at 1.1, notice that it has a
return value. Also note that the Customer object is named aC:Customer. The
underline indicates an object and not a class. The aC: is the name or identifier for
this particular object. That information (i.e., the name of the object) is returned
to the :CustomerHandler object. Referring back to Figure 12-16, note that the
:CustomerHandler object has navigation visibility to the :Customer object. This
mechanism of returning the identifier of the newly created :Customer object
provides this navigation visibility. Thus, the :CustomerHandler object can pass
the other messages to the correct object because it has a reference to it.
The next set of messages, 2.2 and 3.2, have a similar form. Each sends a
create message to the appropriate object and returns the identifier of the newly
created object. These two messages include the detail parameters to be passed.
In the earlier messages, 2, 2.1, 3, and 3.1 only abbreviated parameter lists were
given. The full parameter list is more correct. The abbreviated lists were used
purely to save space. Remember, the purpose of modeling is to provide guide-
lines for programming. So designers sometimes take liberties with the formality
of the model, as long as it is still understandable.
Finally, it is worth mentioning that some return messages have been left off
from :CustomerHandler to the Clerk. A system will normally return and display
the data that was entered so that the actor can verify that the correct informa-
tion was stored. In Figure 13-2, the method of returning data is indicated with
a return message.

■■ Object-Oriented Design with Communication Diagrams


Now that you can read and understand a communication diagram, it’s time to
learn how to do use case realization using this technique. You will work through
the same use case, Create customer account. As you work through the example,
your understanding of object-oriented design should deepen due to the detailed
discussion of the design steps.
Referring back to Figures 12-3 and 12-8, note the models and information
that are prerequisite to detailed object-oriented design. First, you should have
completed the first-cut design class diagram. This gives you a preliminary idea
of what domain classes will be involved and the logical navigation visibility rela-
tionships. From the analysis models, it is helpful to have either an activity dia-
gram or a system sequence diagram. In fact, in the ideal world, both would be
available along with a detailed use case description.

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
404 PART 5 ■ Advanced Design and Deployment Concepts

Figure 13-4 First-cut design


class diagram for Create customer
Customer Account
account
-accountNo: string {key} -accountNo: string {key}
«controller» -name: string -typeOfAccount: string
CustomerHandler -mobilePhone: string -creditCardNo: int
-homePhone: string -creditCardDate: date
-emailAddress: string
-status: string

Address

-accountNo: string {key}


-typeOfAddress: string
-number: string
-street: string

© Cengage Learning ®
-city: string
-state: string
-postalCode: string

❚❚ Input Models
A slightly enhanced version of Figure 12-16 is included here as Figure 13-4. The
selection of which classes to include is purely an estimate at this point because
we will not determine all the classes until we proceed with the design steps.
However, in this simple example, the preliminary assessment is accurate. Do not
worry if you do happen to omit some required classes. It will become evident
during the design process if something is missing.
The other source of input information comes from the analysis ­models.
Chapter 5 developed several models for this use case, including a use case
description (Figure 5-2), an activity diagram (Figure 5-4), and a system
sequence diagram (Figure 5-10). Before initiating the design, you will want
to look at all three models to understand as much as possible about the use
case. For this example, focus on the system sequence diagram, which is dupli-
cated here as ­Figure 13-5. There are three input messages and two return
responses.

❚❚ Extend Input Messages


For each input message, extend the message to the internal objects within the
:System object. Follow this process:
1. From the first-cut design class diagram, identify the classes that will be
­required to carry out the execution of the message. Place the corresponding
objects on the diagram.
2. Beginning with the input message, identify each message that will be
required for each of the included objects on the diagram. For each message,
ensure that the origin object has navigation visibility to the destination
object. Determine which object should have primary responsibility for com-
pleting the required service. Place appropriate messages based on navigation
and responsibility.

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 13 ■ Object-Oriented Design: Use Case Realization 405

Figure 13-5 System sequence


diagram for Create customer
account

:System

Customer

createNewCustomer (name, phones, emails)

cust ID, name, phones, emails

*address details := enterAddress (address)

enterCreditCard (cc-info)

© Cengage Learning ®
credit card info details

3. Name each message to reflect the service requested from the destination
object. Identify and include the parameters that the destination object will
require to carry out the requested service. Identify and name any return
messages or return values that need to be returned to origin objects.
Looking at the first input message, createNewCustomer (name, phones,
emails), we decide the following:
1. The required classes for this message are CustomerHandler and Customer.
2. The required message is createNewCustomer and comes from the Clerk to
the :CustomerHandler. The :CustomerHandler then forwards that same
message to the :Customer object. The :Customer object is the appropriate
object to carry out this service. The constructor method in the Customer
class instantiates a new :Customer object. This is shown in the diagram
with a message directly to the :Customer object.
3. The name of the message is appropriate as given in the SSD. The param-
eters on the SSD, however, do not reflect the attributes of the Customer
class. The accountNo and status attributes are both determined by the
constructor. The other attributes—name, mobilePhone, homePhone, and
emailAddress—need to be passed in as arguments. The input parameter list
will be modified to reflect these changes.
The return information is a little more complex. First, the identifier, “aC,”
of the newly created object is returned from :Customer to :CustomerHandler. As
mentioned previously, this provides navigation visibility from :CustomerHandler­
to :Customer. Second, all of the data from the :Customer object is returned to
the clerk, including the accountNo and the status. Only the parameter-list is
included because all other items of the message syntax are optional, and not
required for this message.
Figure 13-6 is the result of these steps. Notice that the messages in the fig-
ure are numbered sequentially as they are passed.

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
406 PART 5 ■ Advanced Design and Deployment Concepts

Figure 13-6 createNewCustomer message extended to all objects

1: createNewCustomer 1.1: aC := createNewCustomer


(name, mobilePh, homePh, email) (name, mobilePh, homePh, email)

«controller»
aC:Customer
:CustomerHandler

Clerk 1.2: (accountNo, name, mobilePh, homePh, email, status)

Next, you follow the same steps for the second input message, which is
*address details := enterAddress (address).
Notice several things about this input message. First, it begins with an asterisk.
The asterisk means that this message may be sent multiple times. You will carry
that forward to the design. Second, the return data is shown right in the message
syntax. You have the option of showing it that way, or with a separate message
as was done with the first message above. Finally, note that the parameter list
is rather abbreviated. We will need to expand it to reflect the attributes of the
Address class.
The original name of the message is appropriate for the input message and
the second message: enterAddress. However, we change the name to create­
Address for the final name to better reflect service requested. The responsible
object for initiating this final request should be the :Customer object. Because
a customer needs navigation visibility to its dependent objects, including its
addresses, it should be the one to invoke the constructor method. The path of
the message thus goes from the controller to :Customer and then to :Address.
Figure 13-7 illustrates the results of extending this message.
The next message, enterCreditCard (cc-info), will follow the same pro-
cess. We also changed the name of this message to be enterAccount because
we are creating a new Account object. We also expanded the parameter list to
reflect the attributes in the Account class. The other decisions with regard to
responsibility and flow of execution are similar to the enterAddress message.
­Figure 13-8 shows the results of extending the enterAccount message.

Figure 13-7 enterAddress message extended to all objects

aAdd:Address

2: * enterAddress 2.1: enterAddress 2.2: aAdd := createAddress


(type, no, street, city, state, zip) (type, no, street, city, state, zip) (accNo, type, no, street, city, state, zip)

«controller»
aC:Customer
:CustomerHandler

Clerk 2.4: (type, no, street, city, state, zip) 2.3: (type, no, street, city, state, zip)

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 13 ■ Object-Oriented Design: Use Case Realization 407

Figure 13-8 enterAccount message extended to all objects

3: enterAccount (type, CCNo, CCDate) 3.1: enterAccount (type, CCNo, CCDate)

«controller»
aC:Customer
:CustomerHandler
3.2: aAcc := createAccount
(accNo, type, CCNo, CCDate)
Clerk 3.4: (type, CCNo, CCDate) 3.3: (type, CCNo, CCDate)

aAcc:Account

The final communication diagram for this use case is illustrated in


­Figure 13-9. It is similar to the earlier one in Figure 13-3; however, all of the
return messages are included in this final diagram. For ease of reading, the input
messages are on top and the return messages are on the bottom. This diagram
contains only problem domain objects and does not include view layer or data
access layer. The multilayer design using sequence diagrams are covered in the
next section. The process is the same for both types of diagrams.

❚❚ Final Design Class Diagram


As can be seen in Figure 13-9, the messages are specific and precise. Thus, spec-
ifying the methods in the design classes can also be precisely defined. In fact,
message syntax for communication diagrams is quite similar to the method

Figure 13-9 Final communication diagram for Create customer account use case

aAdd:Address

1: createNewCustomer 1.1: aC := createNewCustomer


(name, mobilePh, homePh, email) (name, mobilePh, homePh, email)

2: *enterAddress (type, no, street, city, state, zip) 2.1: enterAddress (type, no, street, city, state, zip) 2.2: aAdd := createAddress
(accNo, type, no, street, city, state, zip)

3: enterAccount (type, CCNo, CCDate) 3.1: enterAccount (type, CCNo, CCDate)

«controller»
aC:Customer
:CustomerHandler

Clerk 1.2: (accountNo, name, mobilePh, homePh, email, status) 2.3: (type, no, street, city, state, zip)
3.2: aAcc := createAccount
(accNo, type, CCNo, CCDate)
2.4: (type, no, street, city, state, zip) 3.3: (type, CCNo, CCDate)

3.4: (type, CCNo, CCDate)

aAcc:Account

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
408 PART 5 ■ Advanced Design and Deployment Concepts

Figure 13-10 Design class diagram for methods added from Create customer account

«controller»
CustomerHandler

+createCustomer (name, mobilePh, homePh, email)


Address
+enterAddress (type, street, city, state, zip)
+enterAccount (type, CCNo, CCDate)
-accountNo: string {key}
-typeOfAddress: string
-number: string
-street: string
-city: string
-state: string
Customer -postalCode: string

+createAddress
-accountNo: string {key} (accNo, type, no, street, city, state, zip): Address
-name: string
-mobilePhone: string
-homePhone: string
-status: string

+createNewCustomer (name, mobilePh, homePh, email): Customer


Account
+enterAddress (type, street, city, state, zip)
+enterAccount (type, CCNo, CCDate) -accountNo: string {key}
-typeOfAccount: string
-creditCardNo: int
-creditCardDate: date

+createAccount (accNo, type, CCNo, CCDate): Account

syntax that is used for the design class diagram. Figure 13-10 illustrates the
final design class diagram. You will note that is very similar to Figure 12-22.
In this instance, however, the constructor methods for each class are included.

■■ Use Case Realization with Sequence Diagrams


Now that you have learned how to do object-oriented design with CRC cards
and with communication diagrams, this section explains how to design com-
plex use cases using sequence diagrams. The next section provides a partial
sequence diagram to introduce the terms and composition of a sequence dia-
gram. The chapter then demonstrates the process of use case realization by
using the use case that we have been working with previously, Create customer
account. The chapter also demonstrates a more complex example with the use
case Fill shopping cart. These examples illustrate the core process of organizing
and structuring the problem domain classes into the solution for the use case.
The final examples explain how to add the data access layer classes and the
view layer classes. Each layer is illustrated with a detailed example using the
same use case.

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 13 ■ Object-Oriented Design: Use Case Realization 409

■■ Understanding Sequence Diagrams


This section first reviews the elements of a sequence diagram to ensure that you
remember and understand how to read a sequence diagram. You first learned
about sequence diagrams in Chapter 5 when you learned how to develop a sys-
tem sequence diagram (SSD).
The most important information on an SSD is the sequence of messages
between the actor and the system. There may be a single input message or many.
The input messages may have data parameters or not. There also may be Loop
frames, Alt frames, and Opt frames as well as repeating inputs and outputs.
A Loop frame denotes a set of messages within a loop. An Alt frame is similar
to an if-then-else statement or switch statement, which allows the firing of dif-
ferent sets of messages. An Opt frame is an optional invocation of a set of mes-
sages. You will see examples of these later in this chapter. First, let’s review the
basic elements in a sequence diagram.
Figure 13-11 is a sample sequence diagram. In many ways, it is similar to a
communication diagram. The actor is an external role, in this case, a Clerk. The
boxes are instantiated objects from the corresponding classes. Object notation is
used. Some objects are named objects, such as aC:Customer. The primary benefit
of the sequence diagram is the ability to lay out the messages from top to bot-
tom to emphasize the sequence of firing. Below each actor and object is a lifeline,
which is used as an indicator of the life of the object. Messages are attached to
activation lifeline a representation of the the lifeline either as a source point or a destination point. Attached to locations
period during which a method of an object is of each lifeline are vertical boxes representing activation lifelines. You might
alive and executing consider these activation lifelines the time period when a method is executing.

Figure 13-11 Sample sequence diagram from Create customer account use case

«controller»
aC:Customer
Clerk :CustomerHandler
Activation Lifeline
A Method to return data;
createNewCustomer (name, mobilePh, homePh, email)
note dashed arrow

aC :=createNewCustomer (name, mobilePh, homePh, email)


A method to return data

(name, mobilePh, homePh, email)

*enterAddress (type, no, street, city, state, zip) aAdd: =createAddress


enterAddress (type, no, street, city, state, zip) (accNo, type, no, street, city, state, zip)

aAdd:Address
Lifeline
(type, no, street, city, state, zip)

(type, no, street, city, state, zip) Vertical position of Send a constructor message
messages indicates either to the object itself, or
sequence of firing to its lifeline

enterAccount (type, CCNo, CCDate)


enterAccount (type, CCNo, CCDate)
© Cengage Learning ®

aAcc: =createAccount (accNo, type, CCNo, CCDate)


aAcc:Account

(type, CCNo, CCDate) (type, CCNo, CCDate)

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
410 PART 5 ■ Advanced Design and Deployment Concepts

Some developers use them; others do not. There are two ways to indicate data
being returned, either by a return assignment with the “:=” operator, or as a return
message using a dashed arrow. Messages that invoke a constructor can be sent
either to a lifeline or to the object itself. Both examples are shown in the figure.
As with a communication diagram, when a message is sent from an originat-
ing object to a destination object, in programming terms, it means that the origi-
nating object is invoking a method on the destination object. Thus, by defining
the messages to various internal objects, we are actually identifying the methods
of that object. The data that is passed by the messages corresponds to the input
parameters of the methods. The return data on a message is the return value from
a method. Hence, once a use case is realized with this detailed design process,
the set of classes and required methods can be extracted so programming can
be completed.

■■ Design Process for Use Case Realization


The design process for using sequence diagrams is the same as it is for com-
munication diagrams. The starting point for the detailed design of a use case
is always its SSD and the first-cut design class diagram. Other models, such as
a use case description and activity diagram, are also helpful. Remember that
the SSD only has two lifelines—one for the actor and one for the system. Start-
ing with the SSD, each input message is taken, one at a time, and extended
to all of the internal classes so that the desired result is obtained. Any data to
be returned is identified and added. Figure 13-11 is the sequence diagram solu-
tion of the Create customer account use case. It was developed using the same
three steps that were used to extend communication diagram messages. You will
notice that it has the same set of messages, but displayed differently.
Let us analyze this solution based on some of the principles of good design
that were discussed in Chapter 12. The use case controller provides the link
between the internal objects and the external environment. The responsibilities
assigned to :CustomerHandler are to catch incoming messages, distribute them
to the correct internal domain objects, and return the required information to
the external environment.
The responsibility assigned to :Customer is to be in charge of creating itself
and to control the other required updates to subordinate objects. The :Address
and :Account objects create themselves. Coupling is straightforward, being basi-
cally vertical on the hierarchy. Thus, the assignment of responsibilities and cor-
responding messages conforms to good design principles. Other issues will need
to be addressed as the design expands to include three layers.

■■ Sequence Diagram: Fill Shopping Cart Use Case


This section looks at a slightly more complex example of a sequence diagram.
With this example, you will see the strength of sequence diagrams in modeling
complex use cases. Figure 13-12 is an activity diagram for the Fill shopping
cart use case. You will remember from Figure 3-15 that this use case “included”
three other use cases, as shown in Figure 13-12. By designing the use case in this
manner, with other use cases included, our solution will only have to focus on
those functions that actually add items to the shopping cart.
The SSD for this use case is quite simple. Figure 13-13 shows that there are
only two input messages to the system: adding an item and adding an acces-
sory item. As you analyze the SSD, notice that adding an item to the shopping
cart and adding an accessory to the cart are the same operation. The only dif-
ference is that adding accessories requires a loop for any multiple accessories
added for that same item. Because this is the only difference, we can simplify the

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 13 ■ Object-Oriented Design: Use Case Realization 411

Figure 13-12 Activity diagram for


the Fill shopping cart use case Customer System

Search for product

Look at product
reviews

Select options and


quantity

Search and view Add to cart


accessories

Select accessory
options and
quantity

Add to cart

© Cengage Learning ®
diagram by limiting the solution to the first message. (Note: An additional class,
­AccessoryPackage, is required for the use case Search and view accessories, but
because we aren’t designing that use case, it isn’t required for this solution.)
We begin this design by developing the first-cut design class diagam. Refer
back to Figure 4-23, which presented the class diagram for the CSMS sales subsys-
tem. Using that diagram, we can identify the classes that are required for this use
case. The Customer, Cart, and CartItem classes are necessary because the use case
will be adding items for this customer to the customer’s cart. To create a cart item,
the system will need to know what product it is, if there are items in stock, and
the price for the item. Therefore, other classes that are required are InventoryItem,
ProductItem, and PromoOffering. As we develop the solution, we may have to add
classes, but this appears to be sufficient for now. Navigation visibility between
these classes will be from the controller to the Customer class and to the Cart class
once it has been created. The Cart class will be able to access the CartItem class.
The CartItem class should have visibility to the other classes, such as ProductItem

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
412 PART 5 ■ Advanced Design and Deployment Concepts

Figure 13-13 System sequence


diagram for Fill shopping cart
use case

Customer :System

addItemToCart (promoNo, prodID, size, qty)

(description, price, extendedPrice)

*addAccessoryToCart (promoNo, prodID, size, qty)

© Cengage Learning ®
(description, price, extendedPrice)

and InventoryItem that contain the necessary information. Figure 13-14 shows
the first-cut design class diagram, which includes several additions to the domain
model. In Figure 13-14, several key identifier fields have been added to some classes.
One correction to the domain model was also made. In Chapter 9 during the nor-
malization process the regularPrice attribute was moved out of the PromoOffering
class and into the ProductItem class, which is where it correctly belongs.
To design this use case, we will follow the same steps that were outlined in
the “Extend Input Messages” section for use case realization using communi-
cation diagrams. Even though this use case has fewer input messages than the
previous example (Create customer account), the processing required to execute
a message is more complex.
Let’s take the first input message, addItemToCart. This message first comes
to the CartHandler. Obviously, it is not possible to add an item to a cart if there
is no cart. So how do you create a cart? One solution is to require the user/actor
to create a new cart. This is a poor idea. It is never a good idea to require the
user to perform an act if the system can do it automatically. The system can be
made smart enough to know if it needs to create an online cart first. How can
the system know? There are several ways to design this process. Let’s use the
perfect technology assumption that the user has logged on. So :CartHandler
should have a reference to the :Customer object. However, if there is no refer-
ence to an online cart object, then it needs to be created. The next question is,
what object should create the new online cart object? From the domain model,
you can see that an online cart object has a cardinality of exactly one to a cus-
tomer object. So a cart cannot exist without a customer, and from the design
class diagram, you can see that the customer must have visibility to the online
cart. Hence :Customer is the obvious object to create the :OnLineCart object.
Figure 13-15 shows this first step. The :CartHandler checks to see if it is the
first item, and if so, sends a createCart message to :Customer. Notice the true/
false condition on that message. The :Customer object sends a create message
directly to :OnlineCart to instantiate a new cart. A reference to the new cart is
returned first to :Customer, which then forwards it on to :CartHandler. Now
both have navigation visibility to the newly created online cart. Figure 13-15
shows both methods of returning data.
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 13 ■ Object-Oriented Design: Use Case Realization 413

Figure 13-14 First-cut


design class diagram for
the Fill shopping cart «controller»
use case CartHandler

Customer OnlineCart CartItem


-accountNo: string {key} -Sale: int {key} -saleItemID: int {key}
-name: string -saleDateTime: date -productID: string
-mobilePhone: string -priorityCode: string -InventoryID: int
-homePhone: string -S&H: currency -quantity: int
-emailAddress: string -tax: currency -soldPrice: currency
-status: string -totalAmt: currency -shipStatus: string
-backOrderStatus: string

InventoryItem ProductItem PromoOffering


-inventoryID: int {key} -productID: string {key} -promoNo: string
-productID: string -gender: string -promoPrice: currency
-size: string -description: string
-color: string -supplier: string
-options: string -manufacturer: string
-quantityOnHand: int -regularPrice: currency

© Cengage Learning ®
-averageCost: currency -pictureID: string
-reorderQuantity: int
-dateLastOrder: date
-dateLastShipment: date

Figure 13-15 First step in extending addItem message

:CartHandler :Customer

Customer

addItem (promoNo, prodID, size, color, qty)


[firstItem]createCart ( )
aCrt: =createCart ( )
aCrt:OnlineCart

(aCrt)

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
414 PART 5 ■ Advanced Design and Deployment Concepts

Now that the cart is created, the system can add the item to the cart. Also,
notice that if it is not the first item, then this sequence of messages is skipped and
the system goes directly to adding the item to the cart. Because :Cart­H andler
now has visibility to :OnlineCart, it sends a message directly to the cart to add
the appropriate item. :OnlineCart creates a new cart item and passes the data to
:CartItem to instantiate a new cart item. :CartItem retrieves the necessary data
to complete its attributes. We are assuming in this case that the price is the pro-
motional price. Once the cart item has created itself, it returns information back
to :OnlineCart, which returns it to :CartHandler and eventually to the user/
customer. Figure 13-16 illustrates this next set of messages.
As you can see, this simple input message extends to quite a bit of internal
activity. How did we know what to do? We observed the attributes of :CartItem
and noted what classes contained the information that was needed. :CartItem is
responsible for obtaining the data to instantiate itself. It simply went to the nec-
essary objects to obtain that data.
Referring back to Figure 13-13, note that there is another input message,
addAccessoryToCart (…), with the same input parameters. As you think about
this, note that adding an accessory is the same activity as adding an item. Acces-
sories are just items that are associated with products for promotions to the cus-
tomer. Once an accessory item is selected, it simply becomes an item. Hence, the
same set of internal messages are required. The only difference is that adding
accessories is an optional activity. In Chapter 5, Figures 5-8 and 5-9 showed you
how to indicate a loop of messages or an optional set of messages. In this case, the

Figure 13-16 Completion of Additem message

:CartHandler :Customer :ProductItem


Customer
addItem
(promoNo, prodID, size, color, qty) :PromoOffering :InventoryItem

[firstItem]createCart ( )
aCrt := createCart ( )

aCrt:OnlineCart
(aCrt)

addItem (promoNo, prodID, size, color, qty) createCartItem


(promoNo, prodID, size, color, qty)

:CartItem

price:=getPrice ( )

description:=getDesc ( )

status:=updateQty (qty)

(description, price)
(description, price)
(description, price, extended price)

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 13 ■ Object-Oriented Design: Use Case Realization 415

SSD indicates a repeating message for the accessories. Figure 13-17 is the full use
case with both sets of messages shown, one set for an item and a repeating set for
the accessories. The repeating messages inside the Opt, Loop frame are the same
as those developed for the first input message, but without the createCart message.
As you identify the specific messages, along with source and destination and
the passed parameters, you need to consider some critical issues. As before, an
important question is: Which object is the source or initiator of a message? If
the message is a query message, the source is the object that needs information.

Figure 13-17 Sequence diagram for Fill shopping cart use case

:CartHandler :Customer :ProductItem


Customer
addItem
(promoNo, prodID, size, color, qty) :PromoOffering :InventoryItem

[firstItem]createCart ( )
aCrt := createCart ( )
aCrt:OnlineCart

(aCrt)

createCartItem
addItem (promoNo, prodID, size, color, qty)
(promoNo, prodID, size, color, qty)

:CartItem

price:=getPrice ( )

description:=getDesc ( )

status:=updateQty (qty)

(description, price)
(description, price)
(description, price,
extended price)

Loop
[Accessory]
addAccessory
(promoNo, prodID, size, color, qty)

addItem createCartItem
(promoNo, prodID, size, color, qty) (promoNo, prodID, size, color, qty)

price:=getPrice ( )

description:=getDesc ( )

status:=updateQty (qty)
© Cengage Learning ®

(description, price) (description, price)


(description, price,
extended price)

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
416 PART 5 ■ Advanced Design and Deployment Concepts

If the message is an update or create message, the source is the object that con-
trols the other object or that has the information necessary for its creation.
Another important consideration is navigation visibility. To send a message
to the correct destination object, the source object must have visibility to the
destination object. Remember that the purpose of doing design is to prepare
for programming. As a designer, you must think about how the program will
work and consider programming issues. Given these two considerations and the
source considerations discussed in the previous paragraph, we have determined
that the following internal messages will be required. For each message, a source
object and a destination object have been identified.
■■ createCart(). The :CartHandler object will know whether it has received
earlier messages to add items. If it hasn’t, it knows it must tell the :Customer
object to create a cart.
■■ aCrt:=createCart(). The :Customer object owns the :OnlineCart object.
■■ addItem(). A forwarded version of the input message from :CartHandler to
:OnlineCart. Because :CartItem objects are dependent on a cart, :OnlineCart
is the logical object to create :CartItem objects. The controller has visibility
to :OnlineCart from the previous return message, when aCrt was returned.
■■ createCartItem(). The internal message from :Cart to :CartItem. Because
:CartItem will be responsible for obtaining the data for its attributes, it
needs visibility to :PromoOffering, :ProductItem, and :InventoryItem. As a
result, information to find those objects is sent as parameters.
■■ getPrice(). The message to get the price from the :PromoOffering object.
The :CartItem initiates the message.
■■ getDescription(). The message initiated by :CartItem to get the description
from :ProductItem.
■■ updateQty(qty). The message that checks for sufficient quantity on hand.
This message also initiates updates of the quantity on hand. :CartItem
­initiates the message.

■■ Guidelines and Assumptions Sequence Diagram Development


From the two previous examples, we can distill several guidelines that can help
you develop a design for a use case or scenario using sequence diagrams. Several
assumptions are also implicit in this process.

❚❚ Guidelines
Designing a use case or scenario by using sequence diagrams involves perform-
ing these tasks:
■■ Take each input message and determine all the internal messages that result
from that input. For each message, determine its objective. Determine what
information is needed, what class needs it (the destination), and what class
provides it (the source).
■■ As you work with each input message, identify the complete set of classes
that will be affected by the message. In other words, select all the objects
from the domain class diagram that need to be involved. In Chapter 5, you
learned about use case preconditions and postconditions. Any classes that are
listed in either the preconditions or postconditions should be included in the
design. Other classes to include are those that are created, classes updated
during the use case, and those that provide information used in the use case.
■■ Flesh out the components for each message; that is, add iteration, true/false con-
ditions, return values, and passed parameters. The passed parameters should be
based on the attributes found in the domain class diagram. Return values and
passed parameters can be attributes, but they may also be objects from classes.
These three steps will produce the preliminary design. Refinements and
modifications may be necessary; again, we are focusing only on the problem
domain classes involved in the use case.
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 13 ■ Object-Oriented Design: Use Case Realization 417

❚❚ Assumptions
The development of the first-cut sequence diagram is based on several assump-
tions, including:
■■ Perfect technology assumption. You first encountered this assumption in
Chapter 5, when identifying business events. The assumption continues
here. You don’t include messages such as the user having to log on.
■■ Perfect memory assumption. You might have noticed our assumption that
the necessary objects were in memory and available for the use case. We
didn’t ask whether those objects were created in memory. We will change
this assumption when we get to multilayer design. In multiple-layer design,
we do include the steps necessary to create objects in memory.
■■ Perfect solution assumption. The first-cut sequence diagram assumes that
there are no exception conditions. No logic is included to handle a situation
in which the requested catalog or product isn’t found. More serious excep-
tion conditions, such as the failure of a credit check, might also be encoun-
tered. Many developers design the basic processing steps first and then add
the other messages and processes to handle the exception conditions later.
We do the same here.

■■ Developing a Multilayer Design


So far in the development of the sequence diagram, we have focused only on the
classes in the problem domain layer. In many instances, this may be sufficient
documentation to program the solution—either by yourself or with another pro-
grammer. Once you have a solid design for the problem domain classes, adding
the view layer and the data access layer is a straightforward, if time-consuming,
process. Conforming to the principles of Agile modeling, we don’t want to cre-
ate diagrams unless there is real benefit. We also don’t normally keep the design
­diagrams as documentation because over time, the system will be modified and
the diagrams will become obsolete. As Agile modeling suggests, be prudent in the
development of models. However, there are times when it is important to see the
total picture and identify the need and use of the view layer classes and the data
access layer classes. A system developer needs to know how to do ­complete
design for those instances when it is necessary.
Every system will need view layer classes to represent the input and out-
put screens for the application. Data access layer classes aren’t always required.
The data access layer is required when the business logic is fairly complex and
should be isolated from the SQL statements that access the database. The CRC
cards example in Chapter 12 for the Create customer account use case showed
an example of a three-layer design with both view and data access classes (see
­Figure 12-21). Because CRC cards is an informal technique, we simply added
the classes without much discussion of how they are to be connected to the
problem domain classes. The following sections develop that same example but
with a sequence diagram. This more rigorous modeling technique highlights the
issues involved with three-layer design. First, we add the view layer, then the
data access layer.

■■ Designing the View Layer


In Chapter 8, you learned how to do the design of the user interface. In ­reality,
user-interface design is both an analysis and a design activity. Quite a bit of
discovery and understanding is being developed as the systems analysts and
the users work together. However, design work is also being done because the
actual detailed layout, including input and output data fields, is being devel-
oped. You might ask, “If the user interface is already designed, do I need to
add the view layer to the sequence diagram?” The answer is a definite maybe.
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
418 PART 5 ■ Advanced Design and Deployment Concepts

One advantage of adding it to the sequence diagram is that the programmer can
see how the view layer classes integrate with the rest of the design. It becomes
a check to make sure the design is correct and complete. It is a good practice to
verify several use cases to ensure that the developers understand how the view
layer represents the user-interface design and how all the elements integrate
together for a smooth program execution. Thus, input for view layer design
includes the use case description, the SSD, the activity diagrams, the first-cut
design class diagram, and, finally, the user-interface layouts or mock-ups.
User-interface design and the integration of the view layer into a sequence
diagram are made even more complex by the fact that many systems require
both a Web-based interface and an internal, network-based interface. Fortu-
nately, browsers are becoming more sophisticated, so many new systems can
now be designed for only one type of interface. Designing a system with multiple
user interfaces is a complex endeavor.
Let’s return to the Add customer account use case and add the view layer.
Remember from the discussion of communication diagrams that there are three
input messages: createNewCustomer, enterAddress, and enterAccount. Let’s
assume that, from the results of our user-interface design, a separate input form
for each message is required. Let’s add those classes to the sequence diagram.
The starting point is Figure 13-11, which is the sequence diagram with the prob-
lem domain classes. The process to add the view layer is simply to add an object
for each input form or screen. First add the appropriate messages from the Clerk
to the input «view» objects. In this instance, the messages are the ones identified
from the SSD, and which were used in Figure 13-11. Additional messages are
added for the :CustWindow to open the :AddrWindow, and the :AddrWindow
to open the :AcctWindow. Figure 13-18 illustrates the resulting diagram with
both the domain and view layers.
In Figure 13-18, we just added a single view object for each message. This
approach was rather straightforward. If we look at the other use case we have
been using, Fill shopping cart, we have a more complex example. Remember
that the Fill shopping cart use case included other use cases for Search for item
and View accessory combinations. Obviously, all those use cases go together
for a rich and efficient user experience. In Figure 13-19, we have added the
two view layer objects for searching items and viewing accessories. The first
input message, addItem ( ), will go through the :SearchItemWindow object.
In other words, when the customer finds something he or she likes, he or she
will initiate adding it to his or her cart from that window. The message then
causes a detailed :AddItemWindow object to display and show the details to
verify the addition to the cart. This later window will forward the message on
to :CartHandler.
Once the item has been added to the cart, another window displays that
shows the results of adding this new item. Depending on the design of the user
interface, this window might show the single newly added item or it might also
show the total shopping cart.
The next three view layer objects, :ViewAccessWindow, :AddAccess­
Window, and :DisplayItem+AccessWindow, function in a manner similar to the
other view layer objects. The only difference is that the data includes the item
and the accessories that have been added to the online cart.
Adding the view layer to your design is a good way to verify that the user
interface that was developed with the users is consistent with the application
design. All the input messages that were identified and documented on SSDs
must be handled by the user interface. If there are messages without input win-
dows or windows without messages, you will know that part of the design is
incomplete and that more definition is required.

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 13 ■ Object-Oriented Design: Use Case Realization 419

Figure 13-18 Add customer account use case with view layer added

«view» «controller»
aC:Customer
:CustWindow :CustomerHandler
Clerk
createNewCustomer
(name, mobilePh, homePh, email)
createNewCustomer
aC:=createNewCustomer
(name, mobilePh, homePh, email)
(name, mobilePh, homePh, email)

showAddrWindow ( )

(name, mobilePh, homePh, email

Loop
[Address]
«view»
:AddrWindow
enterAddress
(type,no,street,city,state,zip) enterAddress
aAdd:=createAddress
(type,no,street,city,state,zip) enterAddress (accNo, type, no, street, city, state, zip)
(type,no,street,city,state,zip)

aAdd:Address

showAcctWindow ( ) (type, no, street, city, state, zip)


(type, no, street, city, state, zip)

«view»
:AcctWindow
enterAccount
(type, CCNo, CCDate) enterAccount aAcc:=createAccount
(type, CCNo, CCDate enterAccount (accNo, type, CCNo, CCDate)
(type, CCNo, CCDate)

aAcc:Account

(type, CCNo, CCDate)


(type, CCNo, CCDate)

■■ Designing the Data Access Layer


The principle of separation of responsibilities is the motivating factor behind
the design of the data access layer. On large, complex systems, designers create
three-layer designs, including classes whose sole responsibility is executing data-
base SQL statements, getting the results of the query, and providing the informa-
tion to the domain layer. As hardware and networks became more sophisticated,
multilayer design was used to support multitier networks in which the database
server was on one machine, the business logic was on another server, and the
user interface was on several desktop client machines. This way of designing
systems creates more robust and more flexible systems.
In most cases, problem domain classes are also persistent classes, which
means that their data values must be stored by the system even when the appli-
cation isn’t executing. The whole purpose of a relational database is to provide
this ability to make problem domain objects persistent. Executing SQL state-
ments on a database enables a program to access a record or a set of records

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
420 PART 5 ■ Advanced Design and Deployment Concepts

Figure 13-19 Partial sequence diagram for the Fill shopping cart use case with view layer

«view» «controller»
:SearchItemWindow :CartHandler

Customer
addItem
(promoNo, prodID, size, color, qty)

«view»
:AddItemWindow
addItem
(promoNo, prodID, size, color, qty)
addItem
(promoNo, prodID, size, color, qty)

«view»
:DisplayItemWindow
(description, price, extendedPrice)

(description, price, extendedPrice)


Loop
[Accessory]

«view»
:ViewAccessWindow

addAccessory
(promoNo, prodID, size, color, qty)

«view»
:AddAccessWindow
addAccessory
(promoNo, prodID, size, color, qty)
addAccessory
(promoNo, prodID, size, color, qty)

(description, price, extendedPrice)


«view»
:DisplayItem+AccessWindow
© Cengage Learning ®

(description, price, extendedPrice)

from the database. One of the problems with object-oriented programs that use
relational databases is that there is a slight mismatch between programming lan-
guages and database SQL statements. For example, in a database, tables are
linked through the use of foreign keys (see Figure 9-9), such as a cart having a

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 13 ■ Object-Oriented Design: Use Case Realization 421

CustomerID as a column so the order can be joined with the customer in a rela-
tional join. However, in object-oriented programming languages, the navigation
is often in the opposite direction (i.e., the Customer class may have an array of
references that point to the OnlineCart objects, which are in computer memory
and are being processed by the system). In other words, design classes don’t have
foreign keys.
This chapter takes a somewhat simplified design approach in order to teach
the basic ideas without getting embroiled in the complexities of database access.
Let us assume that every domain object has a table in a relational database.
(More complex situations exist in which tables must be combined to provide the
correct set of objects in memory.)
When a new persistent object is created in memory, the constructor method
often initiates the process to write it to the database. When an object is updated,
it also needs to be written to the database. The common method to do that
is simply to send a message to the data access object. Either the set of object
attributes can be sent as parameters or simply as a reference to the object itself.
The data access method can pull out the attributes, format an SQL insert or
update statement, and write it to the database. Figure 13-20 is an enhancement
of ­Figure 13-18 with the data access layer added. It is a straightforward addition
to add three data access objects and have the newly created objects send mes-
sages to write themselves out to the database. Although this diagram is fairly
busy, it is organized with the view layer on the left, the problem domain layer in
the middle, and the data access layer on the right.

Figure 13-20 Create customer account use case with view layer and data layer

«view» «controller»
aC:Customer
:CustWindow :CustomerHandler
Clerk
createNewCustomer «dataAccess»
(name, mobilePh, homePh, email) :CustomerDA
createNewCustomer aC:=createNewCustomer
(name, mobilePh, homePh, email) (name, mobilePh, homePh, email)
«dataAccess»
showAddrWindow ( ) :AddressDA
writeDB (ac)
(name, mobilePh, homePh, email)
«dataAccess»
:AddressDA
Loop
[Address] «view»
:AddrWindow
enterAddress
(type,no,street,city,state,zip) enterAddress aAdd:=createAddress
(type,no,street,city,state,zip) enterAddress (accNo,type,no,street,city,state,zip)
(type,no,street,city,state,zip)

aAdd:Address

showAcctWindow ( ) (type,no,street,city,state,zip)
(type,no,street,city,state,zip)
writeDB (aAdd)

«view»
:AcctWindow
enterAccount
(type, CCNo, CCDate) enterAccount
(type, CCNo, CCDate enterAccount aACC:=createAccount
(type, CCNo, CCDate) (accNo, type, CCNo, CCDate)

aAcc:Account

(type, CCNo, CCDate)


(type, CCNo, CCDate)
writeDB (aAcc)

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
422 PART 5 ■ Advanced Design and Deployment Concepts

Figure 13-21 Partial sequence diagram with data access as part of constructor

:PromoOffering
aPO:PromoOffering :PromoOfferingDA

:CartItem
Becomes :CartItem

price:=getPrice ( )
aPO:=findPromo (promoID, ProdID

readPO ( )

price:=getPrice ( )

When the database needs to be read to retrieve data, usually as part of a


constructor, it is a little more complex. There are several techniques (that pro-
vide different designs) for linking the domain layer to the data access layer for
reading data. There are two common techniques.
One technique is to have the constructor method of an object read the
database and obtain the required data to flesh out its attributes and create an
object in memory. For example, in the Fill shopping cart use case, we need to
get the price from a PromoOffering object. This means that we first have to have
a PromoOffering object in memory, so it must be created and then accessed.
­Figure 13-21 illustrates this technique. The findPromo message invokes a con-
structor for :PromoOffering. During the instantiation, it reads the database to
get the required data. Then, it can respond to the getPrice message.
Another technique is to send a message to the data access layer object and
have it read the database and then instantiate a new problem domain object.
This second technique is better when a set of objects needs to be created from a
database access that returns an unknown number of rows. However, both tech-
niques are good solutions. Figure 13-22 illustrates this second technique.

❚❚ The Data Access Layer for the Fill Shopping Cart Use Case
Figure 13-23 is a portion of the Fill shopping cart use case from Figure 13-16. In
this diagram, we have only included the AddItem message to limit the complexity
of the drawing. The data access classes have all been added along the top. The first
two, :OnlineCartDA and :CartItemDA, are needed so that the system can write
out the data from the newly created online cart and cart item. At the bottom of the
lifeline of each of those two objects is the save statement, which causes the data to
be written to the database. The next three data access objects, :PromoOfferDA,
:ProductDA, and :InventoryDA, are needed to retrieve data as part of the construc-
tor for :PromoOffering, :ProductItem, and :InventoryItem. Each of those sets of
messages function as explained in Figure 13-21. As you can see, adding the data
access layer can increase the level of complexity of the drawing quite dramatically.
It is important during this process to ensure that source objects have navi-
gation visibility to destination objects so messages can be sent. We assume but
don’t show that the data access objects have global visibility. (In your program-
ming class, you will learn that factory or singleton classes are often designed

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 13 ■ Object-Oriented Design: Use Case Realization 423

Figure 13-22 Partial sequence diagram with data access prior to constructor

PromoOffering
aPO:PromoOffering :PromoOfferingDA

:CartItem
Becomes :CartItem

price:=getPrice ( )

aPO:=findPromo (promoID, ProdID)

createPO (...)
price:=getPrice ( )

Figure 13-23 Partial sequence diagram for the Fill shopping cart use case with data access layer

«dataAccess» «dataAccess» «dataAccess» «dataAccess» «dataAccess»


:OnlineCartDA :CartItemDA :PromoOfferDA :ProductDA :InventoryDA

:CartHandler
aCrt:OnlineCart aP:PromoOffering aPl:ProductItem all:InventoryItem
Customer

addItem (promoNo, ProdID, size, color, qty) createCartItem


(promoNo, ProdID, size, color, qty)

aCl:CartItem
addItem
(promoNo, ProdID, size, color, qty)
aP:=findPromo (promoID, prodID)

price:=getPrice ( ) readPO ( )

aPl:=findProdItem (prodID)

description:=getDesc ( )
readProd ( )

(description, price)
all:=findInvItem (prodID, size, color)
(description, price)
status:=updateQty (qty)
readInv ( )
(description, price, extended price)

saveCartItem (aCI)
saveCart (aCrt)

with global methods.) After the appropriate problem domain object is created, a
reference to it is returned to the object that needs visibility. As you look closely
at Figure 13-23, note that every object that sends a message to another object
must have navigation visibility to that object. Remember this important design
point as you develop your design solutions.

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
424 PART 5 ■ Advanced Design and Deployment Concepts

An effective method for understanding what is going on in Figure 13-23 is


to begin with the internal messages from the sequence diagram in Figure 13-17.
Let us review each one and see what changes are required:
■■ [firstItem]createCart. The cart handler is going to send a message to a
customer object to create a cart. First, it needs to ensure that there is
a customer object in memory. It sends a findCustomer message to the
aC:Customer object to find and create itself from the database. It does
so by sending a message to the :CustomerDA object to read the database
and return the appropriate customer object. Only then can it send the
createCart message to aC:Customer. Also, note that at the end of this
execution, the aCrt:OnlineCart object sends a message to the data access
object to save the data to the database.
■■ addItem. This message is initially the same in both figures. After
aCrt:CartItem has been created and populated with data, a message is sent
to the data access object to save the data to the database.
■■ getPrice, getDesc, updateQty. These three messages all access or update the
database. Therefore, each also requires a previous message to find the appro-
priate data from the database, which is stored in a domain object in memory.
Even though Figure 13-23 appears rather crowded, looking at each internal
message to a problem domain class makes the figure easier to understand. The
primary thing to remember is that data access objects are necessary to retrieve
data and thereby provide navigation visibility to the required object.

■■ Updating and Packaging the Design Classes


The design class diagram keeps growing and expanding as each use case is
designed and its methods added. The previous examples only created a design
class diagram for the problem domain classes. However, design class diagrams
can also be developed for each layer. In the view layer and the data access layer,
several new classes must be specified. The domain layer also has new classes
added for the use case controllers.
As we update the design class diagram, note that there are three types of
methods found in most classes: (1) constructor methods, (2) data-get and data-
set methods, and (3) use case–specific methods.Constructor methods create new
instances of objects. Get and set methods retrieve and update attribute values.
To avoid information overload, most developers don’t include the get and set
methods in the DCD. The third type of method—use case–specific methods—are
the ones we normally include in the design class diagram. Figure 13-24 contains
the completed design class diagram for the domain layer classes for the two use
cases illustrated in this chapter, Create customer account and Fill shopping cart.
The two major additions to the domain layer classes are the two use case
handlers. Additional navigation arrows have also been added to document which
classes are visible from the controller classes. The other navigation arrows,
which were defined during the first cut of the class diagram, have proved to be
adequate for these two use cases.

■■ Structuring the Major Components with Package Diagrams


A package diagram in UML is simply a high-level diagram that allows design-
ers to associate classes of related groups. Designers sometimes need to docu-
ment differences or similarities in relationships in different layers—perhaps
separating or grouping objects based on a distributed processing environment.
This information can be captured by showing each layer as a separate package.
­Figure 13-25 illustrates how these layers might be documented.
The classes are placed inside the appropriate package based on the layer to which
they belong. To develop this package diagram, we simply extracted the information

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 13 ■ Object-Oriented Design: Use Case Realization 425

Figure 13-24 Updated design class diagram for the domain layer

«controller» «controller»
CustomerHandler CartHandler

+createCustomer (name, mobilephone, homePhone, email) +addItem (promoNo, prodID, size, color, qty)
+enterAddress (type, street, city, state, zip) +addAccessory (promoNo, prodID, size, color, qty)
+enterAccount (type, ccNo, ccDate)

Customer OnlineCart
-accountNo: string {key} -saleID: int {key}
-name: string -saleDateTime: date
-mobilePhone: string -priorityCode: string
-homePhone: string -S&H: currency
-status: string -tax: currency
-totalAmt: currency
+createNewCustomer (name, mobilePh, homePh, +createCart ( )
email): Customer +addItem (promoID, prodID, size, color, qty)
+enterAddress(type, street, city, state, zip)
+enterAccount(type, ccNo, ccDate)
+createCart ( )

CartItem

-saleItemId: int {key}


Account
-productID: string
-accountNo: string {key} -InventoryID: int
-typeOfAccount: string -quantity: int
-creditCardNo: int -soldPrice: currency
-creditCardDate: date -shipStatus: string
-backOrderStatus: string
+createAccount (accNo, type, ccNo, ccDate)
+createCartItem (promoNo, prodID, size, color, qty)

Address
-accountNo: string {key} InventoryItem PromoOffering
-typeOfAddress: string
-number: string -inventoryID: int {key} -promoNo: string
-street: string -productID: string -promoPrice: currency
-city: string -size: string
-state: string -color: string +getPrice ( ): currency
-postalCode: string -options: string
-quantityOnHand: int
+createAddress (accNo, type, no, street, city, state, zip) -averageCost: currency ProductItem
-reorderQuantity: int
-dateLastOrder: date -productID: string {key}
-dateLastShipment: date -gender: string
-description: string
-supplier: string
+updateQty (qty): string
© Cengage Learning ®

-manufacturer: string
-regularPrice: currency
-pictureID: string

+getDesc ( ): string

from design class diagrams and interaction diagrams for each use case. ­Figure 13-25
is only a partial package diagram because the packages contain only the classes from
the use case interaction diagrams that were developed in this chapter.
The other symbol used on a package diagram is a dashed arrow, which
dependency relationship a relationship
between packages, classes, or use cases represents a dependency relationship. The arrow’s tail is connected to the
in which a change in the independent item package that is dependent, and the arrowhead is connected to the independent
requires a change in the dependent item package. To read a dependency relationship, read it in the direction of the arrow.

Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.

You might also like