0% found this document useful (0 votes)
19 views80 pages

Chapter Four Object Oriented Design

The document outlines the principles of object-oriented design (OOD), detailing the representation of software as a set of interacting objects that manage their own state and operations. It discusses the object-oriented design process, characteristics of objects and classes, advantages of OOD, and the use of the Unified Modeling Language (UML) for modeling. Additionally, it covers topics such as inheritance, object communication, and the design of a weather mapping system, illustrating the importance of identifying objects and creating design models.

Uploaded by

herid72018
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views80 pages

Chapter Four Object Oriented Design

The document outlines the principles of object-oriented design (OOD), detailing the representation of software as a set of interacting objects that manage their own state and operations. It discusses the object-oriented design process, characteristics of objects and classes, advantages of OOD, and the use of the Unified Modeling Language (UML) for modeling. Additionally, it covers topics such as inheritance, object communication, and the design of a weather mapping system, illustrating the importance of identifying objects and creating design models.

Uploaded by

herid72018
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

Object-oriented Design

Objectives
 To explain how a software design may be
represented as a set of interacting objects
that manage their own state and operations
 To describe the activities in the object-
oriented design process
 To introduce various models that can be
used to describe an object-oriented design
 To show how the UML may be used to
represent these models
Topics covered
 Objects and object classes
 An object-oriented design process
 Design evolution
Object-oriented development
 Object-oriented analysis, design and programming
are related but distinct.
 OOA is concerned with developing an object model
of the application domain.
 OOD is concerned with developing an object-
oriented system model to implement requirements.
 OOP is concerned with realising an OOD using an
OO programming language such as Java or C++.
Characteristics of OOD
 Objects are abstractions of real-world or system
entities and manage themselves.
 Objects are independent and encapsulate state and
representation information.
 System functionality is expressed in terms of object
services.
 Shared data areas are eliminated. Objects
communicate by message passing.
 Objects may be distributed and may execute
sequentially or in parallel.
Interacting objects
Advantages of OOD
 Easier maintenance. Objects may be
understood as stand-alone entities.
 Objects are potentially reusable components.
 For some systems, there may be an obvious
mapping from real world entities to system
objects.
Objects and object classes
 Objects are entities in a software system
which represent instances of real-world and
system entities.
 Object classes are templates for objects.
They may be used to create objects.
 Object classes may inherit attributes and
services from other object classes.
Objects and object classes

An object is an entity that has a state and a defined set of


operations which operate on that state. The state is represented as a
set of object attributes. The operations associated with the object
provide services to other objects (clients) which request these
services when some computation is required.

Objects are created according to some object class definition. An


object class definition serves as a template for objects. It includes
declarations of all the attributes and services which should be
associated with an object of that class.
The Unified Modeling Language

 Several different notations for describing object-


oriented designs were proposed in the 1980s and
1990s.
 The Unified Modeling Language is an integration of
these notations.
 It describes notations for a number of different
models that may be produced during OO analysis
and design.
 It is now a de facto standard for OO modelling.
Employee object class (UML)

Emp lo yee

n ame: string
address: string
dateOfBirth : Date
emplo yeeNo: in teger
so cialSecurityNo : string
depar tment: Dep t
manager: Employ ee
salar y : in teger
status: {curren t, left, retired}
taxCode: in teger
. ..

jo in ()
leave ()
retire ()
chan geDetails ()
Object communication
 Conceptually, objects communicate by
message passing.
 Messages
• The name of the service requested by the calling object;
• Copies of the information required to execute the service
and the name of a holder for the result of the service.
 In practice, messages are often implemented
by procedure calls
• Name = procedure name;
• Information = parameter list.
Message examples

// Call a method associated with a buffer


// object that returns the next value
// in the buffer
v = circularBuffer.Get () ;

// Call the method associated with a


// thermostat object that sets the
// temperature to be maintained
thermostat.setTemp (20) ;
Generalisation and inheritance
 Objects are members of classes that define
attribute types and operations.
 Classes may be arranged in a class hierarchy
where one class (a super-class) is a generalisation
of one or more other classes (sub-classes).
 A sub-class inherits the attributes and
operations from its super class and may add
new methods or attributes of its own.
 Generalisation in the UML is implemented as
inheritance in OO programming languages.
A generalisation hierarchy
Emp loyee

M an ager Pro grammer

budgetsCo ntro lled p roject


p rogLanguages
dateAp po in ted

Pro ject Dept. Strateg ic


M an ager M an ager M an ager

p rojects dept respo nsibilities


Advantages of inheritance
 It is an abstraction mechanism which may be
used to classify entities.
 It is a reuse mechanism at both the design
and the programming level.
 The inheritance graph is a source of
organisational knowledge about domains
and systems.
Problems with inheritance
 Object classes are not self-contained. they
cannot be understood without reference to
their super-classes.
 Designers have a tendency to reuse the
inheritance graph created during analysis.
Can lead to significant inefficiency.
 The inheritance graphs of analysis, design
and implementation have different functions
and should be separately maintained.
UML associations

 Objects and object classes participate in


relationships with other objects and object classes.
 In the UML, a generalised relationship is indicated
by an association.
 Associations may be annotated with information that
describes the association.
 Associations are general but may indicate that an
attribute of an object is an associated object or that
a method relies on an associated object.
An association model

Emp loy ee Depar tment


is-member-o f

is-managed-by

manages
Man ager
Concurrent objects
 The nature of objects as self-contained
entities make them suitable for concurrent
implementation.
 The message-passing model of object
communication can be implemented directly
if objects are running on separate processors
in a distributed system.
Servers and active objects
 Servers.
• The object is implemented as a parallel process (server)
with entry points corresponding to object operations. If no
calls are made to it, the object suspends itself and waits
for further requests for service.
 Active objects
• Objects are implemented as parallel processes and the
internal object state may be changed by the object itself
and not simply by external calls.
Active transponder object
 Active objects may have their attributes
modified by operations but may also update
them autonomously using internal
operations.
 A Transponder object broadcasts an
aircraft’s position. The position may be
updated using a satellite positioning system.
The object periodically update the position by
triangulation from satellites.
An active transponder object
class Transponder extends Thread {

Position currentPosition ;
Coords c1, c2 ;
Satellite sat1, sat2 ;
Navigator theNavigator ;

public Position givePosition ()


{
return currentPosition ;
}

public void run ()


{
while (true)
{
c1 = sat1.position () ;
c2 = sat2.position () ;
currentPosition = theNavigator.compute (c1, c2) ;
}

} //Transponder
Java threads

 Threads in Java are a simple construct for


implementing concurrent objects.
 Threads must include a method called run()
and this is started up by the Java run-time
system.
 Active objects typically include an infinite
loop so that they are always carrying out the
computation.
An object-oriented design process

 Structured design processes involve


developing a number of different system
models.
 They require a lot of effort for development
and maintenance of these models and, for
small systems, this may not be cost-
effective.
 However, for large systems developed by
different groups design models are an
essential communication mechanism.
Process stages

 Highlights key activities without being tied to


any proprietary process such as the RUP.
• Define the context and modes of use of the
system;
• Design the system architecture;
• Identify the principal system objects;
• Develop design models;
• Specify object interfaces.
Weather system description
• A weather mapping system is required to generate weather maps on a
regular basis using data collected from remote, unattended weather
stations and other data sources such as weather observers, balloons and
satellites.
• Weather stations transmit their data to the area computer in response to a
request from that machine.

• The area computer system validates the collected data and integrates it
with the data from different sources.
• The integrated data is archived and, using data from this archive and a
digitised map database a set of local weather maps is created.
• Maps may be printed for distribution on a special-purpose map printer or
may be displayed in a number of different formats.
System context and models of use

 Develop an understanding of the relationships


between the software being designed and its
external environment
 System context
• A static model that describes other systems in the
environment. Use a subsystem model to show other
systems. Following slide shows the systems around the
weather station system.
 Model of system use
• A dynamic model that describes how the system interacts
with its environment. Use use-cases to show interactions
Layered architecture

Data displaylayer whereobjects are


con cern ed with prep aring and
« subsy stem» p resen ting th e data in a h uman -
Data display readable fo rm

Data arch iv ing layer wh ere objects


« subsy stem» are concerned with storing the data
Data arch iv ing fo r future pro cessin g

Data processinglayer whereobjects


« subsy stem» are con cern ed with ch eck in g an d
Data pro cessing in tegratin g the collected data

Data collectio n layer wh ere objects


« subsy stem» are con cern ed with acquirin g data
Data collectio n fro m remo te sources
Subsystems in the weather mapping system

« subsy stem»
Data collectio n « subsy stem»
Data display

Observer Satellite
User
User M ap
Co mms ininterface
terface disp lay

Weather M ap
statio n Balloo n M ap p rinter

« subsy stem» « subsy stem»


Data pro cessing Data arch iv ing

Data
Data
Data Data sto
storage
rage
checking in tegratio n
M ap sto re Data store
Use-case models

 Use-case models are used to represent each


interaction with the system.
 A use-case model shows the system
features as ellipses and the interacting entity
as a stick figure.
Use-cases for the weather station

Startup

Shutdown

Rep ort

Calibrate

Test
Use-case description

System Weather station


Use-case Report
Actors Weather data collection system, Weather station
Data The w eather station send s a summa ry of the weather data that has been
collected from the instruments in the collection period to the weather data
collection system. The data sent are the maximum minimum and ave rage
ground and air temperatures, the maximum, minimum and av erage air
pressures, the maximum, minimum and ave rage wind speeds, the total
rainfall and th e wind direction as sampled at 5 minute interva ls .
Stimulu s The w eather data collection system establis hes a mod em link w ith the
weather station and reque sts transmi ssion of the data.
Response The summaris ed data is sent to the weather data collection system
Comments Weather stations are usua lly asked to report onc e per hou r but this
frequency may dif fer from one station to the other and may be modified in
future .
Architectural design

 Once interactions between the system and its


environment have been understood, you use this
information for designing the system architecture.
 A layered architecture as discussed in Chapter 11 is
appropriate for the weather station
• Interface layer for handling communications;
• Data collection layer for managing instruments;
• Instruments layer for collecting data.
 There should normally be no more than 7 entities in
an architectural model.
Weather station architecture
Object identification
 Identifying objects (or object classes) is the
most difficult part of object oriented design.
 There is no 'magic formula' for object
identification. It relies on the skill, experience
and domain knowledge of system designers.
 Object identification is an iterative process.
You are unlikely to get it right first time.
Approaches to identification
 Use a grammatical approach based on a natural
language description of the system (used in Hood
OOD method).
 Base the identification on tangible things in the
application domain.
 Use a behavioural approach and identify objects
based on what participates in what behaviour.
 Use a scenario-based analysis. The objects,
attributes and methods in each scenario are
identified.
Weather station description

• A weather station is a package of software controlled


instruments which collects data, performs some data processing
and transmits this data for further processing.
• The instruments include air and ground thermometers, an
anemometer, a wind vane, a barometer and a rain gauge.
• Data is collected periodically.
• When a command is issued to transmit the weather data, the
weather station processes and summarises the collected data.
• The summarised data is transmitted to the mapping computer
when a request is received.
Weather station object classes

 Ground thermometer, Anemometer, Barometer


• Application domain objects that are ‘hardware’ objects
related to the instruments in the system.
 Weather station
• The basic interface of the weather station to its
environment. It therefore reflects the interactions
identified in the use-case model.
 Weather data
• Encapsulates the summarised data from the instruments.
Weather station object classes

WeatherStation WeatherData

identifier airTemper atures


gro un dTemper atures
repo rtWeather ()
windSpeeds
calibrate (instruments)
windDirection s
test ()
p ressures
startup (instruments)
rain fall
sh utdo wn (instruments)
collect ()
summarise ()

Gr o un d An emo met er Baro met er


th ermo met er p ressure
windSpeed
temper ature windDirection h eigh t
test () test ()
test ()
calibrate () calibrate ()
Further objects and object refinement

 Use domain knowledge to identify more objects and


operations
• Weather stations should have a unique identifier;
• Weather stations are remotely situated so instrument
failures have to be reported automatically. Therefore
attributes and operations for self-checking are required.
 Active or passive objects
• In this case, objects are passive and collect data on
request rather than autonomously. This introduces
flexibility at the expense of controller processing time.
Design models

 Design models show the objects and object


classes and relationships between these
entities.
 Static models describe the static structure of
the system in terms of object classes and
relationships.
 Dynamic models describe the dynamic
interactions between objects.
Examples of design models
 Sub-system models that show logical groupings of
objects into coherent subsystems.
 Sequence models that show the sequence of object
interactions.
 State machine models that show how individual
objects change their state in response to events.
 Other models include use-case models, aggregation
models, generalisation models, etc.
Subsystem models

 Shows how the design is organised into


logically related groups of objects.
 In the UML, these are shown using
packages - an encapsulation construct. This
is a logical model. The actual organisation of
objects in the system may be different.
Weather station subsystems
« subsy stem» « subsy stem»
In terface Data collectio n

Co mmsCon troller WeatherData

In strument
WeatherStation Status

« subsy stem»
In struments

Air
th ermo meter Rain Gauge An emo meter

Gro und Baro meter Win dVane


th ermo meter
Sequence models

 Sequence models show the sequence of


object interactions that take place
• Objects are arranged horizontally across the
top;
• Time is represented vertically so models are
read top to bottom;
• Interactions are represented by labelled arrows,
Different styles of arrow represent different
types of interaction;
• A thin rectangle in an object lifeline represents
the time when the object is the controlling object
in the system.
Data collection sequence
Statecharts

 Show how objects respond to different service


requests and the state transitions triggered by these
requests
• If object state is Shutdown then it responds to a Startup()
message;
• In the waiting state the object is waiting for further
messages;
• If reportWeather () then system moves to summarising
state;
• If calibrate () the system moves to a calibrating state;
• A collecting state is entered when a clock signal is
received.
Weather station state diagram
Object interface specification

 Object interfaces have to be specified so that the


objects and other components can be designed in
parallel.
 Designers should avoid designing the interface
representation but should hide this in the object
itself.
 Objects may have several interfaces which are
viewpoints on the methods provided.
 The UML uses class diagrams for interface
specification but Java may also be used.
Weather station interface
interface WeatherStation {

public void WeatherStation () ;

public void startup () ;


public void startup (Instrument i) ;

public void shutdown () ;


public void shutdown (Instrument i ) ;

public void reportWeather ( ) ;

public void test () ;


public void test ( Instrument i ) ;

public void calibrate ( Instrument i) ;

public int getID () ;

} //WeatherStation
Design evolution
 Hiding information inside objects means that
changes made to an object do not affect other
objects in an unpredictable way.
 Assume pollution monitoring facilities are to be
added to weather stations. These sample the
air and compute the amount of different
pollutants in the atmosphere.
 Pollution readings are transmitted with weather
data.
Changes required
 Add an object class called Air quality as part
of WeatherStation.
 Add an operation reportAirQuality to
WeatherStation. Modify the control software
to collect pollution readings.
 Add objects representing pollution monitoring
instruments.
Pollution monitoring
WeatherStation
Air quality
identifier
NOData
repo rtWeather () smok eData
repo rtAirQuality () benz eneData
calibrate (instruments)
test () collect ()
startup (instruments) summarise ()
sh utdo wn (instruments)

Po llutio n mo nito rin g instruments

NOmeter Smok eM eter

Ben zen eM eter


Object Oriented Design and UML

 Software Development Activities


 Object Oriented Design
 Unified Modeling Language (UML)

55
Software Development

 Software involves four basic activities:


1. Establishing the requirements
2. Creating a design
3. Implementing the code
4. Testing the implementation
 These activities are not strictly linear – they
overlap and interact
 We’ve already done a lot with #3 and #4
 Now, we’ll concentrate on #1 and #2

56
Requirements

 Software requirements specify the tasks that a


program must accomplish
• what to do, not how to do it
 Often an initial set of requirements is provided,
but they should be critiqued and expanded
 It is difficult to establish and document detailed,
unambiguous, and complete requirements
 Careful attention to the requirements can save
significant time and expense in the overall project

57
Design
 A software design specifies how a program will
accomplish its requirements
 That is, a software design determines:
• how the solution can be broken down into
manageable pieces
• what each piece will do
 An object-oriented design determines which
classes and objects are needed and specifies
how they will interact
 Low level design details include how individual
methods will accomplish their tasks
58
Object-Oriented Design

 Design Methodology / Process


• Analyze / decompose the requirements
• Determine the classes required for a program
• Define the relationships among classes
 Tool: Unified Modeling Language (UML)
• Use Case Diagram
• Class Diagram
• Interaction Diagram

59
Identifying Classes and Objects

 The core activity of object-oriented design is


determining the actors, classes, and objects that
represent the problem and its solution
 The classes may be part of a class library,
reused from a previous project, or newly written
 One way to identify potential classes is to
identify the objects discussed in the
requirements
 Objects are generally nouns, and the services
that an object provides are generally verbs
60
Identifying Classes and Objects

 A partial requirements document:


The user must be allowed to specify each product by
its primary characteristics, including its name and
product number. If the bar code does not match the
product, then an error should be generated to the
message window and entered into the error log. The
summary report of all transactions must be structured
as specified in section 7.A.

Of course, not all nouns will correspond to


an actor, class or object in the final solution
61
Identifying Classes and Objects

 A class represents a group (a “classification”) of


objects with the same attributes and behaviors
 Generally, classes that represent objects should
be given names that are singular nouns
 Examples: Coin, Student, Message
 A class represents the concept of one such
object
 We are free to instantiate as many “instances” of
each object as needed
 Good selection of object names for the instances
62
can be helpful to understanding
Identifying Classes and Objects
 Sometimes it is challenging to decide whether
something should be represented as a class
 For example, should an employee's address
be represented as a set of instance variables
or as an Address object
 The more you examine the problem and its
details the more clear these issues become
 When a class becomes too complex, it often
should be decomposed into multiple smaller
classes to distribute the responsibilities
63
Identifying Classes and Objects

 We want to define classes with the proper


amount of detail
 For example, it may be unnecessary to
create separate classes for each type of
appliance in a house
 It may be sufficient to define a more general
Appliance class with appropriate instance
data
 It all depends on the details of the problem
being solved
64
Identifying Classes and Objects
 Part of identifying the classes we need is the
process of assigning responsibilities to each
class
 Every activity that a program must accomplish
must be represented by one or more methods
in one or more classes
 We generally use verbs for the names of
methods
 In early stages it is not necessary to determine
every method of every class – begin with
primary responsibilities and evolve the design
65
Unified Modeling Language
(UML)
 UML is a graphical tool to visualize and analyze
the requirements and do design of an object-
oriented solution to a problem
 Three basic types of diagrams:
• Use Case Diagram
• Class Diagram
• Interaction Diagram
 A good reference is UML Distilled, 3rd Ed.,
Martin Fowler, Addison-Wesley/Pearson

66
Unified Modeling Language
(UML)
 Advantage of UML – It is graphical
• Allows you to visualize the problem / solution
• Organizes your detailed information
 Disadvantage of UML – It is graphical
• Can be done with pencil and paper - tedious
• We have UMLPAD which is a simple design tool to
aid in drawing the diagrams
• Commercial UML S/W tools may be expensive!
• Example: Rational ROSE (IBM acquired Rational)

67
Use Case Diagrams

 Typically the first diagram(s) drawn


 Helpful for visualizing the requirements
 Icons on the Use Case Diagram
• Actors: Users or other external systems
• Objects: Potential classes in the solution
• Scenarios: Sequences of interactions between
Actors and Objects that are typical for the
solution to the problem (Both success cases
and error cases should be included)

68
Example: Use Case Diagram

 Actors: Sales person, Customer, Bartender


 Objects: Products, Cash, Cash Register, Credit
Card, Card Swipe Machine, Bank
 Scenarios involving Actors and Objects:
• Customer listens to sales pitch but doesn’t buy
• Customer buys product with cash
• Customer buys product with credit card
• Success scenario: Bank accepts the card
• Error scenario: Bank says card is “maxed out”

69
Example: Use Case Diagram

“No Sale” <<includes>>


Cry over lost Bartender
Customer commission
Stiff Drink
Buy with Cash Process
Cash Sale
Sales Person Cash
Buy On Credit Register
Process
Product Cash Credit Sale
Bank
Credit Card
Card Swipe
Machine 70
Example: Scenario
 Process Credit Sale
• Swipe Card
• Enter Amount of Sale
• Wait for Bank Response
• Success Variation (Bank accepts charge)
• Record authorization number
• Get customer signature
• Give customer product(s) and receipt
• Error Variation (Card maxed out)
• Inform Customer that card was rejected
• <<include>> Cry over Lost Commission

71
Class Diagrams
 Classify the Objects in the Use Cases
 Define name of each class
 Define each class’s attributes
• Constants
• Variables
 Define each class’s behaviors
• Methods
 Show relationships between classes
• Depends on, Inherits, etc.

72
Example: Class Diagram
Credit Card Bank
- name : String
- myCardData : - address : String
CardData - accounts [ ] : AcctData
+ read( ) : CardData + processCharge (
thisCardData : CardData
CardData amt : double,
- cardType : enum {Visa, …} storeName : String,
- myBank : Bank storeBank : Bank,
- myAcctNumber : int storeAcctNumber : int
AcctData
) : boolean
-acctLimit : double
+ getCardType( ) : enum -acctBalance: double 73
+ getBank( ) : Bank …
Interaction Diagrams

 Shows the time relationship of the events in


a scenario between actors and objects
• UML Sequence Diagram
• Sometimes called a “ladder diagram”
 A vertical line represents an actor or object
 A horizontal line represents an interaction
• E.G. a call to a method of another object
 Progress of time is shown down the page

74
Example: Interaction Diagram
Process Credit Sale
Time Sales Card
Credit Card Bank
Person Swipe
swipeCard( )
Machine
read( )
return
enterAmt(…)
CardData
processCharge( … )

return boolean
readResponse( )
return “OK”

75
Activities

 In this activity, you will write a class that


encapsulates the three integer coefficients of a
linear equation:
ax + by = c
 The methods are defined in the assignment
 The class implements the interface
Comparable<T> (we’ll cover implementing
interfaces shortly)

76
Your ApplicationClass java.util.Arrays

+ main (args : String [ ]) : void + sort (array : Object [ ]) : void

Class Libra
You write
<<interface>>
java.lang.Comparable<Equation>
+ compareTo (that : T) : int
Provided You write

EquationTest Equation

77
Equation Class UML Diagram

Equation implements Comparable<Equation>


+ THRESHHOLD : double // threshold for comparisons of double values
- a : int // coefficient of the variable x
- b : int // coefficient of the variable y
- c : int // constant
+ Equation(a : int, b : int, c : int) // constructor
+ toString( ) : String // return a String representing the equation
+ slope( ) : double // return the slope of the line
+ intercept( ) : double // return the y-axis intercept of the line
+ compareTo(that : Equation) : int // compare values of equations
// solving methods for pairs of equations:
+ solveForXWith(that : Equation) : double // solve for X
+ solveForYWith(that : Equation) : double // solve for Y
+ verifySolution(x : double, y : double) : boolean // verify correct
Key points
 OOD is an approach to design so that design
components have their own private state and
operations.
 Objects should have constructor and inspection
operations. They provide services to other objects.
 Objects may be implemented sequentially or
concurrently.
 The Unified Modeling Language provides different
notations for defining different object models.
Key points
 A range of different models may be produced
during an object-oriented design process.
These include static and dynamic system
models.
 Object interfaces should be defined precisely
using e.g. a programming language like
Java.
 Object-oriented design potentially simplifies
system evolution.

You might also like