Title: Software Design CS 406 Software Engineering I Fall 2001
1Software DesignCS 406 Software Engineering
IFall 2001
Last update October 2, 2001
2Organization
- Part I Design principles and process
- Part II OO Design
- Part III Design Patterns
- Part IV Special topics
3Learning Objectives
- To learn notations for representing a design.
- To understand and be able to apply the basic
principles of software design. (GRASP patterns).
- To learn techniques and tools for
Object- Oriented Design.
4Models during the Design Phase
Static structure diagrams
Interaction Diagrams Collaboration
diagrams Sequence diagrams
Contracts for methods and operations
State diagrams for classes
5A collaboration diagram
classAinstance
classBinstance
message1() is sent to an instance of class
A. message2() and message3() are sent, in
that order, by an instance of class A to an
instance of class B. One diagram for each
system event.
6A sequence diagram
May be used for multiple events.
7Collaboration diagram makepayment()
Payment
Note Post is Register in the second edition of
Larman.
8Making collaboration diagrams
- One diagram for each system operation in the
current development cycle, e.g. for
makepayment().
- If the diagram gets complex, split into smaller
diagrams.
- Design a system of interacting objects to fulfill
the tasks....this is the tough part of design!
9Classes and Objects
10Links
Sale
Post
Link illustrates client/server relationship.
11Messages
12Parameters
13Return values
1 tottotal() int
14Messages to self or this
msg1()
Post
1 clear()
15Iteration
iteration, no recurrence values
16Iteration with recurrence
msg1()
iteration clause
17Iteration clause Multiple messages
msg1() for i 1 to 10 myB.msg2() myC.
meg3()
equal iteration clauses
18Creation
new created instance
create message with optional parameter
for initialization. Note that use of the name
create is a UML convention.
19Languages and create
C
Automatic allocation, or new() operator followed
by constructor call.
Java
new() operator followed by a constructor call.
20Message sequence numbering
classA
classB
classC
21Conditional message
Post
Sale
SalesLineItem
22Mutually exclusive conditional messages
23Collections
24Messages to Multiobjects
25Messages to multiobjects and an element 1
26Design Guidelines
- OO system consists of interacting objects.
- How does one determine the assignment of
responsibilities to various objects?
- There is no unique assignment and hence good
and poor designs, beautiful and ugly
designs, efficient and inefficient designs.
- Design guidelines assist in the derivation of a
good design.
27GRASP Patterns
- GRASP
- General Responsibility Assignment Software
Patterns
- These are best considered as design guidelines
and principles. These could also be considered as
thought patterns useful in software design.
28Guidelines and principles
- We first consider three useful guidelines
and two widely applicable principles
- High cohesion
- Low coupling
29POS Partial Domain Model
Contains
1
1
Used-by
1
1
Describes
1..
Stocks
Contained-in
1
1
Houses
1
Captured-on
Started-by
1
1
Paid-by
1
1
1
1
1
1
Initiated-by
Records-sale-on
1
1
30Expert
- Question
- How does one assign responsibilities ?
- Answer
- Assign a responsibility to an information
expert, i.e. to a class that has the information
needed to fulfill that responsibility.
31Expert Example 1
In POS, some class needs to know the grand total
of a sale. Who should be responsible for knowing
the grand total of a sale ?
32Expert Example 2
- From the model, identify the class that contains
the information needed to obtain the grand total.
- Information needed to obtain the grand total
- Knowledge of all SaleItems
- Sum of their subtotals
- Only a Sale object possesses this knowledge.
- Sale being the information expert, we assign this
responsibility to Sale.
33Partial collaboration diagram 1
Sale
34Expert Example 3
- What information is needed to determine subtotal ?
- We need
- Quantity of each SalesLineItem and its price.
- Quantity is available with SalesLineItem and
price with ProductSpecification.
- Hence SalesLineItem is assigned the
responsibility to compute the subtotal.
35Partial collaboration diagram 2
36Summary Example 4
37Expert Discussion
- Expert guideline used often.
- Fulfillment of a responsibility often requires
interaction amongst several objects (3 in our
example). There are many semi-experts who
collaborate in performing a task.
- Use of the Expert guideline allows us to retain
encapsulation of information.
- It often leads to lightweight classes
collaborating to fulfill a responsibility.
38Expert Disadvantages
- On some occasions the Expert guideline might not
suggest a desirable solution.
- Example Who should save Sale in a database ?
- As all the information to be saved is in the Sale
class, it should be responsible for saving the
information.
- This implies that the Sale class must know about
handling databases. Adding database related
methods to sale class will make it in-cohesive.
- It also violates the separation of concerns
principle.
39Expert Benefits
- Objects use their own information to fulfill
tasks, hence encapsulation is maintained.
- This leads to low coupling.
- Behavior is distributed across cohesive and
lightweight classes.
40Creator 1
- Question
- Who should be responsible for creating an
instance of a class ?
- Answer
- Assign to B the responsibility to create an
object of class A if the following is true
41Creator 2
- B aggregates objects of type A.
- B contains objects of type A.
- B records instances of objects of type A.
- B closely uses objects of type A.
- B has the data passed to A when A is created.
Implication B is an expert in the creation of A.
42Creator Example 1
Who should be responsible for creating a
SalesLineItem ?
43Creator Example 2
- Sale contains many SalesLineItem objects.
- This implies that Sale is a good candidate for
creating a SalesLineItem.
- This leads to the following collaboration diagram.
44Sequence diagram for the creation of
SalesLineItem
45Partial collaboration diagram
Sale
SalesLineItem
46Creator Discussion
- Creator guides the assignment of responsibility
of creating objects.
- Creator suggests that the enclosing container or
aggregate class is a good candidate for the
creation of the object contained.
47Controller 1
- Question
- Who should be responsible for handling system
events ?
Recall that a system event is a high level
event, an external event, generated by a system
actor.
- Answer
- Assign a responsibility to handle a system event
to a controller.
48Controller 2
- A controller is a non-user interface object that
handles system events. Here is a list of
controllers
Façade controller Represents the overall system,
device, or business.
Use case controller Represents an artificial
handler of all events of a use case.
49Controller 3
- window, applet, view, document do not qualify as
controllers. They typically receive system events
and delegate them to a controller.
- Pressing the end of sale button.
50System operations
System
endSale() enterItem() makePayment()
During system behavior analysis, system
operations are assigned to the class System. It
does not imply that the class named System
performs these during design. Instead, during
design, a controller class is assigned to
perform these operations.
51Controller Example (1)
Which object should be responsible for handling
the enterItem() system event message ?
52Controller Example 1
Represents the overall system
Represents overall business
Represents a real world actor
Represents an artificial handler
53Controller Example 2
System operations discovered during analysis
Allocation of system operations during design
During design the system operations, identified
during analysis, are assigned to one or more of
controller classes.
54Controller Discussion 1
- Controllers must be chosen to handle incoming
events.
- Use the same controller class for events of one
use case. This allows maintenance of the state of
a use case.
- Do not assign too much responsibility to a
controller. A controller should delegate to other
objects work that needs to be done while
coordinating an activity.
55Controller Discussion 2
- Façade controllers are suitable when there are
only a few system events.
- They are also useful when it is not possible to
redirect system events to other controllers as,
for example, in a message processing system.
- Selecting a use case controller leads to a
different controller for each use case. This
controller is not a domain object. For example,
for Buy items use case one might construct a
BuyItemsHandler class.
56Controller Discussion 3
- When an existing controller becomes too large,
one may choose a use case controller. This will
likely help in maintaining low coupling and high
cohesion.
- Corollary External interfacing objects should
not have the responsibility for handling system
events. Instead, these should be handled in the
domain layer objects as opposed to being handled
in application layer objects.
57Bloated controller
- Signs of a bloated controller
- There is only one controller receiving all system
events.
- The controller performs all tasks itself without
delegating any task to other objects.
- A controller has many attributes and maintains
significant information about the domain.
- A controller duplicates information found in
other objects.
58Avoiding bloated controller
- Add more controllers. If necessary, use
role-controllers and use-case controllers.
- An airline reservation system may contain the
following controllers
59Presentation (Interface) Layer 1
- Avoid using presentation layer to handle system
events.
- Use of domain layer objects to handle system
events is preferred.
- Example
- Assume that POS application has a window that
displays sale information and captures cashiers
operations. Suppose that a Java applet displays
the window. Let us see how the presentation and
domain layers can be coupled.
60Sample GUI for Point of Sale Terminal
_
x
61Sample course of events
62Sample course of events(2)
Actor
System
63Presentation layer 2
SaleJFrame
Sale
POST
64Presentation layer 3
- SaleJFrame passes on the enterItem() message to
the domain layer.
- It does not get involved in the processing of
this message.
- Thus, business processing logic is in a domain
object, not in the presentation object.
- Presentation layer objects have lower opportunity
for re-use due to their coupling with the
environment.
65Presentation layer undesirable coupling 4
Business logic embedded in presentation layer.
SaleJFrame
Presentation layer
Domain layer
66Presentation layer 5
- Some applications do not have a user interface.
They receive messages from an external system.
For example, LDAP (Light Weight Directory
Protocol) might receive a message from a CGI
script.
- In these cases the messages is encoded in a
stream or as a CORBA message.
67Presentation layer 6
- In applications with windows, the window might
choose who the controller will be.
- Different windows may collaborate with different
controllers.
- However, in a message handling application, the
Command design pattern is useful.
68Low coupling
- How to achieve low dependency and increased
reuse?
- A class with high coupling is undesirable because
- Changes in related classes force local changes.
- This class is harder to understand in isolation.
- This class is harder to reuse because its use
requires the inclusion of all classes it is
dependent upon.
69Low coupling Example (1)
Consider the following partial conceptual model
What class should be responsible for creating an
instance of Payment ?
70Low coupling Example 1
One solution is to let POST create an instance of
Payment and pass a reference this Payment to
Sale. This solution is suggested as POST records
a Payment.
71Low coupling Example 3
Another solution is to let Sale create
an instance of Payment.
Which of the two solutions is preferable from
the point of view of coupling?
72Low coupling Discussion 1
- Encourages assigning a responsibility to keep
coupling low.
- Supports design of relatively independent, hence
more reusable, classes.
- Reusable classes have a positive effect on
productivity, i.e. may lead to higher
productivity.
- However, the quest for low coupling to achieve
reusability in a future (mythical!) project may
lead to increased project cost.
73Low coupling Discussion 2
- It is important for the designer to assess the
current level of coupling and attempt to reduce
it if it is likely to cause problems.
- It is important to note that a moderate degree of
coupling between classes is normal. After all an
OO application is a collection of communicating
objects!
74High cohesion
- Question
- How to keep design complexity manageable.
- Answer
- Assign responsibilities while maintaining high
cohesion.
75High cohesion Example 1
- Creation of a Payment can be assigned to POST as
it records a payment in real world. This is
suggested by the guidelines associated with
Creator.
- This is acceptable. However, if this logic is
applied in several other similar situations, more
and more work is likely to be assigned to one
class.
- This might lead to an in-cohesive class.
76High cohesion Example 2
- For example, if there are 50 system operations,
and POST does some work related to each, the POST
will be a large incohesive class.
- In contrast, a design that lets Sale create
Payment, supports higher cohesion in POST.
- This design supports both high cohesion and low
coupling and hence is preferred over the first
one.
77Interaction diagrams and system events
- We now consider two use cases and their
associated events
- Buy items
- enterItem
- endSale
- makePayment
- For each system event we create a collaboration
diagram whose starting message is the system
event message. What should be our controller
class?
78Choosing the controller class
- Choices
- POST or a new class such as RetailSystem
represents the entire system. - Store represents the business.
- Cashier represents a real-world entity.
- BuyItemsHandler represents an artificial
handler. - We select POST as there are only a few system
operations.
79Choosing the controller class
POST or a new class such as RetailSystem
represents the entire system.
Store represents the business.
Cashier represents a real-world entity.
BuyItemsHandler represents an artificial handler.
2. We select POST as there are only a few system
operations.
80System events
We select the POST class to handle system events.
81Interaction diagrams and contracts
- For each contract work through the
responsibilities and post-conditions, and design
message interactions.
- Example
- The enterItem() system operation requires a Sale
to be created in its contract.
- A collaboration diagram that satisfies this state
change
82Partial collaboration diagram enterItem()
POST
Sale
Post-condition If a new sale, Sale was created
(instance creation).
83On the value of post-conditions
- Post-conditions are only an initial estimate of
what must be achieved.
- Thus, treat contracts as a starting point for
determining what must be done.
- New post-conditions might arise during design and
old ones might be found redundant.
- Recall...we are encouraging iterative development!
84Collaboration diagrams and the conceptual model
- Some objects in collaboration diagrams are drawn
from the conceptual model.
- Responsibility assignment depends to some extent
upon information in the conceptual model.
- New concepts might be discovered during design
and previously identified concepts might be
ignored.
85Collaboration diagram enterItem (1)
- Name enterItem
- (upc number, quantity int)
- Responsibilities Enter sale of an item and
- add it to the sale. Display the item
description and price. - Type System
- Cross reference Use cases Buy items
- Exceptions If the UPC is not valid, indicate
that it was an error. -
86Collaboration diagram enterItem (2)
- Pre-condition UPC is known to the system.
-
Post-conditions
- If a new sale, a Sale was created (instance
creation)
- If a new sale, Sale was associated with the POST
(association formed).
- SalesLineItem.quantity was set to quantity
(attribute modification).
- The SalesLineItem was associated with
ProductSpecification based on UPC match
(association formed).
87Collaboration diagram (1)
enterItem(upc,quantity)
POST
Collaboration diagram begins by some object
sending an enterItem() message to an instance of
POST.
88Making a new Sale
- Contract post-conditions related to new Sale
- If a new Sale, a Sale was created (instance
creation). - If a new sale, the new Sale was associated with
the POST (association formed). - POST can be considered as one that records Thus,
POST is a reasonable choice as a creator of Sale.
POST will then also have a reference to this
instance of Sale. - A container SalesLineItem must be created by Sale.
89Collaboration diagram
enterItem(upc,quantity)
1 new sale create()
POST
Sale
1.1 create()
by controller
by creator
an empty collection that will eventually
hold instances of SalesLineItem
Display of the item description and its price is
ignored for now.
90Creating a new SalesLineItem (1)
- More enterItem contract post-conditions
- A SalesLineItem was created (instance creation).
- The SalesLineItem was associated with the Sale
(association formed). - SalesLineItem.quantity was set to quantity
(attribute modification) - The SalesLineItem was associated with a
ProductSpecification (association formed).
91Creating a new SalesLineItem (2)
- Sale contains SalesLineItem objects. Hence Sale
should create SalesLineItem. - SalesLineItem can be associated with Sale by
string it in the container of line items. - POST must pass the quantity to Sale with the
create message. - A makeLineItem message is sent to Sale for it to
create a SalesLineItem.
92Finding a product specification
- It is necessary to retrieve ProductSpecification
based on the UPC of a SalesLineItem. - Question
- Who should have the responsibility for knowing a
ProductSpecification ? - Expert guidelines suggest that ProductCatalog is
a good candidate for this responsibility. -
93Visibility to a ProductCatalog
- Who should send the specification message to the
ProductCatalog to ask for a ProductSpecification
? - We assume that POST and ProductCatalog were
instantiated during the StartUp use case and that
the are connected permanently. - Thus we let POST send the specification message
to ProductCatalog. - Note that POST knows how to get to
ProductCatalog. We say that POST has visibility
to ProductCatalog.
94The enterItem() collaboration diagram
1 new sale create()
enterItem(upc,qty)
3 makeLineItem(spec,qty)
POST
Sale
2 specspecification(upc)
1.1 create()
3.1 create(spec,qty)
Product Catalog
by expert
3.2 add(s))
2.1 specfind(upc)
slSalesLineItem
95Collaboration diagram endSale (1)
- Name endSale()
-
- Responsibilities Record the end of sale and
- display sale total.
- Type System
- Cross reference Use cases Buy items
- Exceptions If a sale is not underway,
indicate that it was an error. -
96Collaboration diagram endSale (2)
- Pre-condition UPC is known to the system.
- Post-conditions
- Sale.isComplete was set to true (attribute
modification). -
97Choosing the controller class
- Who should be responsible for receiving the
endSale message? - We continue to use POST as the controller.
-
98Setting the Sale.isComplete
- Who should be responsible for ensuring the
post-condition? - As Sale knows and maintains the isComplete
attribute, it should have the responsibility of
setting isComplete. -
99Collaboration diagram endSale()
endSale()
1 saleComplete()
POST
Sale
by controller
by expert
100Display of information
- One responsibility in the endSale contract is
that the sale total must be displayed. - Do not use the domain layer objects to
communicate with windows or presentation layer
objects. - Use the Observer pattern.
- Note that Sale must know the total before it can
be displayed!! -
101Computing the sale total-Review
- Who should be responsible form computing the sale
total? ObviouslySale as it is the expert ! - What information is required to compute the total
? - Sub-totals of all SalesLineItem.
- Who should be responsible for computing the
sub-totals? ObviouslySalesLineItem as it is the
expert in this case. - Who has the price for each SalesLineItem?ProductS
pecification. Hence SalesLineItem must
communicate with ProductSpecification to obtain
the price. -
102The Sale total collaboration diagram
by expert
tottotal()
2 stsubtotal()
Sale
sliSalesLineItem
1 for each slinext())
by expert
2.1 prprice()
Sale--total() total0 for each
SalesLineItem.sli tottotsli.subtotal() return
tot
prodSpec Product specification
103Collaboration diagram makePayment (1)
- Name makePayment(amountfloat)
-
- Responsibilities Record the payment, compute
balance, and print a receipt. - Type System
- Cross reference Use cases Buy items
- Exceptions If a sale is not complete,
indicate an error. -
104Collaboration diagram makePayment (2)
- Pre-condition None.
- Post-conditions
- A Payment was created (instance creation)
- Payment.tendered is set to amount (attribute
modification). - The Payment was associated with the Sale
(relationship formed). - The Sale was associated with the Store to add it
to the historical log of completed sales
(relationship formed). -
105Choosing the controller class
- Who should be responsible for receiving the
endSale message? - We continue to use POST as the controller.
-
106Creating Payment
- Who should be responsible for creating an
instance of Payment ? - There are two candidates
- POST
- Sale
- Selecting Sale lightens the workload of Payment.
- Also POST does not need to know about
Payment which leads to lower coupling in POST.
107The makePayment collaboration diagram
by Creator, low coupling
makePayment(cashTendered)
1 makePayment(cashTendered)
POST
Sale
1.1create(cashTendered)
by controller
Payment
108Balance computation collaboration diagram
We have ignored the display of balance.
balbalance()
1 amtamount()
Sale
Payment
Sale is responsible for knowing the balance. It
needs visibility into Payment to ask for cash
tendered. As Sale created Payment it has
visibility into it.
2 ttotal()
109Logging the Sale (1)
- Who should be responsible for knowing all the
logged sales and doing the logging ? - There are two candidates
- Store
- SalesLedger (new idea from basic accounting!)
- As the design grows Store will become incohesive,
hence SalesLedger seems to be a good idea.
110Logging the Sale (2)
- Consider the following post-condition
- The Sale was associated with the Store to add it
to the historical log of completed sales. - This post-condition needs to change if we decide
to use SalesLedger to log the sale. - If we decide to use SalesLedger than contracts
need to be altered to avoid design divergence.
111The logging collaboration diagram
makePayment(cashTendered)
1 makePayment(cashTendered)
POST
sSale
2addSale(s)
1.1create(cashTendered)
by expert
Store
Payment
2.1add(s)
112Collaboration diagram startUp() (1)
- Most systems have a StartUp() use case.
- It is recommended that the collaboration diagram
for startUp be taken up towards the end. - startUp() operation is often dependent on the
programming language and the operating system
used. - A common approach is to create an initial domain
object.
113Collaboration diagram startUp() (2)
- In the initialization method of this initial
object, create other problem domain objects.
public class POSTApplet extends Applet
public void init () post
store.getPOST() private Store store new
Store() private POST post private Sale sale
Here, Store is the initial domain object. It
creates other domain objects.
114Collaboration diagram startUp() (3)
- Name startUp()
-
- Responsibilities Initialize the system
- Type System
- Post-conditions
- Store, POST, ProductCatalog, and
ProductSpecifications created (instance
creation). - ProductCatalog associated with ProductSpecificatio
ns -
115Collaboration diagram startUp() (4)
- Post-conditions
- Store, POST, ProductCatalog, and
ProductSpecifications created (instance
creation). - ProductCatalog associated with ProductSpecificatio
ns - Store associated with POST (association formed).
- POST associated with ProductCatalog (association
formed).
116StartUp collaboration diagram (5)
Reference to the product catalog passed to POST.
create()
2 create(pc)
Store
POST
1.1 create()
1create()
1.2.2 add(ps)
by creator
pcProductCatalog
1.2.1 create(upc,price,description)
psproductSpecification
1.1 loadProdSpec
117Connecting presentation and domain layers(1)
1 create()
2 pgetPOST()POST
create()
POSTApplet
store Store
First the applet creates an instance of Store.
Store in turn creates an instance of POST. Then
the applet requests Store for a reference to the
POST instance.The applet can now send messages
directly to POST as in the next diagram.
118Connecting Presentation layer to the domain layer
(2)
Object Store
Cashier
UPC
Quantity
Cash
Cash
Balance
Presses button
onEnterItem()
Presentation layer
PostApplet
1enterItem(upc,qty)
Domain layer
POST
119Connecting Presentation layer to the domain layer
(3)
Object Store
Cashier
UPC
Quantity
Cash
Cash
Balance
Presses button
onEnterItem()
3 ttotal() float
Presentation layer
PostApplet
1enterItem(upc,qty)
2 no sale salegetSale()Sale
Domain layer
postPOST
saleSale
120Class notation
A class diagram exhibits classes and
their associations used in an application.
Contrast this with a conceptual model which
shows domain concepts and their associations.
A class
121CRC cards
- CRC Class-responsibility-collaboration cards
- Instead of using diagrams to show class
responsibilities and collaboration, CRC cards are
suggested. - These are index cards and one for each class.
- In a team, each person plays the role of one or
more classes and holds the corresponding card(s). - Helpful in group design efforts.
122CRC cards
class name
Responsibility
Collaboration
Order
Order line item
Check if item in stock
Order line item
Determine price
Customer
Check for valid payment
Database interface
Dispatch to delivery address
123Summary
- Collaboration diagrams (notation)
- Design principles and guidelines
- Creation of collaboration diagrams using design
principles and guidelines