Docsity

Intermediate OOP: Association Classes & Sequence Diagrams, Exercises of Object Oriented Programming

Toggle sidebar
bg1
Aug 2016 edition – for NUS students only
1
[ L4P1]
Object-Oriented Programming: Intermediate Concepts
The analysis process for identifying objects and object classes is recognized
as one of the most difficult areas of object-oriented development.
--Ian Sommerville, in the book ā€˜Software Engineering’
Association classes
At times, there is a need to store additional information about an association. For example, a
Man class and a Woman class linked with a ā€˜married to’ association might also require the date
of marriage to be stored. However, that data is related to the association but not specifically
owned by either the Man object or the Woman object. In such situations, an additional class can
be introduced, e.g. a Marriage class, to store such information. These classes are called
association classes and they are denoted as a connection to an association link using a dashed
line as shown below.
115
Man
[Ch.4]
Woman
Marriage
date
licenseNo
divorce()
Note that while a special notation is used to indicate an association class, there is no special way
to implement an association class. At implementation level, an association class is most likely
implemented as follows.
115
Man
[Ch.4]
Woman
Marriage
date
licenseNo
divorce()
1 1
0..10..1
wife
husband
Composition and aggregation
A composition is an association that represents a strong ā€œwhole-partā€ relationship. When the
ā€œwholeā€ is destroyed, ā€œpartsā€ are destroyed too. UML uses a solid diamond symbol to denote
composition.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12

Partial preview of the text

Download Intermediate OOP: Association Classes & Sequence Diagrams and more Exercises Object Oriented Programming in PDF only on Docsity!

[ L4P1]

Object-Oriented Programming: Intermediate Concepts

The analysis process for identifying objects and object classes is recognized as one of the most difficult areas of object-oriented development. --Ian Sommerville, in the book ā€˜Software Engineering’

Association classes

At times, there is a need to store additional information about an association. For example, a Man class and a Woman class linked with a ā€˜married to’ association might also require the date of marriage to be stored. However, that data is related to the association but not specifically owned by either the Man object or the Woman object. In such situations, an additional class can be introduced, e.g. a Marriage class, to store such information. These classes are called association classes and they are denoted as a connection to an association link using a dashed line as shown below.

115

Man

[Ch.4]

Woman

Marriage date licenseNo divorce()

Note that while a special notation is used to indicate an association class, there is no special way to implement an association class. At implementation level, an association class is most likely implemented as follows.

115

Man

[Ch.4]

Woman

Marriage date licenseNo divorce()

1 1

0..1 0..

husband wife

Composition and aggregation

A composition is an association that represents a strong ā€œwhole-partā€ relationship. When the ā€œwholeā€ is destroyed, ā€œpartsā€ are destroyed too. UML uses a solid diamond symbol to denote composition.

Whole

UML Notation : Composition

Part

Board Square

100

Folder

is a sub-folder of >

In addition, composition also implies that there cannot be cyclical links. In the example above, the notation represents a ā€˜sub-folder’ relationship between two folders while implying that a Folder cannot be a sub-folder of itself. If the diamond is removed, it is no longer a composition relationship and technically, allows a folder to be subfolder of itself.

Aggregation represents a ā€˜container-contained’ relationship. It is a weaker relationship than composition. In UML, a hollow diamond is used to indicate an aggregation.

Container

UML Notation : Aggregation

Contained

Club (^) Person

1..*

The distinction between composition and aggregation is rather blurred. Some practitioners (e.g., Martin Fowler, in his famous book UML Distilled ) advocate not using the aggregation symbol altogether as using it adds more confusion than clarity.

Object interactions

Suppose we are planning to implement a simple minesweeper game that has a text based UI and a GUI. Given below is the OOP design we are considering for the application.

TextUi

Gui

MSLogic Minefield * Cell

Before jumping into coding, we may want to decide if this class structure is able to produce the behavior we want. We also need to decide what methods each class need to have. To make those decisions, we need to analyze the how the objects of these classes will interact with each other. Both class diagrams can object diagrams we encountered in previous handouts can only depict the structure of an OOP design. To depict the behavior, we can use UML sequences diagrams.

A UML sequence diagram captures the interactions between multiple objects for a given scenario.

The following is a sequence diagram (SD) that describes the interactions between the player (an actor) and the TextUi object. Note that newgame and clear x y represent commands typed by the Player on the TextUi.

:TextUi

newgame

Show minefield

loop [ until won or lost ] mark x,y OR clear x,y

Show updated minefield

Show result

This is how we show iterative behavior on a sequence diagram

Player

loop [condition]

These an example of an iterative behavior.

Figure 4. Showing loops in an SD

How does the TextUi object carry out the requests it has received from player? It would need to interact with other objects of the system. Since the MSLogic class is the one that controls the game logic, the TextUi needs to collaborate with MSLogic to fulfill the newgame request. This may be represented by extending the SD as shown below.

8

MS SD – add MS Logic (new)

:TextUi

newgame

show minefield

:MSLogic

newGame()

getHeight()

getWidth()

W

H

Player

Figure 5. TextUi and MSLogic interactions for newgame

In the above diagram, it is assumed that W and H (Width and Height of the minefield, respectively) are the only information TextUi requires to display the minefield to the Player. Note that there could be other ways of doing this.

The MSLogic methods that showed up in this SD are: ļ‚· newGame():void ļ‚· getWidth():int

ļ‚· getHeight():int

The next task focuses on theMS SD – add MS Logic (mark OR clear) mark or clear operations performed until the game is won or lost.

:TextUi

mark x y OR clear x y

Show updated minefield

:MSLogic

markCellAt(x,y) OR clearCellAt(x,y)

getGameState()

gameState

ref get minefield appearance

Show result

loop [until won|lost]

This is how we refer to another SD given elsewhere

Player

Figure 6. Using a ref frame in an SD

This interaction adds the following methods to the MSLogic class

ļ‚· clearCellAt(int x, int y) ļ‚· markCellAt(int x, int y) ļ‚· getGameState() :GAME_STATE (GAME_STATE: READY, IN_PLAY, WON, LOST, …)

Note the use of a ref frame to allow a segment of the interaction to be omitted and detailed in another diagram. Given below is the SD that elaborates on the retrieval of cell appearance from MSLogic. MS SD – add MS Logic (get cell appearance)

:TextUi :MSLogic

getAppearanceOfCellAt(x,y)

cellAppearance

sd get minefield appearance

loop [for all cells]

ā€œ sd

ā€ stands for ā€œsequence

diagramā€. This is the UML way of

labeling an SD

Figure 7. The SD for the ref frame

Correspondingly, the following operation gets added to MSLogic API:

ļ‚· getAppearanceOfCellAt(int,int):CELL_APPEARANCE (CELL_APPEARANCE: HIDDEN, ZERO, ONE, TWO, THREE, …, MARKED, INCORRECTLY_MARKED, INCORRECTLY_CLEARED)

Parameters : x, y coordinates of the cell Preconditions : game state is READY or IN_PLAY. x and y are in 0..(H-1) and 0..(W-1), respectively. Postconditions : Cell at x,y changes state to ZERO, ONE, TWO, THREE, …, EIGHT, or INCORRECTLY_CLEARED Game state changes to IN_PLAY, WON or LOST as appropriate.

Other operations can be specified similarly. Note that preconditions and postconditions can be described as part of the operation ā€˜description’ instead of stating them separately. That is the approach taken by Java method descriptions.

Now, let us look at what other objects and interactions are needed to support the newGame() operation. It is likely that a new Minefield object is created when the newGame() method is called, as depicted in the SD below.

156

creation

Now, what internal behavior is needed to support the newGame() operation? It is likely that we create a new Minefield object when the newGame() operation is called. This is how we show that in an SD.

Also note that we have abstracted away the behavior of the Minefield constructor. We plan to design it at a later stage.

:Minefield

:Logic

newGame () Minefield ()

This is how we show object creation

Activation bar for the constructor

[Ch.4]

Note that the behavior of the Minefield constructor has been abstracted away. It can be designed at a later stage.

To illustrate object deletion in an SD, suppose MSLogic supports a reset() operation.

157

deletion

To illustrate how we show object deletion in an SD, let us assume MSLogic also supports a reset() operation.

Note that in languages such as Java that supports automatic memory management, object deletion is not that important. However, you can still use the above notation to show at which point the object stops being used.

:Logic^ :Minefield

delete

reset ()

Lifeline stops here

[Ch.4]

In languages such as Java that supports automatic memory management, although object deletion is not that important, the above notation can still be used to show the point at which the object ceased to be used.

Moreover, the diagram below assumes that the Minefield object has enough information (i.e. H, W, and mine locations) to create itself.

:Minefield

Minefield ()

:Logic

newGame ()

Aug 2016 edition – for NUS students only

An alternative is to have a ConfigGenerator object that generates a string containing the minefield information as shown below.

Thinking about this interaction further surfaces a problem: Minefield does not have enough information (i.e., H, W, and mine locations) to create itself! Perhaps we can refine the design to have a ConfigGenerator object that generates a string containing the minefield information.

:Minefield

:Logic

Minefield (minefield_config_string)

newGame()

:ConfigGenerator

getMinefieldConfig ()

minefield_config_string

In addition, getWidth(), getHeight(), markCellAt(x,y) and clearCellAt(x,y) can be handled like this.

160

getWidth(), getHeight(), markCellAt(x,y) and clearCellAt(x,y) can be handled like this.

It appears as if MSLogic is simply redirecting operations to other internal components. This is normal for classes that play the role of a ā€œfaƧadeā€ whose main job is to shield the component’s clients from its internal complexities.

:Logic^ :Minefield

getWidth() getWidth()

markCellAt(x,y) markCellAt(x,y)

W

[Ch.4]

How is getGameState() operation supported? Given below are two ways (there could be other ways):

  1. Minefield class knows the state of the game at any time. Logic class retrieves it from the Minefield class as and when required.
  2. Logic class maintains the state of the game at all times.

Here’s the SD for option 1.

161

How is getGameState() operation supported? We have a design choice to make. We have to choose between

  1. Minefield class knows the state of the game at any time. Logic class retrieves it from the Minefield class as and when required.
  2. Logic class maintains the state of the game at all times.
  3. There could be other ways of doing this. Here’s the SD for option 1.

:Logic^ :Minefield

getGameState() getGameState()

gameState

[Ch.4]

Here’s the SD for option 2. Here, assume that the game state is updated after every mark/clear action. Note the use of a nested activation bar.

Aug 2016 edition – for NUS students only

165

To illustrate how we show optional interactions, let us assume Minesweeper supports the ā€˜timing’ feature.

:Logic

markCellAt(x,y)

opt [first move]

start ()

We can design the internal behavior of the whole MSLogic component by using sequence diagrams in this manner.

[Ch.4]

:Timer

Similarly, parallel behavior can be shown using a ā€˜par’ frame (ā€˜par’ frames are not examinable).

166

Parallel behavior

For your information (not examinable), here is the notation to show parallel behavior.

par

[Ch.4]

When designing components, it is not necessary to draw elaborate sequence diagrams for all interactions among objects. They can be done as rough sketches. Draw sequence diagrams only when you are not sure which operations are required by each class, or when you want to verify that your class structure can indeed support the required operations.

Inheritance

Sometimes, it helps to be able to define a new class based on another class. For example, to be able to define an EvaluationReport class based on a Report class so that the EvaluationReport class does not have to duplicate code that is already implemented in the Report class. This can be achieved using the object-oriented concept of inheritance.

UML Notation : Inheritance Report

EvaluationReport

Base class

Derived class

wordCount print()

In the example above, The EvaluationReport inherits the wordCount variable and the print() method from the base class Report.

ļ‚· Other names for Base class: Parent class , Super class ļ‚· Other names for Derived class: Extended class , Child class , Sub class

Applying inheritance concept can result in the common parts among classes being extracted into more general classes. In the example below, Man and Woman behaves the same way for the ā€˜owes money’ association. However, the two classes cannot be simply replaced with a more general class Person because of the need to distinguish between Man and Woman for the

ā€˜marriage’ association. A solution is to add the Person class as a super class and let Man and Woman inherit from Person.

Man owes money > Woman

< owes money

*^ *

< owes money Marriage^ < owes money

Person Man

Woman Marriage

< owes money

1

1

1 1 0..1 0..

0..

0..

Inheritance implies the derived class can be considered as a sub-type of the base class (and the base class is a super-type of the derived class), resulting in an ā€˜is a’ relationship^2 ; for example, in the class diagrams of a Snakes and Ladders board game given below:

ļ‚· SnakeHeadSquare is a Square. ļ‚· SnakeTailSquare is a Square.

Board (^) Square number

100 has

head in^ Snake

tail in

1 1

has^5

SnakeHeadSquare SnakeTailSquare

1

1

SnakeTailSquare too has the attribute ā€œnumberā€, inherited from the super-type.

Substitutability Every instance of a subclass is an instance of the superclass, but not vice-versa. For example, an Academic is an instance of a Staff, but a Staff is not necessarily an instance of an Academic. As a result, inheritance allows substitutability. i.e. wherever an object of the superclass is expected, it can substituted by an object of any of its subclasses. For example, the following code is valid because a SnakeHeadSquare object is substitutable as a Square object.

Square square = new SnakeHeadSquare(); // OK

But the following code is not because a square is declared as a Square type (see above) and therefore its value may or may not be of type SnakeHeadSquare, which is the type expected by variable snakeSquare.

SnakeHeadSquare snakeSquare = square; //Compile error

(^2) Inheritance does not necessarily mean a sub-type relationship exists. However, the two often go hand- in-hand. In this handout, we assume inheritance implies a sub-type relationship.

For example, the Payroll class should not depend on the AdminStaff class because it does not use the arrangeMeeting() method. Instead, it should depend on the SalariedStaff interface.

public class Payroll { //... private void adjustSalaries(AdminStaff adminStaff){ //violates ISP //... }

}

public class Payroll { //... private void adjustSalaries(SalariedStaff staff){ //does not violate ISP //... } }

AdminStaff

<> SalariedStaff

setSalary(int) getSalary() arrangeMeeting()

setSalary(int) getSalary() Payroll

Follows ISP

Violates ISP

Worked examples [Q1] Refine the class diagram model (given in L5P2 handout) so that it uses inheritance.

Organization Country State < isMemberOf < isPartOf

    • (^1) *

< borders

< borders

< borders

  • (^) * *

[A1]

LandArea

Country

< borders

Organization State

< isMemberOf^ <^ isPartOf

[Q2]

Modify the class diagram below so that we can keep track of the grade a Student earned every time he/she reads a module. Here, ā€˜reads’ means taking the module.

Student Module

< is read by

[A2]

It appears that now we are required to store some data (i.e. grade) about an association (i.e. ā€˜is read by’). Note that storing the grade inside the Student or the Module is not appropriate as the data is about a particular association between the two objects. Besides, the Student can read a module multiple times. To tackle this situation, we can introduce a class called Reading to represent the association.

Student Module

< is by *^ *

Reading grade

(^11)

is for >

Based on the new class diagram, a Reading object represents exactly one student reading exactly one Module and the grade he/she obtained for the Module in that reading. A module can have any number of Reading objects associated with it and a Student can have any number of Reading objects. Furthermore, a Student can have multiple Reading objects for the same Module.

Note: Reading class can be shown as an association class too.

[Q3] Create an OO class diagram to represent the following description:

Some modules require other prerequisite modules to be taken first. If two modules cover nearly same material, taking one of them would preclude a student from taking the other. Such modules are said to be mutually exclusive. The reasons or descriptions for preclusion as well as for the prerequisite also need to be captured.

private void init(){ srs1 = new SRS1(); srs2 = new SRS2(); }

// TextDiff and Result are part of the solution (they are not library classes). private boolean compareResults(Result[] results){ TextDiff diff = new TextDiff(); return diff.compare(results); } }

[A4] (a)

Note slight variations in the notation. Unfortunately, no two UML tools draw diagrams exactly alike and apparently, none follow the UML standard precisely. It is better for you to get used to such slight variations.

(b)

Notes: Result is simply a parameter to a method of MRS. It does not indicate a structural relationship between MRS and Result. As far as we can see from the given code, it is merely a dependency. Similarly, TextDiff is just a local variable inside a method, not a structural relationship.

[Q5] Consider the code given below. Draw a class diagram to match the code. Include attributes, operations, visibilities, navigabilities, multiplicities, and dependencies.

class ReportGenerator{ //getInstance always returns a valid Storage object. private Storage storage = Storage.getInstance(); public static void main(){ ReportGenerator generator = new ReportGenerator(); generator.printReport(342); } public void printReport(int reportID){ //getReport(int) returns a Report object. displayReport ( storage.getReport(reportID).getText() ); } private void displayReport(String s){ //call the static method print() of Printer class Printer.print(s); } } [A5] Note how only the link between ReportGenerator and Storage is an association. The other links are merely dependencies because they do not represent structural links between classes. The multiplicity 1 represents the fact that a ReportGenerator will always be linked to exactly one Storage object.