Post on 04-Jan-2016
Chapter 8: Object-Oriented Design
Omar MeqdadiSE 273 Lecture 8
Department of Computer Science and Software Engineering University of Wisconsin-Platteville
2
Topics covered
Objects and object classes An object-oriented design process Design evolution
3
Object-Oriented Design
Designing systems using self-contained objects and object classes
4
Objects and Classes
Class – a generalization of a set of entities with common structure, behavior, and relationships to other classes. An abstract data type. A person, an employee
Object – an instance of a class. It has a state, value, and scope of existence Joe Smith, Jane Doe
5
Objects
Objects are entities in a software system which represent instances of real-world and system entities
An object has a state, behavior and identity. Terms instance and object are interchangeable. State – the properties of an object and the current values of these
properties Behavior – how an object acts and reacts in terms of its state change
and message passing
6
Types of objects
Boundary – represent the interactions between the system and actors
Control – represent the tasks that are performed by the user and supported by the system
Entity – represent the persistent information tracked by the system
See [Jacobson ’99]
7
Objects and object classes
Object classes Templates for objects (used to create objects) The structure and behavior of similar objects are defined in
their class. Includes declarations of all the attributes and services
which should be associated with an object of that class Object classes may inherit attributes and services from
other object classes
8
What is a good Class?
Should provide a crisp abstraction of something from the problem (or solution) domain
Embody a small well defined set of responsibilities and carry them out well
Provides clear separation of abstraction, specification, and implementation
Is understandable and simple yet extendable and adaptable.
9
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
10
Advantages of OOD
Easier maintenance. Objects may be understood as stand-alone entities
Objects are appropriate reusable components For some systems, there may be an obvious
mapping from real world entities to system objects
11
Object Oriented paradigm
OO Analysis – A method of analysis which examines requirements from the perspective of classes and objects found in the vocabulary of the problem domain
OO Design – A method of design encompassing the process of object oriented decomposition.
OO Programming – A method of implementation in which programs are organized as cooperative collections of objects, each an instance of a class whose members are part of a inheritance hierarchy
12
A Class in UML
+print()
-name : string(idl)-age : int
PersonClass name
Attributes
Operators
13
Class attributes
Person
+ name : String# address : Address# birthdate : Date- ssn : Id
An attribute is a named property of a class that describes the object being modeled
Attributes are usually listed in the form:
attributeName : Type Attributes can be:
+ public # protected - private
14
Class operations
Person
name : Stringaddress : Addressbirthdate : Datessn : Id
eatsleepworkplay
Operations describe the class behavior and appear in the third compartment
Specify an operation by stating its signature
Operations can be: + public # protected - private
15
An object in UML
object name and class joe : Person
16
Example class diagram
+open()+close()+display()
-name : string(idl)window
dialogboxconsolewindow
event
control
17
Class relationships in UML
Generalization Dependency Association
These can represent inheritance, using, aggregation, etc.
-Role1
*
-Role2
0..1
18
Generalisation and inheritance
Objects are members of classes which 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
19
A generalisation hierarchy
Employee
Programmer
projectprogLanguage
Manager
ProjectManager
budgetsControlled
dateAppointed
projects
Dept.Manager
StrategicManager
dept responsibilities
20
GeneralizationSensor
+currentValue()+calibrate()
CalibratingSensor
+currentDirection()
WindDirectionSensor
+resetHighest()+resetLowest()
-highestValue-lowestVale
HistoricalSensor
-trend
TrendSensor
+currentHumidity()
-humidity
HumiditySensor
+currentSpeed()
-speed
WindspeedSensor
+currentTemp()
-temp
TemperatureSensor
+currentPressure()
-pressure
Barometer
•An is-a relationship•Abstract class
21
Single inheritance
TelemetryData
TelemetryData
TelemetryData
TelemetryData
TelemetryData
TelemetryData
TelemetryData
22
Single inheritance
class TelemetryData {public: TelemetryData(); virtual ~TelemetryData(); virtual void transmit(); Time currentTime() const; private: int id; Time timeStamp;};
class ElectricalData : public TelemetryData {public: ElectricalData(float v1, float v2, float v1, float v2); virtual ElectricalData(); virtual void transmit(); float currentPower() const;private:float fuelCell1Voltage, fuelCell2Voltage;float fuelCell1Amperes, fuelCell2Amperes;};
23
Multiple inheritance
InsurableItem
BankAccount
SavingAccount
InterestBearing
CheckingAccount
Asset
RealEstate
Security
Bond
Stock
24
Multiple inheritance
class Asset;class InsurableItem;class InterestBearing;
class BankAccount : public Asset, public InsurableItem, public InterestBearing {};
class RealEstate : public Asset, public InsurableItem {};
class Security : public Asset, public InterestBearing {};
class SavingsAccount : public BankAccount {};class CheckingAccount : public BankAccount {};
class Stock : public Security {};class Bond : public Security {};
25
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
26
Problems with inheritance
Object classes are not self-contained. they can not 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
27
Inheritance and OOD
There are differing views as to whether inheritance is fundamental to OOD. View 1. Identifying the inheritance hierarchy or network is
a fundamental part of object-oriented design. Obviously this can only be implemented using an OOPL.
View 2. Inheritance is a useful implementation concept which allows reuse of attribute and operation definitions. Identifying an inheritance hierarchy at the design stage places unnecessary restrictions on the implementation
Inheritance introduces complexity and this is undesirable, especially in critical systems
28
Association
Structural relationship between peer classes (or objects). Association can have a name and direction, or be bi-
directional Role names for each end of the association Multiplicity of the relationship
Association code example
class Person {
public:
private:
Company *employer;
};
class Company {
public:
private:
Person **employee;
};
Each instance of Person has a pointer to its employer
Each instance of Company has a collection of pointers denoting its employees
30
Examples of association
person company
person company
Works For
-employee
1..*
-employer
*
31
An association model
EmployeeDepartment
Manager
is-member-of
is-managed-by
manages
32
Association Relationships
A class can have a self association.
LinkedListNode
next
previous
33
Link Attributes
Associations may have properties in the same manner as objects/classes.
Salary and job title can be represented as
person company
-salary-title
1..*
-employee
*
-employer
34
Aggregation & Composition
Special type of association Part of relationship (is-part-of, is-made-of, contains) Can use roles and multiplicity
university department
1 *
Aggregation vs. Composition
Aggregation is a shared containment. No strong life time dependency.
Composition is constrained aggregation that implies ownership. The life time of the aggregates are determined by the object.
1 *
1 *
Aggregation code example
A part-of (has-a) relationship (physical containment)
class Team{public: Team(); Team(vector<*members>); private: vector<*department> members[n];};
Composition code example
A part-of (has-a) relationship (physical containment)
class university {public: university(); university(vector<*department>); private: vector<*department> dept[n];};
38
Dependency
Represents a using relationship If a change in specification in one class effects another
class , then there is a dependency
windchill
windspeedSensor
tempatureSensor
39
Dependency relationships
CourseSchedule
add(c : Course)remove(c : Course)
Course
A dependency indicates a semantic relationship between two ormore elements. The dependency from CourseSchedule to Course exists because Course is used in both the add and remove operations of CourseSchedule.
40
Which Relation is Right?
Aggregation – aka is-part-of, is-made-of, contains Use association when specific (persistent) objects have
multiple relationships (e.g., there is only one Bill Gates at MS)
Use dependency when working with static objects, or if there is only one instance
Do not confuse part-of with is-a
41
Object modeling
Given the high-level requirements (use cases) Define the object model
Identify objects Compile a data dictionary Identify association and aggregations Identify attributes of objects Generalize objects into classes Organized and abstract using inheritance Iterate and refine model Group classes into modules/components
42
Example: Weather Monitoring Station
This system shall provide automatic monitoring of various weather conditions. Specifically, it must measure: wind speed and direction temperature barometric pressure humidity
The system shall also proved the following derived measurements: wind chill dew point temperature temperature trend barometric pressure trend
43
Weather Monitoring System Requirements
The system shall have the means of determining the current time and date so that it can report the highest and lowest values for any of the four primary measurements during the previous 24 hour period.
The system shall have a display that continuously indicates all eight primary and derived measurements, as well as current time and date.
Through he use of a keypad the user may direct the system to display the 24 hour low or high of any one primary measurement, with the time of the reported value.
The system shall allow the user to calibrate its sensors against known values, and set the current time and date.
44
Identify objects
From the vocabulary of the domain User, clock, sensor, temperature, LCDDisplay, Keypad, time, date,
wind speed, humidity, barometer, calibrator, metric units, English units, input manager, sensor sampler, wind direction, display manager, trend, pressure, current time, current date, current temp, high temp, low temp, change temp, change time, power up, power down, input buffer, trend, key, running, selecting
45
Eliminate terms
Refine the model by eliminating Redundancy – classes that represent same concept Irrelevant classes – things you don’t care about Vague classes – ill defined boundaries Attributes – describe parts of objects Operators – sequence of actions are often mistaken for classes Roles – what it is not the role it plays Implementation details – save it for later
46
New Data Dictionary
Time & Date Sensors: Temperature, Pressure, Humidity, Wind Speed, Wind Direction Keypad Input Manager Display (LCD Device) Display Manager Timer (clock) Sensor Sampler
47
Relationships
sensors
samplerinputManager
displayManager
«interface»keypad
«interface»LCDDevice «interface»
timer
-time-date
timeDate
windChill
1
1
1
1
1
1
11
1
1
dewPoint
windDirection
sensor1
1
1
1
1
1..*
1
1
48
Packages
Compiler
A package is a container-like element for organizing other elements into groups.
A package can contain classes and other packages and diagrams.
Packages can be used to provide controlled access between classes in different packages.
49
Packages: Example
Classes in the FrontEnd package and classes in the BackEnd package cannot access each other in this diagram.
FrontEnd BackEnd
Compiler
50
Packages: Example
Classes in the BackEnd package now have access to the classes in the FrontEnd package.
FrontEnd BackEnd
Compiler
51
Packages
JavaCompiler
We can model generalizations and dependencies between packages.Compiler
Java
52
Subsystem models
Shows how the design is organised into logically related groups of objects or packages
53
Weather station subsystems : example1
«subsystem»Interface
CommsController
WeatherStation
«subsystem»Data collection
«subsystem»Instruments
Air thermometer
WeatherData
Ground thermometer
Anemometer
WindVane
RainGauge
InstrumentStatus
Barometer
54
Weather station subsystems : example2 (layer architecture
«subsystem»Data collection
«subsystem»Instruments
«subsystem»Interface
Weather station
Manages allexternal
communications
Collects andsummarisesweather data
Package ofinstruments for raw
data collections
55
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
56
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.
57
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) ;
58
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
59
Active transponder object
Active objects may have their attributes modified by operations but may also update them autonomously using internal operations
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
60
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