You are on page 1of 78

Block II: From analysis to design

Unit 6: Dynamic modelling – from analysis to design

1
 The aim of this unit is to show you how to make the transition from a
software specification consisting of use cases and an analysis structural
model (with classes and associations but no operations), to a design
structural model (with operations assigned to classes), which is ready to
be implemented.

 Dynamic modelling is used to decide upon and document the message


traffic that is intended to implement the system functionality required by
use cases, and results in assigning operations to the classes in the
structural model.
 In this unit you will see how assertions can be used to specify operations
and you will apply a design approach based on the notion of contracts

Note that: All SAQs and Exercises in this unit are required.

2
Section 1: Introduction

 The aim of this unit is to show you how to make the transition from the
analysis of a software solution consisting of use cases and a class
model, indicating what is intended of the software, to a design of how
this solution is going to be implemented, detailing the responsibilities
(operations) of classes in the class model.

 By studying a systematic approach you will gain knowledge of the key


issues that need to be addressed, whether explicitly through models or
implicitly guided by experience.

 From a professional perspective, the key thing to understand is the


issues this unit addresses rather than the particulars of how we address
them.

 In this unit we will assume, for simplicity, that we are dealing with a
layered model and working on the applications layer.

3
 In Object-oriented software development, the objects that you
implement become the software system.
 One way to ensure that a software system performs its intended
functions is based on the concept of contract.
 A form of contract exists when an object sends a message to
another object.
 The sender (client) requests service from receiver (supplier).
 Whenever a service is provided, a contract comes into play:
− the client (caller) expects the supplier to perform the service correctly,
and
− the supplier expects to be asked to perform only those services it
knows how to supply.
 If either of these expectations is not met, the contract has been
broken.

4
 A contract can be expressed in terms of pre- and post
condition for each task in use case diagram.
− Pre-condition: This is the part of the contract the calling method must
agree to.
− Post-condition: This is the part of the contract the called method
agrees to.

 Benefits from identifying roles in terms of clients and


suppliers are:
− Enabling designers to specify the responsibilities of objects more
precisely;
− Allowing clearer software to be built, and, in turn,
− Leading to greater confidence in the correctness of the software.

5
 Design by Contract (DbC) is the process of
developing software based on contract between
objects, where in this process:
 Operations appropriate for each class are
identified, and
 Pre- and post-conditions are specified (i.e. what
each operation expects and should achieve).
−Pre-condition: requiring something from the client object,
which is of benefit to the supplier object;
−Post-condition: requiring something from the supplier
object, which is of benefit to the client object.

6
Contracts to produce quality software

 As you studied before, Constraints on use cases are documented


using pre- and post-conditions, and in class models are documents via
invariants.
 This leads us to introduce the term assertions.
 Assertions are statements that are used for placing constraints on the
relationship between classes.
 In DbC, they may be a precondition, a post-condition or an invariant
 They specify details of the requirements that cannot be represented
graphically.
 In specifying the services the software should provide, assertions
embody the contract between customer and developer by stating what
the customer wants, and hence what the developer must provide.

7
Four main advantages to the DbC approach for adding
assertions:

1. Assertions provide accurate documentation for the implemented


classes so that a programmer knows how to use the classes and
what to expect from them;
2. Provided they are executable, assertions are an important aid to
testing, but without being an obstacle to efficiency;
3. Assertions provide a way of controlling inheritance in which
substitutability and redefinition of methods are allowed;
4. Assertions together with the exception-handling mechanism can
be an important aid to developing mission-critical systems
(provided the programming language has an exception
mechanism).

8
How can DbC help to improve quality?

 DbC complements many of the other tools that the software engineer
uses to improve quality.

 Tools to improve quality could be classified into:


− Static analysis tools: that are used to analyse code to detect defects before
execution such as a compiler that finds all syntax errors.
− Dynamic analysis tools: such as testing, this occupies 40% of total project
effort.
 So in order to improve quality: you need to find defects before execution
and provide testing to ensure the system will work under all
circumstances.
 This is so important to build an error free system especially in what is
known as a critical system.

9
 Critical Systems are software systems
where failure may have catastrophic
consequences such as:
−Loss of life (safety-critical systems),
−Loss of business (business-critical systems) and
−Failure to meet significant objectives (mission-
critical systems).
 It is vital that such systems be as error-free
as possible.

10
 In developing critical systems, the developer will use:

− Formal methods – based on mathematical notations, logic and proof.


− Analysis tools to make the systems as error-free as possible.
− Design by Contract where the most important feature of DbC is allowing the
development of a software system to be traced from requirements through to
code.

 So in general DbC help to improve quality of a software in many


aspects:
− Allows the development of a software system to be traced from requirements
through to code.
− This helps in stating if a correct software system is built in a way that it meets
the contract between client and supplier.
− DbC complements static analysis tools and dynamic tools.

11
Contracts in real world
 In business, contracts are specifications of the obligations of, and benefits to, the
parties involved in an agreement.
 Example: Suppose that you (the client) wish to take advantage of a low-cost
holiday package from a local travel agent (the supplier). The holiday must be paid
for in full at least 1 month in advance of travel, and the payment is non-
refundable. Both you and the travel agent benefit from such a deal but you both
have obligations. These are shown in Table 1.

12
 Example: Imagine that you have set up a dot-com company to
supply email addresses to junk mail companies. You currently
have four million email addresses but your list grows every night.
As you might capture the same email address many times, you
need a way of removing duplicates from your list. You decide that
you need to sort the email addresses; this will enable the
duplicates to appear together, and they can then be removed
easily. Now, you decide to buy an off-the shelf component that will
sort the large number of email addresses quickly. You determine
that you need to:
− sort at least 10 million email addresses at a time  (Precondition)
− you want the sorted list to be output from the component in less than
10 minutes  (Post-condition)

13
 Example: Imagine that you have set up a dot-com company to
supply email addresses to junk mail companies. You currently
have four million email addresses but your list grows every night.
As you might capture the same email address many times, you
decide to buy an off-the shelf component that will sort the large
number of email addresses quickly. This will enable the duplicates
to appear together, and they can then be removed easily. You
determine that you need to sort at least 10 million addresses at a
time (precondition of the sort program), and to be done in less
than 10 minutes (post-condition of the sort program).
 You contact four component ware suppliers, who send description
of their sorting algorithms (components).
 You draw up a table to help you decide which sorting component
to choose .

14
 You can exclude Microsort: It doesn’t satisfy the pre-condition.
 You can exclude ABDC: the service will be achieved in 20 minutes not 10.
 Both offers of AeLPP, and DictoSort are capable of doing more than is required.
 They both have a precondition that is weaker than (contains) the requirement, and
both have a post-condition that is stronger than (is contained within) the requirement.
 Being able to supply a product that satisfies weaker conditions on inputs and
stronger conditions on outputs is very convenient for the client, as it greatly facilitates
reuse.

15
 To weaken a precondition means generalizing the situation in which a
service can be provided.
− In general, this means that it is easier for the client to satisfy the
precondition because there are ‘fewer’ conditions to be satisfied.
 To strengthen a post-condition means making the service that is
requested ‘better’ in terms of time, precision or some other measurable
item.
− The precise notion of ‘better’ is not fixed, but must be considered in
terms of the contract of which the post-condition is part.

 A client’s obligations to constrain inputs provide benefits to a supplier in


that fewer input cases need to be considered.
 A supplier’s obligations to produce outputs satisfying certain constraints
mean that a client can expect to receive a clearly defined service.

16
Contracting, subcontracting and inheritance

 When the client object wants the server object to do


something for it, you can view this relationship as a
contract, with conditions on inputs (preconditions) and
outputs (post-conditions).
 The form of contract should be written as below:
1. A description of the task, activity or operation in question;
2. Precondition: a set of constraints that are assumed to be
true before you can start
3. Post-condition: a set of constraints that must be true
afterwards.

17
Contracting, subcontracting and inheritance

 When we come to examine the idea of subcontracts in software,


we must bear in mind that objects relate to one another in two
basic ways:
1. Through associations (composition, aggregation);
2. Through generalizations (inheritance).
 Therefore, an important relationship must exist between the
operations of a class and the operations of its subclass if the
objects of the subclass are to be substitutable for those of the
parent class.
 This relationship can be expressed in terms of the pre and post-
conditions associated with the equivalent methods in the two
classes.

18
 Constraints on behavior: is the process of translating pre and post-
conditions (from use cases) into your design, for Object Oriented
systems.
− This means you will constrain the behavior of the system.
 A subclass should respect all contracts agreed by superclass.
− If B is a subclass of A, then objB (instance of B class) can be
substituted for objA (instance of A).
 A subclass must neither strengthen the precondition (make the
precondition more restrictive) nor weaken the post-condition (deliver less
service).
 There are three sets of items you should examine to help you finding
post-conditions when identifying the possible operations for a class:
1. Instances of a class (its objects) that have been created or deleted;
2. Instances of associations (links) that have been formed or broken;
3. Attributes that have been modified.

19
Example: The figure shows a class model for the lending of books where
there is a requirement to record both past and current loans.
Describe the contract to borrow a book in terms of objects and links
created. Your answer should differentiate between the pre and the post-
conditions.

Figure: A class model for a lending library

20
Solution: The contract is constrained as follows:

 Precondition:
− There must be an instance of the class LibraryMember that
corresponds to the real-world member;
− There must be an instance of the class Book that corresponds to the
real-world book that the member wants to borrow;
− The instance of the class LibraryMember must be linked to fewer than
3 instances of the class Loan in the role of currentLoans.
 Post-condition:
− A new instance of the class Loan will have been created; the instance of
the class LibraryMember will have been linked to the new instance of
Loan in the role of currentLoans;
− The instance of the class Book will have been linked to the same new
instance of the class Loan.

21
Section 2: Design by contract

Summary of section
In this section we:
 reviewed how assertions are used in classes and operations at the
analysis and design stages of development
 described how using assertions in this way can be seen as expressing a
client–supplier contract between the objects of an object-oriented system
 described how the process of using assertions in this way, called design
by contract (DbC), can be applied during analysis
 examined the notion of a contract, and its benefits and obligations to
clients and suppliers, in both business and software terms
 saw how preconditions and post-conditions must be respected when one
type is a subtype of another
 saw that the behavior of a task or operation can be constrained by
identifying the conditions that must be true before and after the given task
or operation.

22
 Till now you were dealing with static modeling that involve use cases,
activity diagrams and class modeling.

− Use cases describe what a system should do (Required behavior). It did not
say which classes should be responsible for which parts of computation
− Class model identifies classes and its relationship but do not contain
complete list of attributes and operations.

 We need to link between use cases and class modeling, which lead us
to what is known as dynamic modeling.
 Dynamic Modelling shows how the objects interact by sending
messages to implement the required functionality of the software
system.
 You need to take decisions about which classes contain the operations
needed to carry out which parts of the overall use case.

23
 Interaction diagrams are notations representing dynamic
modeling that are used to help make and record decisions
relating to the behavior defined for each class.

 There are two types of interaction diagrams:


1. Sequence diagram
2. Communication (collaboration) Diagram.

 Both are equivalent, and use for the similar purposes but
each has different features as listed in following table.

24
25
Section 3: Starting dynamic modelling

Starting to build a sequence diagram

 When you design the business-model interactions, you have to be aware


that an interaction is triggered by a message from a user interface.

 To construct a sequence diagram, we need to know where the first


message in the use case originates.

 It will normally come from a user interface.

 At this point we are not concerned with any of the details of this interface;
we just need to know that it exists and that a user can initiate a use case
from it, causing a message to be sent to one of the business objects.

26
Section 3: Starting dynamic modelling

Assigning responsibilities in design


◦ Craig Larman has defined a collection of patterns based on guiding design principles
such as encapsulation, low coupling and high cohesion to help designers assign
responsibilities in commonly occurring design scenarios (Larman, 2004). Larman calls
such patterns GRASP, an acronym for general responsibility assignment software
patterns

 GRASP Expert
◦ The GRASP Expert pattern (also known as Information Expert) addresses the
problem of distributing responsibilities for knowing across the system, in
particular for information that should be derived from object properties.

 GRASP Creator
◦ The GRASP Creator pattern is used to assign responsibilities related to the
creation of objects. Its objective is to find a creator that needs to be linked to
the created object, because the creator aggregates, maintains or records, or
contains the created object

27
Building a sequence diagram
1. Begin by looking at interactions implied by use cases.
Consider a use case scenario to be modeled.
2. You need to know where the first message in the use case
originates. (usually user interface).
3. Considering message flow.
− To where the initial message should be sent.
− This implies which class should have this method in its protocol.
4. Use the post-condition of the use cases which reflect how the
system must change.
− Take into consideration the main scenario and the alternative ones.
− It may be helpful to use a pair of object diagrams, showing the
states before and after the operation in question.

28
Sequence-diagram notation
 The objects involved, represented by the rectangles at the top of the
diagram, optionally followed by a colon and a class name, or, for a
generic object, just a colon and a class name.
− For example, objectname, objectName:ClassName and :Classname
are all allowed.
 Messages between the objects, represented by arrows labelled by text
strings.
− A message sent to an object represents a method that the object's class
implements.
 The objects’ lifelines, represented by dashed lines (with time passing
as you move down the page).
 Activation, which indicate when particular objects are ‘active’.
Represented by long rectangles overlaid on objects’ lifelines.
− An object is active, when it is either an operation or waiting completion of an
operation that it has requested another object to do.

29
Figure : One way to check a guest in to a room

30
Note that:
 The solid arrowhead used in the figure indicates a synchronous
message.
− If all messages in a sequence are synchronous, only one object can be computing at
any one time.
− The sender of a message does nothing until the flow of control returns from the
receiver.
− The return of flow of control from the receiver is often not shown, to simplify the
diagram.
 A new activation begins upon receipt of a message, which is indicated
by the message arrow pointing to the top of the activation rectangle.
 An object cannot send a message to another object unless it has a
reference to it. This means either:
− There is a link from the sender to the receiver(associations between classes), or
− The sender has obtained a reference to the receiver during interaction: as the answer
to an earlier message, or as a message argument, or because the sender was
responsible for the creation of the receiver object.

31
Section 3: Starting dynamic modelling

 Procedural interaction: is an interaction in which the


sender of a message is blocked until the receiver of the
message has finished processing.
− This is exactly the same as what is sometimes called
subroutine semantics.
− It is the usual policy when a single thread of control is
allowed.
− If multiple threads are allowed, we might not want the
sender of the message to block, in which case we could
start a concurrent activity.

32
Section 3: Starting dynamic modelling

Example: Construct another sequence diagram for checking jill in to


theRitz, in which the initial message from the user interface is sent to
theRitz. Then complete the sequence diagram by sending the second
message to jill. Use the list of classes and associated methods given in
Table 6. Why must the first message go to a Hotel object rather than a
Guest object?

33
Section 3: Starting dynamic modelling

 The Guest object needs to be identified before that object can be used to
complete the process of checking in, so first message should go to Hotel object.

Figure : Checking in using a Guest object

34
Section 3: Starting dynamic modelling

 A more lightweight approach to modelling how classes interact is the use


of class-responsibility-collaboration cards (CRC).
− The approach is also called a class-responsibility-collaborators model.
 The CRC idea is : a card has three boxes that can be filled in with:
− the name of the card;
− its responsibilities (what data it holds and what it can do);
− its collaborators (other classes it interacts with directly).

Figure : Generic CRC card


35
Section 3: Starting dynamic modelling

Summary of section

 Sequence diagrams are one kind of interaction diagram.


 They are used when moving from a specification to a design as a way of
helping to decide which parts of the overall system behaviour should be
allocated to which classes.
 So far, we have used sequence diagrams only for specific scenarios of
use cases – jill checking in to theRitz rather than aGuest checking in to
aHotel.
 Sometimes a more lightweight approach based on, for example, CRC
cards may be appropriate.
 The key thing is that the appropriate concerns are taken into account

36
 A communication (collaborative) diagram is an object diagram with added
message sends.
 Every message has a multi-stage number (1.1).
 The numbers specify the sequencing, replacing vertical position in a sequence
diagram.

Figure : A communication diagram


37
There are two main differences between
communication diagrams and sequence diagrams:
1. A communication diagram shows in one place all
the links of interest between objects, whereas a
sequence diagram does not.
2. The time-ordering of messages is clear in a
sequence diagram (Time is viewed as running
vertically downwards). However, some form of
numbering is needed in a communication
diagram to show the time-ordering of messages.

38
Figure : Two different sequence diagrams with the same time-ordering of messages

39
Figure : Solving the ambiguity using multi-stage numbering using communication diagram

 Time is represented by the sequential numbering of messages in a


communication diagram and every message has a multi-stage number.
 The numbers specify the sequencing, replacing vertical position in a
sequence diagram.
 Sequence diagrams emphasize the flow of messages from object to object
over time.
 Communication diagrams emphasize the message traffic across the links
in a particular configuration of objects.

40
Message results and parameterized interactions

 In each use cases there may be more than one scenario, the main one,
and the other alternatives. The sequence diagram shows one case.
 If you want to capture all scenarios this will end up with a lot of
diagrams.
 To model interaction diagram for a range of different scenarios use
prototypical interaction style.

 Prototypical interaction style: it is a generic form, where you can


model more than one scenario in the same diagram by using
parameters.
 In this style objects involved have names such as aGuest or theRoom.
 The names for objects are chosen to suggest that the interaction will be
the same whichever guest or room is involved.

41
 You may:
− Use conditional behavior on an interaction diagram (Unit 7); OR
− Construct separate unconditional diagrams for a range of different concrete
classes.
 For example, in the case of the hotel check in, you might show two
diagrams for two attempts at checking in:
− One for jill, who is able to occupy a room.
− One for jack, who is not.

 The advantage of constructing only unconditional diagrams is


that they are easier to understand.
 The disadvantages are that you have to draw more diagrams,
and commonality and differences between the diagrams may
not be evident.

42
 The purpose of sending a message to an object is:
−to request an action;
−to change the internal state of the recipient;
−or to get it to return a value.

 In Object Oriented there are two types of methods:


1. Accessor methods (getters): that do not change
states of objects, it may return answers such as
getOccupant().
2. Mutator methods (setters): that change the states
of objects such as setOccuppant().

43
You can give a name to the value returned by a
message:
 Turn the message name into an assignment
statement as follows: r := findAFreeRoom()
−r refers to the returned object (the message result).
−r is not meant to suggest that the sender is required to
have a local variable called r.
 When to do this?
−When the returned value is subsequently used as a
parameter to other messages.

44
Figure : A generalized sequence diagram for checking in to a hotel

 The above figure shows how the concrete sequence diagram can be generalized
to describe a prototypical interaction.

45
 The identity of each newly arrived guest has been
preserved using g.
 The scenario in the previous figure does not apply:
−In the case where a guest is not known to the
hotel in question (a link between a particular
instance of Hotel and the object g);
−Where there is no room available at the hotel
(if findAFreeRoom() fails).

46
Creation and deletion

 Object-based programs
frequently need to create new
objects.
 In sequence diagrams: Figure
6 shows the creation of an
anonymous Guest object,
apparently by sending the
message newGuest() to a
Guest instance.
 Of course we cannot send
messages to an instance that
does not yet exist.
Figure : Creating and destroying an object in a
sequence diagram

47
Creation and deletion
 In a communication diagram: object creation and destruction are shown
by the special constraints {new} and {destroyed} respectively.

Figure : Object creation in a communication diagram

 Whether a developer has to use a specific delete command will depend on


the target language.
 Java provides garbage collection to remove references that are not used
for a time.

48
Levels of detail
 Sequence and communication diagrams can be drawn at any level of
detail for a software system.

 How to decide? you have to decide either to specify what is required in


just enough detail for a programmer who understands the domain, OR to
spell out in detail how some goal is to be achieved.

 Your job as a designer is to work at a higher level of abstraction.

 Example: the hotel check in scenario led to a requirement for an operation


called findAFreeRoom, which returned a Room object. You could go into
the precise details of how this might work, or you could simply specify the
necessary operation by defining a precondition and a postcondition, and
leave the coding to a programmer.

49
 Problems of adding more details to interaction diagram:
− The diagram may get too big and, therefore, difficult to understand.
− Can easily get details wrong or introduce inconsistencies.

 The uses of interaction diagram is that they can show:


− How a use case is turned into object interactions,
− How a class provides an operation,
− How a component can be used, and
− How a design pattern works.

50
Exercise:
The figure shows a class model for lending books where there is a requirement to
record both past and current loans.
Represent a prototypical in interaction for the borrowing of a book. Draw both a
sequence diagram and a communication diagram that sends the message
borrow(b) to an instance of LibraryMember from aUserInterface, where b is
a reference to the object representing the book that the library member m wants to
borrow. At this point we are not concerned about where the object b came from.

Figure : A class model for a lending library

51
Solution: Sequence diagram

Figure : A generalized sequence diagram for borrowing a book

52
Solution: Communication diagram

Figure : A generalized communication diagram for borrowing a book

53
Exercise:
Draw a communication diagram that is equivalent to sequence diagram of given figure.

Figure : Checking in using a Guest object

54
Solution:

Figure : Checking in communication diagram

55
Summary of Section

This section has introduced communication diagrams as a different kind of interaction diagram
to deal with the dynamic behavior of a software system, and you have seen examples of how to
add detail to your interaction diagrams as follows.

• Communication diagrams provide an alternative notation to sequence diagrams,


emphasizing message routes rather than timing.
• Communication diagrams require a complex numbering system in order to make the actual
sequencing of messages clear.
• Sequence diagrams can be enriched by notation to assign the result of a message to a local
variable.
• Sequence and communication diagrams have different notations relating to the creation and
deletion of objects.
• Sequence and communication diagrams can be drawn at any level of detail for a software
system. They can show how a use case is turned into object interactions, how a class
provides an operation, how a component can be used and how a design pattern works

Sequence diagrams can be drawn at many different levels of detail, ranging from concrete
scenarios about individual objects to general ones operating on prototypical objects.

56
Managing associations

 When you have completed interaction diagrams for ALL


use cases of the system, you will have a rich set of
operations on all the classes.
 By examining the diagrams, you can also see the overall
pattern of message traffic.
 In particular, you can collect information on the directions
of the messages.
−For example, you can see whether Room objects send
messages to Hotel objects, or
−Hotel objects just send messages to Room objects.

57
Managing associations
 If you find an association that is one-way, you can add an arrow to the
association.
 The direction in which an association is used is called its navigability.

 If navigability is not shown, it is assumed that the association must be


navigable in both directions (bidirectional).

Figure : Associations used in a single direction

58
Importance of direction
 In a class diagram, the direction of association shows which
object can send a message to others.
 If no Guest object sends messages to any Room object, there is
no need to implement the association in this direction.
 Each navigability arrow on an association identifies a
dependency.
 In the previous figure:
− Room depends on Guest.
− Hotel depends on both Room and Guest.
− Guest depends on neither Hotel nor Room.
 A bidirectional association introduces a cyclical dependency,
which is harder to maintain.

59
Link manipulation

 When constructing conceptual models drawing


associations between classes was sufficient.
−We did not discuss the representation of associations.

 In this detailed design stage we need to decide how


associations are to be represented and write the
appropriate code.
 Sometimes implemented association depends on
programming language in use.

60
Naming the link-manipulation methods

 The actual implementation of links is best encapsulated within methods


that hide the chosen representation.
− Use association role names to name the links-manipulated
methods, especially if association has a multiplicity > 1.
− Use setter and getter methods with role names, and if there are no
role names use class name as indicator.
 In class diagram, you have to consider link direction when implementing
methods as follows:
− In the case of a unidirectional association, the class from which links
will be navigated should be responsible for those links.
− In the case of a bidirectional association, making the class at one end
of the association responsible for managing the links in both directions
is a way of avoiding the danger of the two ends becoming inconsistent.

61
 The given below figure shows a class model to which we have added
link-handling methods, whose names directly reflect the roles.

Figure : Role names used to name methods

62
Manipulation of association as follows:

1. Favorite association: it is Unidirectional so only represent (favorite)


association based on direction (in source class), in this case in Guest
class with a method named:
setFavourite(Room)
2. Occupant-accommodation association: is bidirectional so methods
should be implemented in both classes using role names as follows:
− In Guest class: setAccommodation(Room);
− In Room class: setOccupant(Guest);
3. Hotel–Guest association is marked as unidirectional, we have
provided methods addGuest and removeGuest only at the Hotel
end; there are no methods provided on Guest to say which hotel is
being used.

63
 In set methods usually you need to send a parameter to change the
object state, the type of parameter based on target class.
 If you have a bidirectional association, there is a consistency
requirement on the two ends.
− If the guest jack is represented as occupying room r23, then r23
must have jack as its occupant.
− If it has any other occupant, the system is in an inconsistent state.

 Implementation is represented as
Guest::setAccommodation();
which means that the method seAccommodation() is method
of Guest class.

64
A sequence diagram for changeRoom(newRoom) use case in hotel system
is presented as shown in the below given figure

Figure : A sequence diagram manipulating links


65
Forks and cascades
 When designing an interaction diagram, sometimes an object needs to
send a message to another object with which it has no direct
associations.
− For example, in the given below figure, Company has an association
with a number of instances of Job, and each Job has an association
with a Person.
− A Company has no direct association with a Person.
 We can implement this as either forks or cascades.

 A fork centralizes control in the sender.

 A cascade delegates responsibility to another object.

Figure : Sending indirect messages

66
 Suppose that the company needs to collect information about the ages of
all its employees.
 There are two ways to design this:

A. Using fork pattern: where Company


can send a message to Job to get
back person. Then send message to
Person to get the age.

In this pattern, the company contacts


two classes directly, using the value
returned from the first message as
parameter for the second one.

Figure : Fork pattern

67
B. Using Cascade pattern:
Company send
getAgeofPerson() to
Job class, where Job class
send another message
getAge() to Person class.
So there is no direct
interaction between
Company and Person.

− A reasonable position is that


Job should need to know
only about the existence of
Person, not particular
Figure : Cascade pattern
attributes such as age.

68
How to choose which to use: Fork or cascade pattern?

 It is better to use guidelines of Law of Demeter, which tends to favor


cascades.
 The goal of it is to reduce coupling which in turn simplify implementation
and subsequent maintenance.
 Law of Demeter allows an object to send messages to:
− any objects communicated as parameters of the current method;
− any new objects that the object has created in the current method;
− any objects to which the object has direct links – its neighbors;
− itself.

 Note that the law does not allow sending messages to objects that
are returned as a result of sending other messages  it does not
prefer forking.

69
In summary: To move toward design and using interaction diagram that
reflect behavior of the system you have to do the following:

1. Start from use cases: take each scenario, in cooperation with class
model to determine methods of each class and scenario to show you
flow of messages, which lead you to build sequence diagram.

2. A most important point, is where the initial message come from,


usually the interface is used to initiate first message.

3. The aim of interaction diagram is to determine exactly all operations


and its classes, you can use association with role names found in
class model, and manipulation them as methods in classes based on
association direction.

70
Exercise
The following figure shows a class model for a Company. For each
association, decide which end should manage the association, and what
methods must be defined.

Figure : A company model

___________________________________________________________
Solution:

71
Exercise
 The figure shows a fragment of a hotel system, extended to give each
Guest a Bill. Suppose we wish to implement a use case
printBill(Guest jack). It has been decided that the user interface
will send the initial message printBill(jack) to the Hotel.
1. Draw two sequence diagrams, showing fork and cascade solutions. For
each solution, list the methods on each class that this use case
requires.

Figure : Hotel with Guests and their Bills

72
Solution

 Since that all associations are bidirectional, the classes will


have the following operations:
− Class Hotel: addGuest(name); and removeGuset(name);
getGuest(name);
− Class Guest: setBill(Guest); getBill(Guest);
− Class Bill: setGuest(Bill); GetGuest(Bill); print()

 You may not need all of these, but it help you when you draw
the sequence diagram.

73
Sequence Diagram - Fork solution

Figure : Fork solution for billing a guest

74
Sequence Diagram - Cascade solution

Figure : Cascade solution for billing a guest

75
Exercise

2. Which of your two solutions would the Law of Demeter exclude, and
why?

Solution
The guidelines identified within the Law of Demeter would exclude the fork
solution, because it involves the Hotel sending the message print( )
to the Bill.
The Bill is not an object known to the Hotel through a permanent
association; it is neither created in this method of the Hotel, nor passed to
the Hotel as a parameter to the current method.

76
Summary of Section

This section has shown examples of the kinds of design decisions that you
might record in your interaction diagrams; these can have a profound
influence on the eventual software system. You have learnt the following:

 The actual implementation of links is best encapsulated within methods that hide
the chosen representation. In the case of a unidirectional association, the class
from which links will be navigated should be responsible for those links. In the
case of a bidirectional association, making the class at one end of the
association responsible for managing the links in both directions is a way of
avoiding the danger of the two ends becoming inconsistent.
 During design you often have to decide how to send messages to an object that
is not known directly. A fork centralises control in the sender, whereas a cascade
delegates responsibility to another object.
 The Law of Demeter offers guidelines on the paths of communication between
objects; these guidelines tend to favour cascades.

77
Unit Summary

On completion of this unit you should be able to:

 explain the benefits of using a design approach based on the idea of


contracts
 make informed choices between different possible designs
 apply some principles that will help you to decide the classes that
should implement system functionality
 use sequence diagrams to show how use cases can be realised in a
class model
 use communication diagrams to show the same information.

78

You might also like