Object-Oriented Software Design: Dr. R. Mall

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 116

Object-Oriented

Software Design (lecture 7)

Dr. R. Mall

1
Organization of this
Lecture
 Brief review of last lecture
 Introduction to object-oriented
concepts
 Object modelling using Unified
Modelling Language (UML)
 Object-oriented software
development and patterns
 Summary

2
Review of Last Lecture
 Last lecture we started
 with an introduction to function-
oriented design.
 We looked at goals of structured
analysis (SA)
 Result of SA (i.e. DFD)

3
Review of Last Lecture
 We looked at DFD modelling
techniques

 We looked at importance of Data


Dictionary

4
Review of Last Lecture
 We looked at balancing a DFD
 During structured design (SD),
transformation of DFD to structure
chart
 Also we discussed few examples of
structured analysis & structured
design

5
Object-oriented Concepts
 Object-oriented (OO) design
techniques are becoming popular:
 Inception in early 1980’s and nearing
maturity.
 Widespread acceptance in industry
and academics
 Unified Modelling Language (UML)
poised to become a standard for
modelling OO systems

6
Object-oriented Concepts
 Basic Mechanisms:
 Objects:
 A real-world entity.
 A system is designed as a set of interacting
objects.
 Consists of data (attributes) and functions
(methods) that operate on data
 Hides organization of internal information
(Data abstraction)
 Examples: an employee, a book etc.

7
Object-oriented Concepts

m8 m7
mi are methods
of the object

m1 m6
Data
m2 m5

Object

m3 m4
Model of an object

8
Object-oriented Concepts
 Class:
 Instances are objects
 Template for object creation
 Sometimes not intended to produce
instances (abstract classes)
 Considered as abstract data type (ADT)
 Examples: set of all employees, different
types of book

9
Object-oriented Concepts
 Methods and message:
 Operations supported by an object
 Means for manipulating the data of
other objects
 Invoked by sending message
 Examples: calculate_salary, issue-
book, member_details, etc.

10
Object-oriented Concepts
 Inheritance:
 Allows to define a new class (derived
class) by extending or modifying existing
class (base class)
 Represents Generalization-
specialization relationship
 Allows redefinition of the existing
methods (method overriding)

11
Object-oriented Concepts
 Multiple Inheritance:
 Subclass can inherit attributes and
methods from more than one base class

 Multiple inheritance is represented by


arrows drawn from the subclass to each of
the base classes

12
Object-oriented Concepts

LibraryMember Base Class LibraryMember Base Class

Derived
Faculty Students Staff Faculty Students Staff
Classes
Multiple
Inheritance

UnderGrad PostGrad Research UnderGrad PostGrad Research

13
Object-oriented Concepts
 Key Concepts:
 Abstraction:
 Consider aspects relevant for certain
purpose
 Suppress non-relevant aspects
 Supported at two levels i.e. class level
where base class is an abstraction &
object level where object is a data
abstraction entity

14
Object-oriented Concepts
 Advantages of abstraction:
 Reduces complexity of software
 Increases software productivity
 It is shown that software
productivity is inversely proportional
to software complexity

15
Object-oriented Concepts
 Encapsulation:
 Objects communicate outside world
through messages
 Objects data encapsulated within its
methods

16
Object-oriented Concepts

m4

m3
m5

m2 Data
m6

m1

Methods

Concept of encapsulation
17
Object-oriented Concepts
 Polymorphism:
 Denotes to poly (many) morphism
(forms)
 Same message result in different
actions by different objects (static
binding)

18
Object-oriented Concepts
 Example of static binding:
 Class Circle{
 private float x, y, radius;
 private int fillType;

 public create ();
 public create (float x, float y, float centre);
 public create (float x, float y, float centre, int
fillType);
 }

19
Object-oriented Concepts
 In this example:
 A class named Circle has three definitions
for create operation

 Without any parameter, default

 Centre and radius as parameter

20
Object-oriented Concepts
 In this example:
 Centre, radius and filltype as parameter

 Depending upon parameters given,


method will be invoked

 Method create is overloaded

21
Object-oriented Concepts
 Dynamic binding:
 In inheritance hierarchy, an object can be
assigned to another object of its ancestor class

 A method call to an ancestor object would


result in the invocation of appropriate method
of object of the derived class

22
Object-oriented Concepts
 Dynamic binding:
 Exact method cannot be known at compile
time

 Dynamically decided at runtime

23
Object-oriented Concepts
 Example of dynamic binding:
 Consider class hierarchy of different
geometric objects
 Now display method is declared in
the shape class and overridden in
each derived class
 A single call to the display method
for each object would take care
displaying appropriate element

24
Object-oriented Concepts

Shape

Circle Rectangle Line

Ellipse Square

Cube

Class hierarchy of geometric objects

25
Object-oriented Concepts

Traditional code Object-oriented code

If (shape == Circle) then Shape.draw();


draw_circle();
else if (shape == Rectangle) then -
draw_rectangle(); -
-
- -
-
-
-

Traditional code and OO code using dynamic binding


26
Object-oriented Concepts
 Advantages of dynamic binding:
 Leads to elegant programming
 Facilitates code reuse and
maintenance
 New objects can be added with
minimal changes to existing objects

27
Object-oriented Concepts
 Composite objects:
 Object containing other objects

 Composition limited to tree hierarchy


i.e. no circular inclusion relation

 Inheritance hierarchy different from


containment hierarchy

28
Object-oriented Concepts
 Composite objects:
 Inheritance hierarchy, different object
types with similar features

 Containment allows construction of


complex objects

29
Object-oriented Concepts
 Genericity:
 Ability to parameterize class definitions
 Example: class stack of different types of
elements such as integer, character and
floating point stack
 Generacity permits to define generic class
stack and later instantiate as required

30
Advantages
of Object-oriented design
 Code and design reuse
 Increased productivity
 Ease of testing & maintenance
 Better understandability
 Its agreed that increased
productivity is chief advantage

31
Advantages
of Object-oriented design
 Initially incur higher costs, but
after completion of some projects
reduction in cost become possible
 Well-established OO methodology
and environment can be managed
with 20-50% of traditional cost
of development

32
Object
modelling using UML
 UML is a modelling language
 Not a system design or
development methodology
 Used to document object-
oriented analysis and design
 Independent of any specific
design methodology

33
Unified Modelling Language
(UML)
 Origin
 In late 1980s and early 1990s
different software development
houses were using different
notations
 Developed in early 1990s to
standardize the large number of
object-oriented modelling notations

34
UML
 Based Principally on
 OMT [Rumbaugh 1991]
 Booch’s methodology[Booch 1991]
 OOSE [Jacobson 1992]
 Odell’s methodology[Odell 1992]
 Shlaer and Mellor [Shlaer 1992]

35
UML

OMT

UML
Booch
OOSE Methodology

Different object modelling techniques in UML

36
UML
 As a Standard
 Adopted by Object Management
Group (OMG) in 1997
 OMG an association of industries
 Promote consensus notations and
techniques
 Used outside software development,
example car manufacturing

37
Why UML is required?
 Model is required to capture only
important aspects
 UML a graphical modelling tool, easy
to understand and construct
 Helps in managing complexity

38
UML diagrams
 Nine diagrams to capture
different views of a system
 Provide different perspectives of
the software system
 Diagrams can be refined to get
the actual implementation of the
system

39
UML diagrams
 Views of a system
 User’s view
 Structural view
 Behavioral view
 Implementation view
 Environmental view

40
UML diagrams

Behavioural View
Structural View - Sequence Diagram
- Class Diagram - Collaboration Diagram
- Object Diagram
- State-chart Diagram
- Activity Diagram
User’s View
-Use Case
Diagram

Implementation View Environmental View


- Component Diagram - Deployment Diagram

Diagrams and views in UML

41
Are all views required?
 NO
 Use case model, class diagram and one
of the interaction diagram for a simple
system
 State chart diagram in case of many
state changes
 Deployment diagram in case of large
number of hardware components

42
Use Case model
 Consists of set of “use cases”
 An important analysis and design
artifact
 Other models must confirm to this
model
 Not really an object-oriented model
 Represents a functional or process
model

43
Use Cases
 Different ways in which system can be used
by the users
 Corresponds to the high-level requirements
 Represents transaction between the user and
the system
 Define behavior without revealing internal
structure of system
 Set of related scenarios tied together by a
common goal

44
Use Cases
 Normally, use cases are independent
of each other
 Implicit dependencies may exist
 Example: In Library Automation
System, renew-book & reserve-book
are independent use cases. But in
actual implementation of renew-book,
a check is made to see if any book has
been reserved using reserve-book

45
Example of
Use Cases
 For library information system
 issue-book
 Query-book
 Return-book
 Create-member
 Add-book, etc.

46
Representation of
Use Cases
 Represented by use case diagram
 Use case is represented by ellipse
 System boundary is represented by
rectangle
 Users are represented by stick
person icon (actor)
 Communication relationship
between actor and use case by line
 External system by stereotype

47
Example of
Use Cases

Play Move

Player Tic-tac-toe game

Use case model

48
Why develop
Use Case diagram?
 Serves as requirements specification
 Users identification helps in
implementing security mechanism
through login system
 Another use in preparing the
documents (e.g. user’s manual)

49
Factoring
Use Cases
 Complex use cases need to be factored
into simpler use cases
 Represent common behavior across
different use cases
 Three ways of factoring
 Generalization
 Includes
 Extends

50
Factoring Using
Generalization

Pay membership fee

Pay through credit card Pay through library pay card

Use case generalization

51
Factoring Using
Includes
<<include>> Common
Base use case
use case

Use case inclusion

Base use case Base use case

<<include>>
<<include>>
<<include>> <<include>>

Base use case Base use case Base use case

Paralleling model 52
Factoring Using
Extends

Base <<extends>> Common


use case use case

Use case extension

53
Hierarchical Organization
of Use Cases
use case 1 use case 3
External users

use case 2

use case 3.1 use case 3.3


Subsystems
use case 3. 2

use case 1 use case 3


Method
use case 2

Hierarchical organization of use cases


54
Use Case Packaging

Accounts
Print
Query balance
Balance sheet

Receive Make
grant payments

Use case packaging

55
Class diagram
 Describes static structure of a system
 Main constituents are classes and their
relationships:
 Generalization
 Aggregation
 Association
 Various kinds of dependencies

56
Class diagram
 Entities with common features, i.e.
attributes and operations
 Classes are represented as solid
outline rectangle with compartments
 Compartments for name, attributes &
operations
 Attribute and operation compartment
are optional for reuse purpose

57
Example of
Class diagram

LibraryMember LibraryMember LibraryMember


Member Name Member Name
Membership Number Membership Number
Address Address
Phone Number Phone Number
E-Mail Address E-Mail Address
Membership Admission Date Membership Admission Date
Membership Expiry Date Membership Expiry Date
Books Issued Books Issued
issueBook( );
findPendingBooks( );
findOverdueBooks( );
returnBook( );
findMembershipDetails( );

Different representations of the LibraryMember class

58
Association Relationship
 Enable objects to communicate with
each other
 Usually binary but more classes can be
involved
 Class can have relationship with itself
(recursive association)
 Arrowhead used along with name,
indicates direction of association
 Multiplicity indicates # of instances

59
Association Relationship

Library Member
1 borrowed by * Book

Association between two classes

60
Aggregation Relationship
 Represent a whole-part relationship
 Represented by diamond symbol at
the composite end
 Cannot be reflexive(i.e. recursive)
 Not symmetric
 It can be transitive

61
Aggregation Relationship

1 * 1
Document Paragraph * Line

Representation of aggregation

62
Composition Relationship

 Life of item is same as the order

1 *
Order Item

Representation of composition

63
Inheritance Relationship

Library
Book

issuable reference

Issuable Reference
Issuable Reference
Single Volume Single Volume
BookSet BookSet
Book Book

Representation of the inheritance relationship

64
Class Dependency

Dependent Class Independent Class

Representation of dependence between class

65
Object diagram

LibraryMember LibraryMember LibraryMember

Mritunjay Mritunjay
B10028 B10028
C-108, Laksmikant Hall C-108, Laksmikant Hall
1119 1119
Mrituj@cse Mrituj@cse
25-02-04 25-02-04
25-03-06 25-03-06
NIL NIL

IssueBook( );
findPendingBooks( );
findOverdueBooks( );
returnBook( );
findMembershipDetails( );

Different representations of the LibraryMember object

66
Interaction diagram
 Models how groups of objects
collaborate to realize some behaviour

 Typically each interaction diagram


realizes behaviour of a single use case

67
Interaction diagram
 Two kinds: Sequence &
Collaboration

 Two diagrams are equivalent but


portrays different perspective

 These diagram play a very important


role in the design process

68
Sequence diagram
 Shows interaction among objects as two-
dimensional chart
 Objects are shown as boxes at top
 If object created during execution then
shown at appropriate place
 Objects existence are shown as
dashed lines (lifeline)
 Objects activeness, shown as
rectangle on lifeline

69
Sequence diagram
 Messages are shown as arrows
 Message labelled with message name
 Message can be labelled with control
information
 Two types of control information:
condition ([]) & an iteration (*)

70
Example of
Sequence diagram
:Library
:Library
:Library Book :Library
Book :Book
Boundary Renewal Member
Register
Controller

renewBook find MemberBorrowing


displayBorrowing
selectBooks bookSelected
* find
[reserved]
[reserved] apology
update
apology

confirm

confirm
updateMemberBorrowing

Sequence Diagram for the renew book use case


71
Collaboration diagram
 Shows both structural and behavioural
aspects
 Objects are collaborator, shown as boxes
 Messages between objects shown as a solid
line
 Message is shown as a labelled arrow
placed near the link
 Messages are prefixed with sequence
numbers to show relative sequencing

72
Example of
Collaboration diagram
6: * find
:Library
Book :Book
[reserved] Register
9: update
8: apology 5: book 10: confirm
Selected
1: renewBook :Library [reserved]
:Library Book 7: apology
Boundary 3: display Renewal
Borrowing Controller

4: selectBooks
2: findMemberBorrowing

12: confirm
:Library
Member

updateMemberBorrowing

Collaboration Diagram for the renew book use case


73
Activity diagram
 New concept, possibly based on event
diagram of Odell [1992]

 Represent processing activity, may not


correspond to methods

 Activity is a state with an internal


action and one/many outgoing
transition

74
Activity diagram
 Can represent parallel activity and
synchronization aspects

 Swim lanes enable to group activities


based on who is performing them

 Example: academic department vs.


hostel

75
Activity diagram
 Normally employed in business process
modelling

 Carried out during requirement analysis


and specification

 Can be used to develop interaction


diagrams

76
Example of
Activity diagram
Academic Section Accounts Section Hostel Office Hospital Department

check
student
records
receive
fees

allot create
hostel hospital
record
register
receive
in
fees
course
conduct
allot medical
room examination

issue
identity card
Activity diagram for student admission procedure at IIT
77
State Chart diagram
 Based on the work of David Harel
[1990]

 Model how the state of an object


changes in its lifetime

 Based on finite state machine (FSM)


formalism

78
State Chart diagram
 State chart avoids problem of state
explosion as in FSM

 Hierarchical model of a system,


represents composite state (nested)

79
State Chart diagram
 Elements of state chart diagram
 Initial State: Filled circle
 Final State: Filled circle inside larger
circle
 State: Rectangle with rounded corners
 Transitions: Arrow between states,
also boolean logic condition (guard)

80
Example of
State Chart diagram
order received
Unprocessed
Order
[reject] checked [accept] checked

Rejected Accepted
Order Order
[some items available]
[some items not processed / deliver
available] processed

[all items
Pending available] Fulfilled
Order newsupply Order

Example: State chart diagram for an order object


81
Object-oriented
Software Design & Patterns
 Objects are identified by examining nouns
in problem description
 Many OOD techniques are proposed by Grady
Booch [1991]
 From requirements specification, initial
model is developed (OOA)
 Analysis model is refined into a design model
 Design model is implemented using OO
concepts

82
Object-oriented
Software Design Process

User interface
Use case Interaction
Issues or GUI
diagram diagram
prototype

Start

SRS document Domain model Class diagram Code

Glossary

83
Domain Modelling
 Representation of concepts or objects
appearing in the problem domain
 Also captures relationships among
objects
 Three types of objects are identified
 Boundary objects
 Entity objects
 Controller objects

84
Boundary Objects
 Interacts with actors
 Includes screens, menus, forms,
dialogs etc.
 Do not perform processing but
validates, formats etc.
 Interface class term used for these in
Java, COM/DCOM & UML

85
Entity Objects
 Hold information such as data tables &
files, e.g. Book, BookRegister

 Many of these are dumb servers

 Responsible for storing data, fetching


data etc.

86
Controller Objects
 Coordinate the activities of a set of
entity objects
 Interface with the boundary objects
 Realizes use case
 Embody most of the logic involved
with the use case realization
 There can be more than one controller

87
Use Case Realization

Boundary 1 Controller Boundary 2

Entity 1 Entity 2 Entity 3

Realization of use case through the collaboration of


Boundary, controller and entity objects

88
Class-Responsibility-
Collaborator(CRC) Cards
 Pioneered by Ward Cunningham and
Kent Beck
 Index cards prepared one each per
class
 Responsibility is written on these
cards
 Responsibility of collaborating object
is also written

89
Class-Responsibility-
Collaborator(CRC) Cards
 Interaction diagrams are developed by
flipping through CRC cards

 Required for complex use cases

 Team members participate to


determine responsibility of classes
involved in the use case realization

90
Example: CRC Cards
Class name

BookRegister

BookRegister BookRegister

BookRegister BookRegister

BookRegister BookRegister

Responsibility Collaborator

CRC card for the BookRegister class

91
Design Patterns
 Standard solutions to commonly
recurring problems
 Provides a good solution to model
 Pattern has four important parts
 The problem
 The context (problem)
 The solution
 The context (solution)

92
Example Pattern
 Expert
 Problem: Which class should be
responsible for doing certain things
 Solution: Assign responsibility to the
class that has the information
necessary to fulfil the required
responsibility

93
Example Pattern
 Creator
 Problem: Which class should be
responsible for creating a new instance
of some class?
 Solution: Assign a class C1 the
responsibility to create class C2 if
 C1 is an aggregation of objects of
type C2
 C1 contains object of type C2

94
Example Pattern
 Controller
 Problem: Who should be responsible
for handling the actor requests?
 Solution: Separate controller object for
each use case.

95
Example Pattern
 Facade
 Problem: How should the services be
requested from a service package?
 Context (problem): A package
(cohesive set of classes), example:
RDBMS interface package
 Solution: A class (DBfacade) can be
created which provides a common
interface to the services of the package

96
Example 1: Tic-Tac-Toe
Computer Game
 A human player and the computer make
alternate moves on a 3 3 square.
 A move consists of marking a previously
unmarked square.
 The user inputs a number between 1
and 9 to mark a square
 Whoever is first to place three
consecutive marks along a straight line
(i.e., along a row, column, or diagonal)
on the square wins.
97
Example 1: Tic-Tac-Toe
Computer Game
 As soon as either of the human player or
the computer wins,
 a message announcing the winner should be
displayed.
 If neither player manages to get three
consecutive marks along a straight line,
 and all the squares on the board are filled up,
 then the game is drawn.
 The computer always tries to win a
game.

98
Example 1: Use Case Model

Play Move

Player Tic-tac-toe game

99
Example 1: Initial and Refined
Domain Model

Board

Initial domain model

PlayMoveBoundary PlayMoveController Board

Refined domain model

100
Example 1: Sequence Diagram

:playMove :playMove
:board
Boundary Controller

acceptMove checkMoveValidity
move
[invalidMove] [invalidMove]
announceInvalidMove
announceInvalidMove
checkWinner
[game over]
[game over] announceResult
announceResult
playMove
checkWinner

[game over] [game over]


announceResult announceResult

displayBoardPositions getBoardPositions

[game not over]


promptNextMove

Sequence Diagram for the play move use case


101
Example 1: Class Diagram

Board PlayMoveBoundary

int position[9]

checkMove Validity announceInvalidMove


checkResult announceResult
playMove displayBoard

Controller

announceInvalidMove
announceResult

102
Example 2: Supermarket Prize
Scheme
 Supermarket needs to develop
software to encourage regular
customers.
 Customer needs to supply his
residence address, telephone
number, and the driving licence
number.
 Each customer who registers is
assigned a unique customer
number (CN) by the computer.
103
Example 2: Supermarket Prize
Scheme
 A customer can present his CN to
the staff when he makes any
purchase.
 The value of his purchase is
credited against his CN.
 At the end of each year, the
supermarket awards surprise gifts
to ten customers who make highest
purchase.
104
Example 2: Supermarket Prize
Scheme
 Also, it awards a 22 carat gold coin
to every customer whose purchases
exceed Rs. 10,000.
 The entries against the CN are reset
on the last day of every year after
the prize winner’s lists are
generated.

105
Example 2: Use Case Model

register
Customer customer Clerk

register
sales

Sales Clerk
select
winners

Supermarket
Prize scheme
Manager

106
Example 2: Initial Domain
Model

SalesHistory CustomerRegister

1 1

* *
SalesRecords CustomerRecord

Initial domain model

107
Example 2: Refined Domain
Model
SalesHistory CustomerRegister

1 1

* *
SalesRecords CustomerRecord

RegisterCustomerBoundary RegisterCustomerController

RegisterSalesBoundary RegisterSalesController

SelectWinnersBoundary SelectWinnersControllers

Refined domain model


108
Example 2: Sequence Diagram for
the Select Winners Use Case
:SelectWinner :SelectWinner :Sales :Sales :Customer :Customer
Boundary Controller History Record Register Record

Select
SelectWinners
Winners
SelectWinners
*computeSales

*browse

[for each winner]


find WinnerDetails [for each winner]
announces
browse

Sequence Diagram for the select winners use case


109
Example 2: Sequence Diagram for
the Register Customer Use Case
:SelectWinner :SelectWinner :Customer :Customer
Boundary Controller Register Record

register
register
checkDuplicate
*match

[duplicate]

showError
generateCIN

create
register :Customer
Record
displayCIN

Sequence Diagram for the register customer use case


110
Example 2: Sequence Diagram for
the Register Sales Use Case

:Register :Register
:Sales
Sales Sales
History
Boundary Controller

RegisterSales registerSales
registerSales

create :Sales
Record

confirm
confirm

Sequence Diagram for the register sales use case

111
Example 2: Sequence Diagram for
the Register Sales Use Case

:Register
:Sales
Sales
History
Boundary

registerSales
RegisterSales

create :Sales
Record

confirm

Refined Sequence Diagram for the register sales use case

112
Example 1: Class Diagram

SalesHistory CustomerRegister

selectWinners findWinnerDetails
registerSales register

1 1

* *
SalesRecords CustomerRecord

salesDetails name
address
computerSales browse
browse checkDuplicate
create create

113
Summary
 We discussed object-oriented
concepts
 Basic mechanisms: Such as objects,
class, methods, inheritance etc.
 Key concepts: Such as abstraction,
encapsulation, polymorphism,
composite objects etc.

114
Summary
 We discussed an important OO language
UML
 Its origin, as a standard, as a model
 Use case representation, its factorisation
such as generalization, includes and extends
 Different diagrams for UML representation
 In class diagram we discussed some
relationships association, aggregation,
composition and inheritance

115
Summary
 Some more diagrams such as
interaction diagrams (sequence and
collaboration), activity diagrams,
state chart diagram
 We discussed OO software
development process and patterns
 In this we discussed some patterns
example and domain modelling

116

You might also like