SlideShare una empresa de Scribd logo
1 de 93
OO Design 1
Object Oriented Design
OO Design 2
Object Orientation
 Traditional procedural systems separate
data and procedures, and model these
separately
 Object orientation –views data and
functions together; data abstraction is the
basis
 The purpose of OO design is to define the
classes in the system to be built and their
relationships
OO Design 3
OOA and OOD
 OO techniques can be used in analysis
(requirements) as well as design
 The methods and notations are similar
 In Object Oriented Analysis (OOA) we model the
problem, while in Object Oriented Deisgn (OOD)
we model the solution
 Often OOA structures are subsumed in the
solution domain structures
 The line between OOA and OOD is not fixed
OO Design 4
OOA and OOD…
OO Design 5
OO Concepts
 Encapsulation – grouping of related ideas
into one unit which we can refer to by a
single name
 Eg. procedures, functions, packages
 In OO, object is the unit; encapsulates
state and provides interface to access and
modify
OO Design 6
OO Concepts..
 Information hiding – use encapsulation to
restrict external visibility
 OO encapsulates the data, provides limited
access, visibility
 Information hiding can be provided without
OO – is an old concept
OO Design 7
OO Concepts…
 State retention – functions, procedures do
not retain state; an object is aware of its
past and maintains state
 Identity – each object can be identified and
treated as a distinct entity
 Behavior – state and services together
define the behavior of an object, or how an
object responds
OO Design 8
OO Concepts..
 Messages – through which a sender object
conveys to a target object a request
 For requesting O1
 must have – a handle for O2
 name of the operation
 information on operations that O2 requires
 General format O2.method(args)
OO Design 9
OO Concepts..
 Classes – a class is a stencil from which objects
are created; defines the structure and services. A
class has
 An interface which defines which parts of an object can
be accessed from outside
 Body that implements the operations
 Instance variables to hold object state
 A class defines the attributes and operations
 Objects and classes are different; class is a type,
object is an instance
 State and identity is of objects
OO Design 10
OO Concepts – access
 Operations in a class can be
 Public: accessible from outside
 Private: accessible only from within the class
 Protected: accessible from within the class and
from within subclasses
 There are some constructor and destructor
operations
 Used to modify attributes
OO Design 11
Inheritance
 Inheritance is unique to OO
 not there in function-oriented languages/models
 Inheritance by class B from class A is the facility
by which B implicitly gets the attributes and
operations of A as part of itself
 Attributes and methods of A are reused by B
 When B inherits from A, B is the subclass or
derived class and A is the base class or
superclass
OO Design 12
Inheritance..
 A subclass B generally has a derived part
(inherited from A) and an incremental part
(is new)
 Hence, B needs to define only the
incremental part
 Creates an “is-a” relationship
 objects of type B are also objects of type A
OO Design 13
Inheritance…
OO Design 14
Inheritance…
 The inheritance relationship between classes
forms a class hierarchy
 In models, hierarchy should represent the natural
relationships present in the problem domain
 In a hierarchy, all the common features can be
accumulated in a superclass
 An existing class can be a specialization of an
existing general class – is also called
generalization-specialization relationships
OO Design 15
Hierarchy Class Example
Attributes
Subclass has access to these
Operations
Subclass has access to these
OO Design 16
Inheritance…
 Strict inheritance – a subclass takes all
features of parent class
 Only adds features to specialize it
 Non-strict: when some of the features have
been redefined
 Strict inheritance supports “is-a” cleanly
and has fewer side effects
OO Design 17
Inheritance…
 Single inheritance – a subclass inherits
from only one superclass
 Class hierarchy is a tree
 Multiple inheritance – a class inherits from
more than one class
 Can cause runtime conflicts
 Repeated inheritance - a class inherits from a
class but from two separate paths
OO Design 18
Inheritance and Polymorphism
 Inheritance brings polymorphism, i.e. an object
can be of different types
 An object of type B is also an object of type A
 Hence an object has a static type and a dynamic
type
 Implications on type checking
 Also brings dynamic binding of operations which allows
writing of general code where operations do different
things depending on the type
OO Design 19
Module Level Concepts
 Basic modules are classes
 During design key activity is to specify the
classes in the system being built
 Correctness of design is fundamental
 But design should also be “good” –
efficient, modifiable, stable, …
 Can evaluate a design using coupling,
cohesion, and open-closed principle
OO Design 20
Coupling
 Coupling is an inter-module concept,
captures the strength of interconnection
between modules
 More tightly coupled the modules, the more
they depend on each other, more difficult to
modify one
 Low coupling is desirable for making
systems understandable and modifiable
 In OO, three types of coupling exists –
interaction, component, and inheritance
OO Design 21
Coupling…
 Interaction coupling occurs due to methods
of a class invoking methods of other
classes
 Like calling of functions
 Worst form if methods directly access internal
parts of other methods
 Still bad if methods directly manipulate
variables of other classes
 Passing information through temporary
variables is also bad
OO Design 22
Coupling…
 Least interaction coupling if methods
communicate directly with parameters
 With least number of parameters
 With least amount of information being passed
 With only data being passed
 I.e. methods should pass the least amount
of data, with least number of parameters
OO Design 23
Coupling…
 Component coupling – when a class A has
variables of another class C
 A has instance variables of C
 A has some parameters of type C
 A has a method with a local variable of type C
 When A is coupled with C, it is coupled with
all subclasses of C as well
 Component coupling will generally imply
the presence of interaction coupling also
OO Design 24
Coupling…
 Inheritance coupling – two classes are
coupled if one is a subclass of other
 Worst form – when subclass modifies a
signature of a method or deletes a method
 Coupling is bad even when same signature
but a changed implementation
 Least, when subclass only adds instance
variables and methods but does not modify
any
OO Design 25
Cohesion
 Cohesion is an intra-module concept
 Focuses on why elements are together
 Only elements tightly related should exist together in a
module
 This gives a module clear abstraction and makes it
easier to understand
 Higher cohesion leads to lower coupling – many
interacting elements are in the module
 Goal is to have higher cohesion in modules
 Three types of cohesion in OO – method, class,
and inheritance
OO Design 26
Cohesion…
 Method cohesion – why different code
elements are together in a method (like
cohesion in functional modules)
 Highest form is if each method implements a
clearly defined function with all elements
contributing to implementing this function
 Should be able to state what the module does
by a simple statement
OO Design 27
Cohesion…
 Class cohesion – why different attributes
and methods are together in a class
 A class should represent a single concept with
all elements contributing towards it
 Whenever multiple concepts encapsulated,
cohesion is not as high
 A symptom of multiple concepts – different
groups of methods accessing different subsets
of attributes
OO Design 28
Cohesion…
 Inheritance cohesion – focuses on why
classes are together in a hierarchy
 Two reasons for subclassing

generalization-specialization

reuse
 Cohesion is higher if the hierarchy is for
providing generalization-specialization
OO Design 29
Friday
OO Design 30
Open-closed Principle
 Principle: Classes should be open for
extension but closed for modification
 Behavior can be extended to accommodate
new requirements, but existing code is not
modified
 I.e. allows addition of code, but not modification
of existing code
 Minimizes risk of having existing functionality
stop working due to changes – a very important
consideration while changing code
 Good for programmers as they like writing new
code
OO Design 31
Open-closed Principle…
 In OO this principle is satisfied by using
inheritance and polymorphism
 Inheritance allows creating a new class to
extend behavior without changing the
original class
 This can be used to support the open-
closed principle
 Consider example of a client object which
interacts with a printer object for printing
OO Design 32
Example
OO Design 33
Example..
 Client directly calls methods on Printer1
 If another printer is to be allowed
 A new class Printer2 will be created
 But the client will have to be changed if it wants
to use Printer 2
 Alternative approach
 Have Printer1 a subclass of a general Printer
 For modification, add another subclass Printer 2
 Client does not need to be changed
OO Design 34
Example…
OO Design 35
Liskov’s Substitution Principle
 Principle: Program using object O1 of base
class C should remain unchanged if O1 is
replaced by an object of a subclass of C
 If hierarchies follow this principle, the open-
closed principle gets supported
OO Design 36
Unified Modeling Language (UML)
and Modeling
 UML is a graphical notation useful for OO
analysis and design
 Allows representing various aspects of the
system
 Various notations are used to build different
models for the system
 OOAD methodologies use UML to
represent the models they create
OO Design 37
Modeling
 Modeling is used in many disciplines –
architecture, aircraft building, …
 A model is a simplification of reality
 “All models are wrong, some are useful”
 A good model includes those elements that
have broad effect and omits minor
elements
 A model of a system is not the system!
OO Design 38
Why build models?
 Models help us visualize a system
 Help specify the system structure
 Gives us a template that can guide the
construction
 Document the decisions taken and their
rationale
OO Design 39
Modeling
 Every complex system requires multiple
models, representing different aspects
 These models are related but can be
studied in isolation
 Eg. Architecture view, electrical view,
plumbing view of a building
 Model can be structural, or behavioral
OO Design 40
Views in an UML
 Different views
 A use case view
 A design view
 A process view
 Implementation view
 Deployment view
 We will focus primarily on models for
design
 class diagram, interaction diagram, etc.
OO Design 41
Class Diagrams
 Classes are the basic building blocks of an
OO system as classes are the
implementation units also
 Class diagram is the central piece in an OO
design. It specifies
 Classes in the system
 Association between classes
 Subtype, supertype relationship
OO Design 42
Class Diagram…
 Class itself represented as a box with
name, attributes, and methods
 There are conventions for naming
 If a class is an interface, this can be
specified by <<interface>> stereotype
 Properties of attributes/methods can be
specified by tags between { }
OO Design 43
Class – example
OO Design 44
Generalization-Specialization
 This relationship leads to class hierarchy
 Can be captured in a class diagram
 Arrows coming from the subclass to the
superclass with head touching super
 Allows multiple subclasses
 If specialization is done on the basis of some
discriminator, arrow can be labeled
OO Design 45
Example – class hierarchy
OO Design 46
Association/aggregation
 Classes have other relationships
 Association: when objects of a class need
services from other objects
 Shown by a line joining classes
 Multiplicity can be represented
 Aggregation: when an object is composed
of other objects
 Captures part-whole relationship
 Shown with a diamond connecting classes
OO Design 47
Example – association/aggregation
OO Design 48
Interaction Diagrams
 Class diagrams represent static structure of
the system (classes and their relationships)
 Do not model the behavior of system
 Behavioral view
 shows how objects interact for performing
actions (typically a use case)
 Interaction is between objects, not classes
 Interaction diagram in two styles
 Collaboration diagram
 Sequence diagram
 Two are equivalent in power
OO Design 49
Sequence Diagram
 Objects participating in an interaction are
shown at the top
 For each object a vertical bar represents its
lifeline
 Message from an object to another,
represented as a labeled arrow
 If message sent under some condition, it
can be specified in bracket
 Time increases downwards, ordering of
events is captured
OO Design 50
Example – sequence diagramTime
Objects participating in an interaction
OO Design 51
Collaboration diagram
 Also shows how objects interact
 Instead of timeline, this diagram looks more
like a state diagram
 Ordering of messages captured by
numbering them
 Is equivalent to sequence diagram in
modeling power
OO Design 52
Example – collaboration diag
OO Design 53
Other Diagrams
 Class diagram and interaction diagrams
most commonly used during design
 There are other diagrams used to build
different types of models
OO Design 54
State Diagrams
 Dynamic model to represent behavior of an
individual object or a system
 Shows the states of an object and
transitions between them
 Helps understand the object – focus only
on the important logical states
 State diagrams can be very useful for
automated and systematic testing
OO Design 55
State diagram of a stack
push
pop
OO Design 56
Activity Diagrams
 Another method for modeling the dynamic
behavior
 Describes the sequence of activities, and
parallel behavior in a system
 Activity represented by ovals, dependence
shown by inputs/outputs
 Variant of a state diagram – captures the
state of the system and transitions
OO Design 57
Other Diagrams
 Instead of objects/classes, can represent
components, packages, subsystems
 These are useful for developing
architecture structures
 UML is extensible – can model a new but
similar concept by using stereotypes (by
adding <<name>>)
 Tagged values can be used to specify
additional properties, e.g. private,
readonly..
 Notes can be added
OO Design 58
Other symbols
OO Design 59
Design using UML
 Many OOAD methodologies have been
proposed
 They provide some guidelines on the steps
to be performed
 Basic goal is to identify classes, understand
their behavior, and relationships
 Different UML models are used for this
 Often UML is used, methodologies are not
followed strictly
OO Design 60
Design using UML
 Basic steps
 Identify classes, attributes, and operations from
use cases
 Define relationships between classes
 Make dynamic models for key use cases and
use them to refine class diagrams
 Make a functional model and use it to refine the
classes
 Optimize and package
 Class diagrams play the central role; class
definition gets refined as we proceed
OO Design 61
Success Scenario
 Customer read the menu
 Customer places the order
 Order is sent to the kitchen for preparation
 Ordered items are served
 Customer requests for a bill for the order
 Bill is prepared for this order
 Customer is given the bill
 Customer pays the bill
OO Design 62
Restaurant example: Initial classes
OO Design 63
OO Design 64
Restaurant example: a sequence diagram
OO Design 65
Example: Word Count
Problem
 System prompts for the file name; user
enters the file name
 System checks for existence of file
 System reads the words from the file
 Systems prints the count
OO Design 66
Example: Word Count Problem…
History
addWord()
exists()
File
name
getword()
isEof()
Word
string
setstring()
getstring()
Counter
count
increment()
display()
OO Design 67
Example: Word Count Problem…
Read
File
Get
words
Check
For
Uniqueness
Add to
History
Increment
Count
OO Design 68
Monday
 Object Oriented Design
 Covered concepts
 Classes and objects
 Encapsulation
 State, behavior, identity
 Relationships among objects
 Inheritance and polymorphism
 Covered constraints
 Coupling
 Cohesion
 Covered tools
 Class diagrams
 Sequence diagrams
OO Design 69
Metrics
 Weighted Methods per Class (WMC)
 Complexity of a class depends on number of
classes and their complexity
 Suppose class C has methods M1, M2, …, Mn
 Suppose complexity of methods is c1, c2…
determined by some functional complexity metric
 WMC = Σ ci

If the complexity of each method is considered 1,
WMC gives the total number of methods in the class
 Large WMC might mean that the class is more
fault-prone
OO Design 70
Metrics…
 The deeper a class is in a class hierarchy
 More methods to reuse – larger reuse
potential
 Increased coupling – harder to make change
 Depth of Inheritance (DIT) Tree
 DIT of class C in an inheritance hierarchy
tree is depth from the root class

Shortest path from root to node C
 DIT is significant in predicting fault
proneness
OO Design 71
Metrics…
 Number of Children (NOC)
 Number of immediate subclasses of C
 Evaluates the degree of reuse
 Higher NOC indicates reuse of definitions in
superclass by a larger number of subclasses
 Indicates influence of a class on other elements

Larger influence, more important to get design
correct
 Higher NOC classes are less defect-prone
NOC is only measuring structure, not inheritance
OO Design 72
Metrics…
 Coupling Between Classes (CBC)
 Reduces modularity and makes module modification
harder
 CBC = Number of classes to which this class is
coupled

Two classes are coupled if methods of one use methods or
instance variables of other
 Can be determined from code

There are indirect forms of coupling that cannot be statically
determined (e.g., pointers)
 Can predict fault proneness of classes, particular user
interface classes
OO Design 73
Metrics…
 Response for a Class (RFC)
 The total number of methods that can be invoked from
an object of this class
 RFC of C is cardinality of the response set for a class

Set of all methods that can be invoked if a message is sent to
an object of this class
 All methods of C as well as other classes the methods of C send
messages

Even if CBC of a class is 1, RBC may be high
 Captures the strength of connections
 Harder to test classes with high RFC
OO Design 74
Metrics…
 Lack of Cohesion in Methods (LCOM)
 Cohesion captures how close are different methods of
a class bound

Two methods form a cohesive pair if they access some
common variables

Form a non-cohesive pair if no common variables

High cohesion is highly desirable
 LCOM is the number of method pairs that are non-
cohesive minus the number of cohesive pairs
 Not significant in predicting fault tolerance of a class
OO Design 75
Metrics Studies Show
 Weighted Methods per Class (WMC)
 Classes tend to have only small number of methods

Classes are simple and provide some specific abstraction and
operations

Only few classes have many methods defined in them
 Has a reasonable correlation with fault-proneness of a class
 Depth of Inheritance (DIT)
 Classes tend to be close to the root

Max DIT around 10

Most classes have DIT of 0 (they are the root)
 Designers tend to keep the number of abstraction levels small,
i.e., they give up reusability in favor of comprehensibility
 Number of Children (NOC)
 Classes generally had a smaller NOC value with most having 0
 Inheritance was not used very heavily
OO Design 76
Metrics Studies Show…
 Coupling Between Classes (CBC)
 Most classes are self contained with CBC = 0

Not coupled with any other class
 Interface objects tend to have higher CBC
 Response for a Class (RFC)
 Most classes tend to invoke a small number of
methods of other classes
 Classes for interface objects tend to have higher RFC
 Lack of Cohesion in Methods (LCOM)
 Not very good at predicting fault-proneness
OO Design 77
Summary
 OO is a newer paradigm, slowly replacing the
functional approach
 OO models both data and functions
 UML is a notation that is used often to model
systems in an OO manner
 UML provides various diagrams for modeling the
structure, dynamic behavior, etc.
 Through UML modeling, design for the system
can be developed
 Metrics can help predict fault proneness of design
OO Design 78
Example OO Design – PIMS
Personal Investment System
 Help investors keep track of their
investments
 Determine rate of return
 On individual investments
 On overall portfolio
 Determine net worth of portfolios
OO Design 79
Example OO Design –
PIMS…
 Investor can have many portfolios
 Portfolio can have many investments
 Investor can invest and withdraw any amount of money at any time
 Dates and amounts are tracked by PIMS
 Get current value of each investment from Web site
 Invest in instruments with fixed interest rates
 Alert to notify pending maturity dates
 Save information about the portfolio
 Edit entered data
 View any portfolio
 Summary
 Detailed
 Provide security
 Determine rate of return
 For each investment
 Overall for each portfolio
 Total investments
 Compute on monthly basis
OO Design 80
Example OO Design – PIMS…
Basic Classes
Class Principle Responsibility
Investment Manages computations regarding total investment.
Portfolio Manages computations regarding a Portfolio.
Security Manages computations related to a security.
Transaction Manages computations and stores attributes related to a transaction.
GUI Manages the Graphical User Interface.
NetLoader Manages downloading current prices of shares from the Internet.
Current Value
System
Manages current value of shares.
Alerts Manages alerts.
SecurityManager Manages user validation.
DataRepository Manages all file operations. It is an interface between the main
modules and the database (which in our case is done using file
system.)
OO Design 81
Example OO Design – PIMS…
Inheritance Structure
Two kinds of securities
Bank: interest bearing
Shares: trading/dividends
Two kinds of transactions
buy: exchange cash for security
sell: exchange security for cash
OO Design 82
Example OO Design – PIMS…
Aggregation Structure
An investment consists of many portfolios
A portfolio can consist of many different
securities
Many transactions can act on a single
security
OO Design 83
Example OO Design – PIMS…
Class Diagram
Investment
Portfolio
Security
Bank Deposit Shares
Transaction
Debit Credit
1
m
1
m
1
m
OO Design 84
Example OO Design – PIMS…
associations for action Create/Delete/Edit Transaction
OO Design 85
Example OO Design – PIMS…
Class diagram with all classes and associations
OO Design 86
Example OO Design – PIMS…
Basic Actions
Actions
Create/Delete/Rename Portfolio/Security.
Create/Delete/Edit Transactions.
Calculate Net Worth of Investment/Portfolio/ Security.
Calculate Rate of Investment of a security.
Load Current Prices from the Internet.
Check/Set/Delete Alerts.
Validate User.
OO Design 87
Example OO Design – PIMS…
Sequence diagram for principle action Create Portfolio
OO Design 88
Example OO Design – PIMS…
Sequence diagram for principle action Delete Transaction
OO Design 89
Example OO Design – PIMS…
Sequence diagram for action Compute Net Worth of
Investment/Portfolio/Security
OO Design 90
Example OO Design – PIMS…
Sequence diagram for action Compute ROI
OO Design 91
Example OO Design – PIMS…
Sequence diagram for action Load current prices from
the Internet
OO Design 92
Example OO Design – PIMS…
Sequence diagram for action Set/Check/Delete Alerts
OO Design 93
Example OO Design – PIMS…
Sequence diagram for action Validate User

Más contenido relacionado

La actualidad más candente

Line drawing algo.
Line drawing algo.Line drawing algo.
Line drawing algo.Mohd Arif
 
Unit 3 object analysis-classification
Unit 3 object analysis-classificationUnit 3 object analysis-classification
Unit 3 object analysis-classificationgopal10scs185
 
Ecg analysis in the cloud
Ecg analysis in the cloudEcg analysis in the cloud
Ecg analysis in the cloudgaurav jain
 
Distributed Systems Real Life Applications
Distributed Systems Real Life ApplicationsDistributed Systems Real Life Applications
Distributed Systems Real Life ApplicationsAman Srivastava
 
Output primitives in Computer Graphics
Output primitives in Computer GraphicsOutput primitives in Computer Graphics
Output primitives in Computer GraphicsKamal Acharya
 
Seven step model of migration into the cloud
Seven step model of migration into the cloudSeven step model of migration into the cloud
Seven step model of migration into the cloudRaj Raj
 
Naming in Distributed Systems
Naming in Distributed SystemsNaming in Distributed Systems
Naming in Distributed SystemsNandakumar P
 
Middleware and Middleware in distributed application
Middleware and Middleware in distributed applicationMiddleware and Middleware in distributed application
Middleware and Middleware in distributed applicationRishikese MR
 
Requirement specification (SRS)
Requirement specification (SRS)Requirement specification (SRS)
Requirement specification (SRS)kunj desai
 
User datagram protocol (udp)
User datagram protocol (udp)User datagram protocol (udp)
User datagram protocol (udp)Ramola Dhande
 
process management
 process management process management
process managementAshish Kumar
 
Types of Load distributing algorithm in Distributed System
Types of Load distributing algorithm in Distributed SystemTypes of Load distributing algorithm in Distributed System
Types of Load distributing algorithm in Distributed SystemDHIVYADEVAKI
 
Message and Stream Oriented Communication
Message and Stream Oriented CommunicationMessage and Stream Oriented Communication
Message and Stream Oriented CommunicationDilum Bandara
 
Agreement Protocols, distributed File Systems, Distributed Shared Memory
Agreement Protocols, distributed File Systems, Distributed Shared MemoryAgreement Protocols, distributed File Systems, Distributed Shared Memory
Agreement Protocols, distributed File Systems, Distributed Shared MemorySHIKHA GAUTAM
 
Hypermedia messageing (UNIT 5)
Hypermedia messageing (UNIT 5)Hypermedia messageing (UNIT 5)
Hypermedia messageing (UNIT 5)nirmalbj
 

La actualidad más candente (20)

Google App Engine
Google App EngineGoogle App Engine
Google App Engine
 
Line drawing algo.
Line drawing algo.Line drawing algo.
Line drawing algo.
 
Transport layer
Transport layerTransport layer
Transport layer
 
Unit 3 object analysis-classification
Unit 3 object analysis-classificationUnit 3 object analysis-classification
Unit 3 object analysis-classification
 
Ecg analysis in the cloud
Ecg analysis in the cloudEcg analysis in the cloud
Ecg analysis in the cloud
 
Distributed Systems Real Life Applications
Distributed Systems Real Life ApplicationsDistributed Systems Real Life Applications
Distributed Systems Real Life Applications
 
Output primitives in Computer Graphics
Output primitives in Computer GraphicsOutput primitives in Computer Graphics
Output primitives in Computer Graphics
 
Data link layer
Data link layer Data link layer
Data link layer
 
Cocomo model
Cocomo modelCocomo model
Cocomo model
 
Atom and rss
Atom and rssAtom and rss
Atom and rss
 
Seven step model of migration into the cloud
Seven step model of migration into the cloudSeven step model of migration into the cloud
Seven step model of migration into the cloud
 
Naming in Distributed Systems
Naming in Distributed SystemsNaming in Distributed Systems
Naming in Distributed Systems
 
Middleware and Middleware in distributed application
Middleware and Middleware in distributed applicationMiddleware and Middleware in distributed application
Middleware and Middleware in distributed application
 
Requirement specification (SRS)
Requirement specification (SRS)Requirement specification (SRS)
Requirement specification (SRS)
 
User datagram protocol (udp)
User datagram protocol (udp)User datagram protocol (udp)
User datagram protocol (udp)
 
process management
 process management process management
process management
 
Types of Load distributing algorithm in Distributed System
Types of Load distributing algorithm in Distributed SystemTypes of Load distributing algorithm in Distributed System
Types of Load distributing algorithm in Distributed System
 
Message and Stream Oriented Communication
Message and Stream Oriented CommunicationMessage and Stream Oriented Communication
Message and Stream Oriented Communication
 
Agreement Protocols, distributed File Systems, Distributed Shared Memory
Agreement Protocols, distributed File Systems, Distributed Shared MemoryAgreement Protocols, distributed File Systems, Distributed Shared Memory
Agreement Protocols, distributed File Systems, Distributed Shared Memory
 
Hypermedia messageing (UNIT 5)
Hypermedia messageing (UNIT 5)Hypermedia messageing (UNIT 5)
Hypermedia messageing (UNIT 5)
 

Similar a 7 ooad

OOps Interview questions.pdf
OOps Interview questions.pdfOOps Interview questions.pdf
OOps Interview questions.pdfGeekster
 
Synapseindia strcture of dotnet development part 1
Synapseindia strcture of dotnet development part 1Synapseindia strcture of dotnet development part 1
Synapseindia strcture of dotnet development part 1Synapseindiappsdevelopment
 
Object Oriented Design
Object Oriented DesignObject Oriented Design
Object Oriented DesignAravinth NSP
 
SE18_Lec 06_Object Oriented Analysis and Design
SE18_Lec 06_Object Oriented Analysis and DesignSE18_Lec 06_Object Oriented Analysis and Design
SE18_Lec 06_Object Oriented Analysis and DesignAmr E. Mohamed
 
SE_Lec 06_Object Oriented Analysis and Design
SE_Lec 06_Object Oriented Analysis and DesignSE_Lec 06_Object Oriented Analysis and Design
SE_Lec 06_Object Oriented Analysis and DesignAmr E. Mohamed
 
Review oop and ood
Review oop and oodReview oop and ood
Review oop and oodthan sare
 
Top 30 Technical interview questions
Top 30 Technical interview questionsTop 30 Technical interview questions
Top 30 Technical interview questionsSohailSaifi15
 
Ooad lab manual
Ooad  lab manualOoad  lab manual
Ooad lab manualPraseela R
 
Assignment 1 SYD601 2012 rick_danby completed with audio
Assignment 1 SYD601 2012 rick_danby completed with audioAssignment 1 SYD601 2012 rick_danby completed with audio
Assignment 1 SYD601 2012 rick_danby completed with audioRickNZ
 
Object Oriented Analysis and Design
Object Oriented Analysis and DesignObject Oriented Analysis and Design
Object Oriented Analysis and DesignDr. C.V. Suresh Babu
 
The View object orientated programming in Lotuscript
The View object orientated programming in LotuscriptThe View object orientated programming in Lotuscript
The View object orientated programming in LotuscriptBill Buchan
 
Final sdp ppt
Final sdp pptFinal sdp ppt
Final sdp pptnancy_17
 

Similar a 7 ooad (20)

testtesttest
testtesttesttesttesttest
testtesttest
 
6-Design.ppt
6-Design.ppt6-Design.ppt
6-Design.ppt
 
PMSE pdf
PMSE pdfPMSE pdf
PMSE pdf
 
Concepts of oops
Concepts of oopsConcepts of oops
Concepts of oops
 
OOps Interview questions.pdf
OOps Interview questions.pdfOOps Interview questions.pdf
OOps Interview questions.pdf
 
Synapseindia strcture of dotnet development part 1
Synapseindia strcture of dotnet development part 1Synapseindia strcture of dotnet development part 1
Synapseindia strcture of dotnet development part 1
 
Object Oriented Design
Object Oriented DesignObject Oriented Design
Object Oriented Design
 
Object Oriented Design
Object Oriented DesignObject Oriented Design
Object Oriented Design
 
SE18_Lec 06_Object Oriented Analysis and Design
SE18_Lec 06_Object Oriented Analysis and DesignSE18_Lec 06_Object Oriented Analysis and Design
SE18_Lec 06_Object Oriented Analysis and Design
 
SE_Lec 06_Object Oriented Analysis and Design
SE_Lec 06_Object Oriented Analysis and DesignSE_Lec 06_Object Oriented Analysis and Design
SE_Lec 06_Object Oriented Analysis and Design
 
Review oop and ood
Review oop and oodReview oop and ood
Review oop and ood
 
Sda 7
Sda   7Sda   7
Sda 7
 
Top 30 Technical interview questions
Top 30 Technical interview questionsTop 30 Technical interview questions
Top 30 Technical interview questions
 
Ooad lab manual
Ooad  lab manualOoad  lab manual
Ooad lab manual
 
Assignment 1 SYD601 2012 rick_danby completed with audio
Assignment 1 SYD601 2012 rick_danby completed with audioAssignment 1 SYD601 2012 rick_danby completed with audio
Assignment 1 SYD601 2012 rick_danby completed with audio
 
Object Oriented Analysis and Design
Object Oriented Analysis and DesignObject Oriented Analysis and Design
Object Oriented Analysis and Design
 
Oop concepts
Oop conceptsOop concepts
Oop concepts
 
Oops
OopsOops
Oops
 
The View object orientated programming in Lotuscript
The View object orientated programming in LotuscriptThe View object orientated programming in Lotuscript
The View object orientated programming in Lotuscript
 
Final sdp ppt
Final sdp pptFinal sdp ppt
Final sdp ppt
 

Último

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 

Último (20)

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 

7 ooad

  • 1. OO Design 1 Object Oriented Design
  • 2. OO Design 2 Object Orientation  Traditional procedural systems separate data and procedures, and model these separately  Object orientation –views data and functions together; data abstraction is the basis  The purpose of OO design is to define the classes in the system to be built and their relationships
  • 3. OO Design 3 OOA and OOD  OO techniques can be used in analysis (requirements) as well as design  The methods and notations are similar  In Object Oriented Analysis (OOA) we model the problem, while in Object Oriented Deisgn (OOD) we model the solution  Often OOA structures are subsumed in the solution domain structures  The line between OOA and OOD is not fixed
  • 4. OO Design 4 OOA and OOD…
  • 5. OO Design 5 OO Concepts  Encapsulation – grouping of related ideas into one unit which we can refer to by a single name  Eg. procedures, functions, packages  In OO, object is the unit; encapsulates state and provides interface to access and modify
  • 6. OO Design 6 OO Concepts..  Information hiding – use encapsulation to restrict external visibility  OO encapsulates the data, provides limited access, visibility  Information hiding can be provided without OO – is an old concept
  • 7. OO Design 7 OO Concepts…  State retention – functions, procedures do not retain state; an object is aware of its past and maintains state  Identity – each object can be identified and treated as a distinct entity  Behavior – state and services together define the behavior of an object, or how an object responds
  • 8. OO Design 8 OO Concepts..  Messages – through which a sender object conveys to a target object a request  For requesting O1  must have – a handle for O2  name of the operation  information on operations that O2 requires  General format O2.method(args)
  • 9. OO Design 9 OO Concepts..  Classes – a class is a stencil from which objects are created; defines the structure and services. A class has  An interface which defines which parts of an object can be accessed from outside  Body that implements the operations  Instance variables to hold object state  A class defines the attributes and operations  Objects and classes are different; class is a type, object is an instance  State and identity is of objects
  • 10. OO Design 10 OO Concepts – access  Operations in a class can be  Public: accessible from outside  Private: accessible only from within the class  Protected: accessible from within the class and from within subclasses  There are some constructor and destructor operations  Used to modify attributes
  • 11. OO Design 11 Inheritance  Inheritance is unique to OO  not there in function-oriented languages/models  Inheritance by class B from class A is the facility by which B implicitly gets the attributes and operations of A as part of itself  Attributes and methods of A are reused by B  When B inherits from A, B is the subclass or derived class and A is the base class or superclass
  • 12. OO Design 12 Inheritance..  A subclass B generally has a derived part (inherited from A) and an incremental part (is new)  Hence, B needs to define only the incremental part  Creates an “is-a” relationship  objects of type B are also objects of type A
  • 14. OO Design 14 Inheritance…  The inheritance relationship between classes forms a class hierarchy  In models, hierarchy should represent the natural relationships present in the problem domain  In a hierarchy, all the common features can be accumulated in a superclass  An existing class can be a specialization of an existing general class – is also called generalization-specialization relationships
  • 15. OO Design 15 Hierarchy Class Example Attributes Subclass has access to these Operations Subclass has access to these
  • 16. OO Design 16 Inheritance…  Strict inheritance – a subclass takes all features of parent class  Only adds features to specialize it  Non-strict: when some of the features have been redefined  Strict inheritance supports “is-a” cleanly and has fewer side effects
  • 17. OO Design 17 Inheritance…  Single inheritance – a subclass inherits from only one superclass  Class hierarchy is a tree  Multiple inheritance – a class inherits from more than one class  Can cause runtime conflicts  Repeated inheritance - a class inherits from a class but from two separate paths
  • 18. OO Design 18 Inheritance and Polymorphism  Inheritance brings polymorphism, i.e. an object can be of different types  An object of type B is also an object of type A  Hence an object has a static type and a dynamic type  Implications on type checking  Also brings dynamic binding of operations which allows writing of general code where operations do different things depending on the type
  • 19. OO Design 19 Module Level Concepts  Basic modules are classes  During design key activity is to specify the classes in the system being built  Correctness of design is fundamental  But design should also be “good” – efficient, modifiable, stable, …  Can evaluate a design using coupling, cohesion, and open-closed principle
  • 20. OO Design 20 Coupling  Coupling is an inter-module concept, captures the strength of interconnection between modules  More tightly coupled the modules, the more they depend on each other, more difficult to modify one  Low coupling is desirable for making systems understandable and modifiable  In OO, three types of coupling exists – interaction, component, and inheritance
  • 21. OO Design 21 Coupling…  Interaction coupling occurs due to methods of a class invoking methods of other classes  Like calling of functions  Worst form if methods directly access internal parts of other methods  Still bad if methods directly manipulate variables of other classes  Passing information through temporary variables is also bad
  • 22. OO Design 22 Coupling…  Least interaction coupling if methods communicate directly with parameters  With least number of parameters  With least amount of information being passed  With only data being passed  I.e. methods should pass the least amount of data, with least number of parameters
  • 23. OO Design 23 Coupling…  Component coupling – when a class A has variables of another class C  A has instance variables of C  A has some parameters of type C  A has a method with a local variable of type C  When A is coupled with C, it is coupled with all subclasses of C as well  Component coupling will generally imply the presence of interaction coupling also
  • 24. OO Design 24 Coupling…  Inheritance coupling – two classes are coupled if one is a subclass of other  Worst form – when subclass modifies a signature of a method or deletes a method  Coupling is bad even when same signature but a changed implementation  Least, when subclass only adds instance variables and methods but does not modify any
  • 25. OO Design 25 Cohesion  Cohesion is an intra-module concept  Focuses on why elements are together  Only elements tightly related should exist together in a module  This gives a module clear abstraction and makes it easier to understand  Higher cohesion leads to lower coupling – many interacting elements are in the module  Goal is to have higher cohesion in modules  Three types of cohesion in OO – method, class, and inheritance
  • 26. OO Design 26 Cohesion…  Method cohesion – why different code elements are together in a method (like cohesion in functional modules)  Highest form is if each method implements a clearly defined function with all elements contributing to implementing this function  Should be able to state what the module does by a simple statement
  • 27. OO Design 27 Cohesion…  Class cohesion – why different attributes and methods are together in a class  A class should represent a single concept with all elements contributing towards it  Whenever multiple concepts encapsulated, cohesion is not as high  A symptom of multiple concepts – different groups of methods accessing different subsets of attributes
  • 28. OO Design 28 Cohesion…  Inheritance cohesion – focuses on why classes are together in a hierarchy  Two reasons for subclassing  generalization-specialization  reuse  Cohesion is higher if the hierarchy is for providing generalization-specialization
  • 30. OO Design 30 Open-closed Principle  Principle: Classes should be open for extension but closed for modification  Behavior can be extended to accommodate new requirements, but existing code is not modified  I.e. allows addition of code, but not modification of existing code  Minimizes risk of having existing functionality stop working due to changes – a very important consideration while changing code  Good for programmers as they like writing new code
  • 31. OO Design 31 Open-closed Principle…  In OO this principle is satisfied by using inheritance and polymorphism  Inheritance allows creating a new class to extend behavior without changing the original class  This can be used to support the open- closed principle  Consider example of a client object which interacts with a printer object for printing
  • 33. OO Design 33 Example..  Client directly calls methods on Printer1  If another printer is to be allowed  A new class Printer2 will be created  But the client will have to be changed if it wants to use Printer 2  Alternative approach  Have Printer1 a subclass of a general Printer  For modification, add another subclass Printer 2  Client does not need to be changed
  • 35. OO Design 35 Liskov’s Substitution Principle  Principle: Program using object O1 of base class C should remain unchanged if O1 is replaced by an object of a subclass of C  If hierarchies follow this principle, the open- closed principle gets supported
  • 36. OO Design 36 Unified Modeling Language (UML) and Modeling  UML is a graphical notation useful for OO analysis and design  Allows representing various aspects of the system  Various notations are used to build different models for the system  OOAD methodologies use UML to represent the models they create
  • 37. OO Design 37 Modeling  Modeling is used in many disciplines – architecture, aircraft building, …  A model is a simplification of reality  “All models are wrong, some are useful”  A good model includes those elements that have broad effect and omits minor elements  A model of a system is not the system!
  • 38. OO Design 38 Why build models?  Models help us visualize a system  Help specify the system structure  Gives us a template that can guide the construction  Document the decisions taken and their rationale
  • 39. OO Design 39 Modeling  Every complex system requires multiple models, representing different aspects  These models are related but can be studied in isolation  Eg. Architecture view, electrical view, plumbing view of a building  Model can be structural, or behavioral
  • 40. OO Design 40 Views in an UML  Different views  A use case view  A design view  A process view  Implementation view  Deployment view  We will focus primarily on models for design  class diagram, interaction diagram, etc.
  • 41. OO Design 41 Class Diagrams  Classes are the basic building blocks of an OO system as classes are the implementation units also  Class diagram is the central piece in an OO design. It specifies  Classes in the system  Association between classes  Subtype, supertype relationship
  • 42. OO Design 42 Class Diagram…  Class itself represented as a box with name, attributes, and methods  There are conventions for naming  If a class is an interface, this can be specified by <<interface>> stereotype  Properties of attributes/methods can be specified by tags between { }
  • 43. OO Design 43 Class – example
  • 44. OO Design 44 Generalization-Specialization  This relationship leads to class hierarchy  Can be captured in a class diagram  Arrows coming from the subclass to the superclass with head touching super  Allows multiple subclasses  If specialization is done on the basis of some discriminator, arrow can be labeled
  • 45. OO Design 45 Example – class hierarchy
  • 46. OO Design 46 Association/aggregation  Classes have other relationships  Association: when objects of a class need services from other objects  Shown by a line joining classes  Multiplicity can be represented  Aggregation: when an object is composed of other objects  Captures part-whole relationship  Shown with a diamond connecting classes
  • 47. OO Design 47 Example – association/aggregation
  • 48. OO Design 48 Interaction Diagrams  Class diagrams represent static structure of the system (classes and their relationships)  Do not model the behavior of system  Behavioral view  shows how objects interact for performing actions (typically a use case)  Interaction is between objects, not classes  Interaction diagram in two styles  Collaboration diagram  Sequence diagram  Two are equivalent in power
  • 49. OO Design 49 Sequence Diagram  Objects participating in an interaction are shown at the top  For each object a vertical bar represents its lifeline  Message from an object to another, represented as a labeled arrow  If message sent under some condition, it can be specified in bracket  Time increases downwards, ordering of events is captured
  • 50. OO Design 50 Example – sequence diagramTime Objects participating in an interaction
  • 51. OO Design 51 Collaboration diagram  Also shows how objects interact  Instead of timeline, this diagram looks more like a state diagram  Ordering of messages captured by numbering them  Is equivalent to sequence diagram in modeling power
  • 52. OO Design 52 Example – collaboration diag
  • 53. OO Design 53 Other Diagrams  Class diagram and interaction diagrams most commonly used during design  There are other diagrams used to build different types of models
  • 54. OO Design 54 State Diagrams  Dynamic model to represent behavior of an individual object or a system  Shows the states of an object and transitions between them  Helps understand the object – focus only on the important logical states  State diagrams can be very useful for automated and systematic testing
  • 55. OO Design 55 State diagram of a stack push pop
  • 56. OO Design 56 Activity Diagrams  Another method for modeling the dynamic behavior  Describes the sequence of activities, and parallel behavior in a system  Activity represented by ovals, dependence shown by inputs/outputs  Variant of a state diagram – captures the state of the system and transitions
  • 57. OO Design 57 Other Diagrams  Instead of objects/classes, can represent components, packages, subsystems  These are useful for developing architecture structures  UML is extensible – can model a new but similar concept by using stereotypes (by adding <<name>>)  Tagged values can be used to specify additional properties, e.g. private, readonly..  Notes can be added
  • 59. OO Design 59 Design using UML  Many OOAD methodologies have been proposed  They provide some guidelines on the steps to be performed  Basic goal is to identify classes, understand their behavior, and relationships  Different UML models are used for this  Often UML is used, methodologies are not followed strictly
  • 60. OO Design 60 Design using UML  Basic steps  Identify classes, attributes, and operations from use cases  Define relationships between classes  Make dynamic models for key use cases and use them to refine class diagrams  Make a functional model and use it to refine the classes  Optimize and package  Class diagrams play the central role; class definition gets refined as we proceed
  • 61. OO Design 61 Success Scenario  Customer read the menu  Customer places the order  Order is sent to the kitchen for preparation  Ordered items are served  Customer requests for a bill for the order  Bill is prepared for this order  Customer is given the bill  Customer pays the bill
  • 62. OO Design 62 Restaurant example: Initial classes
  • 64. OO Design 64 Restaurant example: a sequence diagram
  • 65. OO Design 65 Example: Word Count Problem  System prompts for the file name; user enters the file name  System checks for existence of file  System reads the words from the file  Systems prints the count
  • 66. OO Design 66 Example: Word Count Problem… History addWord() exists() File name getword() isEof() Word string setstring() getstring() Counter count increment() display()
  • 67. OO Design 67 Example: Word Count Problem… Read File Get words Check For Uniqueness Add to History Increment Count
  • 68. OO Design 68 Monday  Object Oriented Design  Covered concepts  Classes and objects  Encapsulation  State, behavior, identity  Relationships among objects  Inheritance and polymorphism  Covered constraints  Coupling  Cohesion  Covered tools  Class diagrams  Sequence diagrams
  • 69. OO Design 69 Metrics  Weighted Methods per Class (WMC)  Complexity of a class depends on number of classes and their complexity  Suppose class C has methods M1, M2, …, Mn  Suppose complexity of methods is c1, c2… determined by some functional complexity metric  WMC = Σ ci  If the complexity of each method is considered 1, WMC gives the total number of methods in the class  Large WMC might mean that the class is more fault-prone
  • 70. OO Design 70 Metrics…  The deeper a class is in a class hierarchy  More methods to reuse – larger reuse potential  Increased coupling – harder to make change  Depth of Inheritance (DIT) Tree  DIT of class C in an inheritance hierarchy tree is depth from the root class  Shortest path from root to node C  DIT is significant in predicting fault proneness
  • 71. OO Design 71 Metrics…  Number of Children (NOC)  Number of immediate subclasses of C  Evaluates the degree of reuse  Higher NOC indicates reuse of definitions in superclass by a larger number of subclasses  Indicates influence of a class on other elements  Larger influence, more important to get design correct  Higher NOC classes are less defect-prone NOC is only measuring structure, not inheritance
  • 72. OO Design 72 Metrics…  Coupling Between Classes (CBC)  Reduces modularity and makes module modification harder  CBC = Number of classes to which this class is coupled  Two classes are coupled if methods of one use methods or instance variables of other  Can be determined from code  There are indirect forms of coupling that cannot be statically determined (e.g., pointers)  Can predict fault proneness of classes, particular user interface classes
  • 73. OO Design 73 Metrics…  Response for a Class (RFC)  The total number of methods that can be invoked from an object of this class  RFC of C is cardinality of the response set for a class  Set of all methods that can be invoked if a message is sent to an object of this class  All methods of C as well as other classes the methods of C send messages  Even if CBC of a class is 1, RBC may be high  Captures the strength of connections  Harder to test classes with high RFC
  • 74. OO Design 74 Metrics…  Lack of Cohesion in Methods (LCOM)  Cohesion captures how close are different methods of a class bound  Two methods form a cohesive pair if they access some common variables  Form a non-cohesive pair if no common variables  High cohesion is highly desirable  LCOM is the number of method pairs that are non- cohesive minus the number of cohesive pairs  Not significant in predicting fault tolerance of a class
  • 75. OO Design 75 Metrics Studies Show  Weighted Methods per Class (WMC)  Classes tend to have only small number of methods  Classes are simple and provide some specific abstraction and operations  Only few classes have many methods defined in them  Has a reasonable correlation with fault-proneness of a class  Depth of Inheritance (DIT)  Classes tend to be close to the root  Max DIT around 10  Most classes have DIT of 0 (they are the root)  Designers tend to keep the number of abstraction levels small, i.e., they give up reusability in favor of comprehensibility  Number of Children (NOC)  Classes generally had a smaller NOC value with most having 0  Inheritance was not used very heavily
  • 76. OO Design 76 Metrics Studies Show…  Coupling Between Classes (CBC)  Most classes are self contained with CBC = 0  Not coupled with any other class  Interface objects tend to have higher CBC  Response for a Class (RFC)  Most classes tend to invoke a small number of methods of other classes  Classes for interface objects tend to have higher RFC  Lack of Cohesion in Methods (LCOM)  Not very good at predicting fault-proneness
  • 77. OO Design 77 Summary  OO is a newer paradigm, slowly replacing the functional approach  OO models both data and functions  UML is a notation that is used often to model systems in an OO manner  UML provides various diagrams for modeling the structure, dynamic behavior, etc.  Through UML modeling, design for the system can be developed  Metrics can help predict fault proneness of design
  • 78. OO Design 78 Example OO Design – PIMS Personal Investment System  Help investors keep track of their investments  Determine rate of return  On individual investments  On overall portfolio  Determine net worth of portfolios
  • 79. OO Design 79 Example OO Design – PIMS…  Investor can have many portfolios  Portfolio can have many investments  Investor can invest and withdraw any amount of money at any time  Dates and amounts are tracked by PIMS  Get current value of each investment from Web site  Invest in instruments with fixed interest rates  Alert to notify pending maturity dates  Save information about the portfolio  Edit entered data  View any portfolio  Summary  Detailed  Provide security  Determine rate of return  For each investment  Overall for each portfolio  Total investments  Compute on monthly basis
  • 80. OO Design 80 Example OO Design – PIMS… Basic Classes Class Principle Responsibility Investment Manages computations regarding total investment. Portfolio Manages computations regarding a Portfolio. Security Manages computations related to a security. Transaction Manages computations and stores attributes related to a transaction. GUI Manages the Graphical User Interface. NetLoader Manages downloading current prices of shares from the Internet. Current Value System Manages current value of shares. Alerts Manages alerts. SecurityManager Manages user validation. DataRepository Manages all file operations. It is an interface between the main modules and the database (which in our case is done using file system.)
  • 81. OO Design 81 Example OO Design – PIMS… Inheritance Structure Two kinds of securities Bank: interest bearing Shares: trading/dividends Two kinds of transactions buy: exchange cash for security sell: exchange security for cash
  • 82. OO Design 82 Example OO Design – PIMS… Aggregation Structure An investment consists of many portfolios A portfolio can consist of many different securities Many transactions can act on a single security
  • 83. OO Design 83 Example OO Design – PIMS… Class Diagram Investment Portfolio Security Bank Deposit Shares Transaction Debit Credit 1 m 1 m 1 m
  • 84. OO Design 84 Example OO Design – PIMS… associations for action Create/Delete/Edit Transaction
  • 85. OO Design 85 Example OO Design – PIMS… Class diagram with all classes and associations
  • 86. OO Design 86 Example OO Design – PIMS… Basic Actions Actions Create/Delete/Rename Portfolio/Security. Create/Delete/Edit Transactions. Calculate Net Worth of Investment/Portfolio/ Security. Calculate Rate of Investment of a security. Load Current Prices from the Internet. Check/Set/Delete Alerts. Validate User.
  • 87. OO Design 87 Example OO Design – PIMS… Sequence diagram for principle action Create Portfolio
  • 88. OO Design 88 Example OO Design – PIMS… Sequence diagram for principle action Delete Transaction
  • 89. OO Design 89 Example OO Design – PIMS… Sequence diagram for action Compute Net Worth of Investment/Portfolio/Security
  • 90. OO Design 90 Example OO Design – PIMS… Sequence diagram for action Compute ROI
  • 91. OO Design 91 Example OO Design – PIMS… Sequence diagram for action Load current prices from the Internet
  • 92. OO Design 92 Example OO Design – PIMS… Sequence diagram for action Set/Check/Delete Alerts
  • 93. OO Design 93 Example OO Design – PIMS… Sequence diagram for action Validate User