object-oriented design ©ian sommerville 2006. objectives to explain how a software design may be...

65
Object-Oriented Design ©Ian Sommerville 2006

Post on 19-Dec-2015

213 views

Category:

Documents


0 download

TRANSCRIPT

Object-Oriented Design

©Ian Sommerville 2006

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

• 1- Objects and object classes • 2- An object-oriented design process• 3- 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

state o3

o3:C3

state o4

o4: C4

state o1

o1: C1

state o6

o6: C1

state o5

o5:C5

state o2

o2: C3

ops1() ops3 () ops4 ()

ops3 () ops1 () ops5 ()

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.

Object Oriented Terminologies • Class • Defines the abstract characteristics of a thing (object), including the thing's characteristics (its

attributes (variables), fields or properties) and the thing's behaviors (the things it can do, or methods, operations or features). One might say that a class is a blueprint or factory that describes the nature of something. For example, the class Dog would consist of traits shared by all dogs, such as breed and fur color (characteristics), and the ability to bark and sit (behaviors). Classes provide modularity and structure in an object-oriented computer program. A class should typically be recognizable to a non-programmer familiar with the problem domain, meaning that the characteristics of the class should make sense in context. Also, the code for a class should be relatively self-contained (generally using encapsulation). Collectively, the properties and methods defined by a class are called members.

• Object • A pattern (exemplar) of a class. The class of Dog defines all possible dogs by listing the

characteristics and behaviors they can have; the object Lassie is one particular dog, with particular versions of the characteristics. A Dog has fur; Lassie has brown-and-white fur.

Object Oriented Terminologies • Instance • One can have an instance of a class or a particular object. The instance is the actual object

created at runtime. In programmer jargon, the Lassie object is an instance of the Dog class. The set of values of the attributes of a particular object is called its state. The object consists of state and the behavior that's defined in the object's class.

• Method • An object's abilities. In language, methods (sometimes referred to as "functions") are verbs.

Lassie, being a Dog, has the ability to bark. So bark() is one of Lassie's methods. She may have other methods as well, for example sit() or eat() or walk() or save_timmy(). Within the program, using a method usually affects only one particular object; all Dogs can bark, but you need only one particular dog to do the barking.

Object Oriented Terminologies • Message passing • "The process by which an object sends data to another object or asks the other object to invoke a

method." Also known to some programming languages as interfacing. For example, the object called Breeder may tell the Lassie object to sit by passing a "sit" message which invokes Lassie's "sit" method. The syntax varies between languages, for example: [Lassie sit] in Objective-C.

Object Oriented Terminologies • Inheritance • "Subclasses" are more specialized versions of a class, which inherit attributes and behaviors from their

parent classes, and can introduce their own. • For example, the class Dog might have sub-classes called Collie, Chihuahua, and GoldenRetriever. In

this case, Lassie would be an instance of the Collie subclass. Suppose the Dog class defines a method called bark() and a property called furColor. Each of its sub-classes (Collie, Chihuahua, and GoldenRetriever) will inherit these members, meaning that the programmer only needs to write the code for them once.

• Each subclass can alter its inherited traits. For example, the Collie class might specify that the default furColor for a collie is brown-and-white. The Chihuahua subclass might specify that the bark() method produces a high pitch by default. Subclasses can also add new members. The Chihuahua subclass could add a method called tremble(). So an individual chihuahua instance would use a high-pitched bark() from the Chihuahua subclass, which in turn inherited the usual bark() from Dog. The chihuahua object would also have the tremble() method, but Lassie would not, because she is a Collie, not a Chihuahua. In fact, inheritance is an "a... is a" relationship between classes, while instantiation is an "is a" relationship between an object and a class: a Collie is a Dog ("a... is a"), but Lassie is a Collie ("is a"). Thus, the object named Lassie has the methods from both classes Collie and Dog.

• Multiple inheritance is inheritance from more than one ancestor class, neither of these ancestors being an ancestor of the other. For example, independent classes could define Dogs and Cats, and a Chimera object could be created from these two which inherits all the (multiple) behavior of cats and dogs. This is not always supported, as it can be hard both to implement and to use well.

Object Oriented Terminologies • Abstraction • Abstraction is simplifying complex reality by modelling classes appropriate to the problem, and

working at the most appropriate level of inheritance for a given aspect of the problem. • For example, Lassie the Dog may be treated as a Dog much of the time, a Collie when necessary

to access Collie-specific attributes or behaviors, and as an Animal (perhaps the parent class of Dog) when counting Timmy's pets.

• Abstraction is also achieved through Composition. For example, a class Car would be made up of an Engine, Gearbox, Steering objects, and many more components. To build the Car class, one does not need to know how the different components work internally, but only how to interface with them, i.e., send messages to them, receive messages from them, and perhaps make the different objects composing the class interact with each other.

Object Oriented Terminologies • Encapsulation • Encapsulation conceals the functional details of a class from objects that send messages to it. • For example, the Dog class has a bark() method. The code for the bark() method defines exactly how

a bark happens (e.g., by inhale() and then exhale(), at a particular pitch and volume). Timmy, Lassie's friend, however, does not need to know exactly how she barks. Encapsulation is achieved by specifying which classes may use the members of an object. The result is that each object exposes to any class a certain interface — those members accessible to that class. The reason for encapsulation is to prevent clients of an interface from depending on those parts of the implementation that are likely to change in future, thereby allowing those changes to be made more easily, that is, without changes to clients. For example, an interface can ensure that puppies can only be added to an object of the class Dog by code in that class. Members are often specified as public, protected or private, determining whether they are available to all classes, sub-classes or only the defining class. Some languages go further: Java uses the default access modifier to restrict access also to classes in the same package, C# and VB.NET reserve some members to classes in the same assembly using keywords internal (C#) or Friend (VB.NET), and Eiffel and C++ allow one to specify which classes may access any member.

Object Oriented Terminologies • Polymorphism • Polymorphism allows the programmer to treat derived class members just like their parent class'

members. More precisely, Polymorphism in object-oriented programming is the ability of objects belonging to different data types to respond to method calls of methods of the same name, each one according to an appropriate type-specific behavior. One method, or an operator such as +, -, or *, can be abstractly applied in many different situations. If a Dog is commanded to speak(), this may elicit a bark(). However, if a Pig is commanded to speak(), this may elicit an oink(). They both inherit speak() from Animal, but their derived class methods override the methods of the parent class; this is Overriding Polymorphism. Overloading Polymorphism is the use of one method signature, or one operator such as "+", to perform several different functions depending on the implementation. The "+" operator, for example, may be used to perform integer addition, float addition, list concatenation, or string concatenation. Any two subclasses of Number, such as Integer and Double, are expected to add together properly in an OOP language. The language must therefore overload the addition operator, "+", to work this way. This helps improve code readability. How this is implemented varies from language to language, but most OOP languages support at least some level of overloading polymorphism. Many OOP languages also support Parametric Polymorphism, where code is written without mention of any specific type and thus can be used transparently with any number of new types. Pointers are an example of a simple polymorphic routine that can be used with many different types of objects.

1- 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)

Employee

name: stringaddress: stringdateOfBirth: DateemployeeNo: integersocialSecurityNo: stringdepartment: Deptmanager: Employeesalary: integerstatus: {current, left, retired}taxCode: integer. . .

join ()leave ()retire ()changeDetails ()

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 (function) 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) ;

Generalization 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 generalization 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.

• Generalization in the UML is implemented as inheritance in OO programming languages.

A Generalization Hierarchy

Employee

Programmer

projectprogLanguages

Manager

ProjectManager

budgetsControlled

dateAppointed

projects

Dept.Manager

StrategicManager

dept responsibilities

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 organizational 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 generalized 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

Employee Department

Manager

is-member-of

is-managed-by

manages

1.1 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.

2- 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.

Object-oriented Design Process Stages• Highlights key activities without being tied to any

proprietary process such as the RUP & OPEN. Third generation OO methods have two examples: the rational unified process

(RUP) and object-oriented process, environment and notation (OPEN) that have acceptable standards in process support, project management guidelines and full lifecycle description for OO software development.

– 2.1 Define the context and modes of use of the system;– 2.2 Design the system architecture;– 2.3 Identify the principal system objects;– 2.4 Develop design models;– 2.5 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.

2.1 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. Can use An association model. The create UMLs (next slides) for sub-systems. Use a subsystem model to show other systems. Following slide shows the systems around the weather station system.

• Model of system use– When your system is dynamic model that describes how the

system interacts with its environment. The RUP recommend to use use-cases to show interactions

2.1 Define the context and modes of use of the system;2.2 Design the system architecture;2.3 Identify the principal system objects;2.4 Develop design models;2.5 Specify object interfaces.

Layered architecture

«subsystem»Data collection

«subsystem»Data processing

«subsystem»Data archiving

«subsystem»Data display

Data collection layer where objectsare concerned with acquiring datafrom remote sources

Data processing layer where objectsare concerned with checking andintegrating the collected data

Data archiving layer where objectsare concerned with storing the data for future processing

Data display layer where objects areconcerned with preparing andpresenting the data in a human-readable form

Subsystems in the weather mapping system

Datastorage

Userinterface

«subsystem»Data collection

«subsystem»Data processing

«subsystem»Data archiving

«subsystem»Data display

Weatherstation

Satellite

Comms

Balloon

Observer

Map store Data store

Datastorage

Map

Userinterface

Mapdisplay

Mapprinter

Datachecking

Dataintegration

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.

• Next slides show weather station interact with external entities

• Use case describes in natural language to help identify system objects …

Use-cases for the weather station

Startup

Shutdown

Report

Calibrate

Test

Use-case description

System Weather stationUse-case ReportActors Weather data collection system, Weather stationData The weather station sends a summary of the weather data that has been

collected from the instruments in the collection period to the weather datacollection system. The data sent are the maximum minimum and averageground and air temperatures, the maximum, minimum and average airpressures, the maximum, minimum and average wind speeds, the totalrainfall and the wind direction as sampled at 5 minute intervals.

Stimulus The weather data collection system establishes a modem link with theweather station and requests transmission of the data.

Response The summarised data is sent to the weather data collection systemComments Weather stations are usually asked to report once per hour but this

frequency may differ from one station to the other and may be modified infuture.

2.2 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 earlier 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.

2.1 Define the context and modes of use of the system;2.2 Design the system architecture;2.3 Identify the principal system objects;2.4 Develop design models;2.5 Specify object interfaces.

Weather station architecture

Weather station

Manages allexternal

communications

Collects andsummarisesweather data

Package ofinstruments for raw

data collections

«subsystem»Data collection

«subsystem»Instruments

«subsystem»Interface

2.3 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.

2.1 Define the context and modes of use of the system;2.2 Design the system architecture;2.3 Identify the principal system objects;2.4 Develop design models;2.5 Specify object interfaces.

Approaches to identification• Use a grammatical approach based on a natural language

description of the system (used in Hood OOD method, in European aerospace

industry). Objectives and Attributes are nouns; operations and services are verbs.

• Base the identification on tangible things in the application domain. i.e domain:aircraft, role:manager, event: request, interaction:meeting

• Understand overall behavioural of the system, break it into parts, assign parts, participants play important roles

• Use a scenario-based analysis. The objects, attributes and methods in each scenario are identified. Teams responsible define object, attributes and methods

Weather station Object 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

• 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.

• Ground thermometer, Anemometer, Barometer– Application domain objects that are ‘hardware’ objects

related to the instruments in the system.

Weather station object classes

identifier

reportWeather ()calibrate (instruments)test ()startup (instruments)shutdown (instruments)

WeatherStation

test ()calibrate ()

Groundthermometer

temperature

Anemometer

windSpeedwindDirection

test ()

Barometer

pressureheight

test ()calibrate ()

WeatherData

airTemperaturesgroundTemperatureswindSpeedswindDirectionspressuresrainfall

collect ()summarise ()

• 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.• Ground thermometer, Anemometer, Barometer

– Application domain objects that are ‘hardware’ objects related to the instruments in the system.

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.

2.4 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.

2.1 Define the context and modes of use of the system;2.2 Design the system architecture;2.3 Identify the principal system objects;2.4 Develop design models;2.5 Specify object interfaces.

Design models Examples

• A- Sub-system models that show logical groupings of objects into coherent subsystems.

• B- Sequence models that show the sequence of object interactions.

• C- State machine models that show how individual objects change their state in response to events.

• D- Other models include use-case models, aggregation models, generalisation models, etc.

A) Subsystem Models

• Shows how the design is organized into logically related groups of objects.

• In the UML, these are shown using packages - an encapsulation construct. This is a logical model. The actual organization of objects in the system may be different.

Weather station subsystems«subsystem»

Interface«subsystem»

Data collection

CommsController

WeatherStation

WeatherData

InstrumentStatus

«subsystem»Instruments

Air thermometer

Ground thermometer

RainGauge

Barometer

Anemometer

WindVane

B) 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

:CommsController

request (report)

acknowledge ()report ()

summarise ()

reply (report)

acknowledge ()

send (report)

:WeatherStation :WeatherData

– 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.

C) State Machines Models

• 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

transmission done

calibrate ()

test ()startup ()

shutdown ()

calibration OK

test complete

weather summarycomplete

clock collectiondone

Operation

reportWeather ()

Shutdown Waiting Testing

Transmitting

Collecting

Summarising

Calibrating

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.

2.5 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 and 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

2.1 Define the context and modes of use of the system;2.2 Design the system architecture;2.3 Identify the principal system objects;2.4 Develop design models;2.5 Specify object interfaces.

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

3- 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

NODatasmokeDatabenzeneData

collect ()summarise ()

Air qualityidentifier

reportWeather ()reportAirQuality ()calibrate (instruments)test ()startup (instruments)shutdown (instruments)

WeatherStation

Pollution monitoring instruments

NOmeter SmokeMeter

BenzeneMeter

• 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

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.

Fortune 2008: Top 20 Most Admired Companies1 Apple 2 Berkshire Hathaway 3 General Electric 4 Google 5 Toyota Motor 6 Starbucks 7 FedEx 8 Procter & Gamble 9 Johnson & Johnson 10 Goldman Sachs Group 11 Target 12 Southwest Airlines 13 American Express 14* BMW 14* Costco Wholesale 16 Microsoft 17 United Parcel Service 18 Cisco Systems 19 3M 20 Nordstrom

Keys:

Innovation

People management

Use of corporate assets

Social responsibility

Quality of management

Financial soundness

Long-term investment

Quality of products/services

Best Cities for Jobs

5. Fort Worth, Texas

4. Atlanta, Ga.,

2. Witchita, Kansas

3. Austin, Texas

1. Salt Lake City, Utah