1 Object-Oriented Design Lesson #13 Note: CIS 601 notes were originally developed by H. Zhu for NJIT...

Post on 29-Mar-2015

221 views 2 download

Tags:

Transcript of 1 Object-Oriented Design Lesson #13 Note: CIS 601 notes were originally developed by H. Zhu for NJIT...

1

Object-Oriented Design

Lesson #13

Note: CIS 601 notes were originally developed by H. Zhu for NJIT DL Program. The notes were subsequently revised by M. Deek

2

Activities in Software Development

Problem Analysis Solution Design Coding Documenting Testing Maintenance

3

Strategy

One basic way to deal with complexity: Divide and Conquer.

Systems can be divided into modules (Objects or Classes).

The challenge is to ensure effective communication between different parts of the program without destroying the divisions.

4

Objectives

We are concerned with producing software that satisfies user requirements.

The primary means to do so is to produce software with a clean internal structure.

5

The Tasks of OO Design

We need to specify: The needed classes The public interface The protected interface

6

The Need for a Clean Internal Structure

To simplify: Testing Porting Maintenance Extension Re-organization Understanding

7

Characteristics of Successful Software

It has an extended life where it might be:

worked on by a succession of programmers and designers

ported to new hardware adapted to unanticipated uses

8

The Development Cycle

Create an overall design Find standard components and then

customize the components for this design.

Create new standard components and then customize the components for this design.

Assemble design.

9

Design for Change

The system must be designed to remain as simple as possible under a sequence of changes.

Aim for: flexibility extensibility portability

OOD can support the above.

10

Design Steps of OOD

Find the Concepts/Classes and their fundamental relationships.

Refine the Classes by specifying the sets of Operations on them classify these operations: constructors,

destructors, etc. consider minimalism, completeness, and

convenience

11

Design Steps Refine the classes by specifying their

dependencies on other classes: Inheritance Use dependencies

Specify the interfaces for the classes: separate functions into public and protected

operations specify the exact type of the operations on

the classes.

12

Finding Classes

Good design must capture and model some aspects of reality.

Look at the application rather than the abstractions.

Usually nouns correspond to classes and verbs represent functions.

13

Example When ordering new videotapes from a supplier, the

store manager creates a purchase order, fills in the date, the supplier’s name , address, and enters a list of videotapes to be ordered. The purchase order is added to a permanent list of purchases. When one or more video tapes are received from a supplier, a clerk locates the original purchase order and makes a record of each tape that was received. A record of the videotape is then added to the store’s inventory. When all tapes listed on a particular purchase order have been received, the manager sends a payment to the supplier and the purchase order is given a completion date.

14

Specifying operations

Consider how an object of the class is constructed, copied, and destroyed.

Define the minimal set of operations required by the concept the class is representing.

Consider which operations could be added for notational convenience and include only important ones.

15

Specifying Operations

Consider which operations are to be virtual.

Consider what commonality of naming and functionality can be achieved across all the classes of the component.

16

Operations on a Class

Foundation: Constructors, destructors, and copy

operators Selectors:

Operations that do not modify the state of an object.

Modifiers: Operations that modify the state of an

object.

17

Operations on a Class

Conversion Operators: Operations that produce an object of

another type based on the value (state) of the object to which they are applied.

Iterators: Operations that process data members

containing collections of objects.

18

Specifying Dependencies

The key dependencies to consider in the context of design are inheritance and use relationships.

Overuse can lead to inefficient and incomprehensible designs.

19

Specifying Interfaces

Private functions are not considered at this stage.

The interface should be implementation independent (more than one implementation should be possible).

All operators in a class should support the same level of abstraction.

20

Reorganizing the Class Hierarchy

Typically, initial organization of classes may not be adequate and therefore, may have to be reorganize to improve the design and/or implementation.

The two most common reorganizations of a class hierarchy are: factoring of two classes into a new class. splitting a class into two new ones.

21

Use of Models Whenever possible, design and

programming should be based on previous work.

This allows the designer to focus on a the important issues at any given time.

22

Experimentation and Analysis

Prototyping is frequently used for experimenting.

Different aspects of a system may be prototyped independently, such as the graphical user interface.

Analysis of a design and/or implementation can be an important source of insight.

23

Example:Doctor’s office scheduling

Specification: The program allows to schedule appointments for

patients. The office has multiple doctors, each with a daily

schedule divided into 15-minute appointment slots beginning from 8:00am to 6:00pm.

We also want to print out separate daily schedules for each doctor, listing the time and patient name of each appointment.

All output directed to the screen, except for the doctors’ schedules, which will be written to a file for later printing.

For simplicity: Each doctor has only one appointment day.

24

Analysis

Finding classes: Doctor Patient DailySchedule Appointment Scheduler (Interface to the user)

25

Scenario of the process

• Scheduler requests the patient’s name;• Patient chooses a doctor;• Scheduler displays doctor’s schedule,

showing available appointment slots;• Patient requests the specific slot;• Scheduler adds the appointment to the

doctor’s schedule, and adds the appointment to the patient’s record;

• Scheduler confirms the appointment.

26

Class dependencies

Scheduler

Doctor

DailySchedule Appointment

Patient

:composite(contains)

:link(requests, send messages)

Fstring(LastName)

Fstring(FirstName)

27

Operations Doctor

1. AddToSchedule: Add an appt. to the Dr’s Sch.

2. ShowAppointment:Display the sch

Patient1.InputName:

2.ChooseDoctor:

3.ChooseTimeSlot:

4.SetAppointment: Schedule an Appt.

28

Operations DailySchedule

1.SetAppointment: Add an appt to the sch.2.IsTimeSlotFree:Find out if a particular slot is available

3.ShowAppointments: Display the schd appt Appointment

1.Constructor:2.IsScheduled: Find out if an appt schd for the current Appt

Scheduler1.ScheduleOneAppointment: p-appt-d2.ScheduleAllAppointments:input p, request d, update d

3.PrintAllAppointment: print all the schd appt for all Ds

29

Additional Classes

TimeSlot: Handles the translation and formatting of

appointment times. FString:

Deals with string data members.

30

The TimeSlot classclass TimeSlot {

public:

TimeSlot( const unsigned n = 0 );

unsigned AsInteger() const;

friend istream & operator >>(istream & inp, TimeSlot & T);

friend ostream & operator <<(ostream & os, const TimeSlot & T);

private:

static unsigned StartHour;

static unsigned ApptLen;

unsigned intValue;

};

31

The Appointment classclass Appointment {public: Appointment(); Appointment ( const TimeSlot & aTime, unsigned docNum, const Patient & P); const FString & GetPatientName() const; const TimeSlot & GetTime() const; int IsScheduled() const; void SetTime( const unsigned n ); friend ostream & operator <<( ostream & os,const Appointment & A );private: enum { NoDoctor = 9999 }; unsigned doctorNum; TimeSlot timeSlot; FString patientName;};

32

The Patient classclass Patient {public: Patient(); void InputName(); unsigned ChooseDoctor() const; TimeSlot ChooseTimeSlot(const Doctor & D) const; const Appointment & GetAppointment() const; const FString & GetFirstName() const; const FString & GetLastName() const; int IsScheduled() const; void SetAppointment( const Appointment & A ); friend ostream & operator <<( ostream & os, const Patient & P );private: FString lastName; FString firstName; Appointment nextVisit;};

33

The DailySchedule classclass DailySchedule {public: DailySchedule(); int IsTimeSlotFree( const TimeSlot & T ) const; void SetAppointment( const Appointment & A ); void ShowAppointments( ostream & os ) const; friend ostream & operator <<( ostream & os,

const DailySchedule & DS );private: enum { MaxTimeSlots = 40 }; Appointment appointments[MaxTimeSlots];};

34

The Doctor classclass Doctor {public: Doctor(); int AddToSchedule( const Appointment & A ); const DailySchedule & GetSchedule() const; void SetId( const unsigned ); void SetLastName( const FString & L ); const FString & GetLastName() const; void ShowAppointments( ostream & ) const; static const FString & GetDoctorName( unsigned index ); static void SetDoctorName(unsigned, const FString & nam);private: unsigned id; FString lastName; DailySchedule schedule; static FString doctorName[NumDoctors];};

35

The Scheduler class

class Scheduler {

public:

Scheduler( Doctor * docs );

void PrintAllAppointments( const char * fileName);

int ScheduleOneAppointment();

void ScheduleAllAppointments();

private:

Doctor * doctors;

};

36

The main Program

#include "doctors.h"

static Doctor doctorArray[NumDoctors];

int main()

{ cout << "Doctors Office Scheduling Program\n\n";

Scheduler officeSchedule( doctorArray );

officeSchedule.ScheduleAllAppointments();

officeSchedule.PrintAllAppointments( "appts.txt" );

return 0;

}

37

The Implementation

The Time Slot h : hour value sa: the starting appointment time aph: appointments per hour m: minute value al: the appointment length in minutes

timeslot = (h-sa)*aph+m/al

E.g: timeslot = (12-8)*4+20/15=17

The 17th slot.

38

The TimeSlot class

unsigned TimeSlot::StartHour = 8;unsigned TimeSlot::ApptLen = 15;istream & operator >>( istream & inp, TimeSlot & T ){ char buf[20]; inp.getline( buf, 20 ); // get a line of input istrstream aStream( buf, 20 ); unsigned h, m; char ch; aStream >> dec >> h >> ch >> m; unsigned aph = 60 / TimeSlot::ApptLen; if( h < T.StartHour ) // afternoon hour? h += 12; // add 12 to hours T.intValue = ((h - TimeSlot::StartHour)* aph) + (m /

TimeSlot::ApptLen); return inp;}

39

The TimeSlot class

ostream & operator <<( ostream & os, const TimeSlot & T )

{ unsigned aph = 60 / T.ApptLen; // 4 = 60 / 15

unsigned h = (T.intValue / aph ) + T.StartHour; // (S / 4) + 8

unsigned m = (T.intValue % aph ) * T.ApptLen; // (S % 4) * 15

char oldfill = os.fill('0');

os << setw(2) << h << ':' << setw(2) << m;

os.fill( oldfill );

return os;

}

40

The Appointment class

Appointment::Appointment ( const TimeSlot & aTime,

unsigned docNum, const Patient & aPatient )

{

timeSlot = aTime;

doctorNum = docNum;

patientName = aPatient.GetLastName();

patientName.Append( ", " );

patientName.Append( aPatient.GetFirstName() );

}

41

The Appointment class

ostream & operator <<( ostream & os, const Appointment & A )

{

os << "Dr. "

<< Doctor::GetDoctorName(A.doctorNum) << ", "

<< "Time: "

<< A.timeSlot;

return os;

}

42

The Patient class

void Patient::InputName()

{ cout << "Patient's last name: ";

cin >> lastName;

cout << "Patient's first name: ";

cin >> firstName;

}

43

The Patient classunsigned Patient::ChooseDoctor() const{ for(unsigned i = 0; i < NumDoctors; i++) cout << i << ": " << Doctor::GetDoctorName(i) << '\n'; unsigned n = 0; int ok = 0; do { cout << "Enter a doctor number: "; cin >> n; cin.ignore(255,'\n'); if( n >= NumDoctors ) cout << "Number out of range!\n"; else ok = 1; } while( !ok ); return n;}

44

The Patient class

TimeSlot Patient::ChooseTimeSlot( const Doctor & D ) const

{ cout << '\n'

<< "Daily Schedule of Dr. " << D.GetLastName() << '\n'

<< "........................................" << '\n'

<< D.GetSchedule() << '\n'

<< "Enter a time (format hh:mm): ";

TimeSlot aSlot;

cin >> aSlot;

return aSlot;

}

45

The Patient class

ostream & operator <<( ostream & os, const Patient & P )

{

os << "Patient " << P.firstName << ' '

<< P.lastName << '\n'

<< "has been scheduled as follows:" << '\n'

<< P.nextVisit << endl;

return os;

}

46

The DailySchedule class

DailySchedule::DailySchedule(){ for(unsigned i = 0; i < MaxTimeSlots; i++) appointments[i].SetTime( i );}int DailySchedule::IsTimeSlotFree( const TimeSlot & aTime ) const{ unsigned n = aTime.AsInteger(); return !appointments[n].IsScheduled();}void DailySchedule::SetAppointment( const Appointment & app ){ unsigned n = app.GetTime().AsInteger(); appointments[n] = app;}

47

The DailySchedule class

void DailySchedule::ShowAppointments( ostream & os ) const

{

for(unsigned i = 0; i < MaxTimeSlots; i++)

{

if( appointments[i].IsScheduled())

os << appointments[i].GetTime() << " "

<< appointments[i].GetPatientName()

<< endl;

}

}

48

The DailySchedule classostream & operator <<( ostream & os, const DailySchedule & DS )

{ for(unsigned i = 0; i < DS.MaxTimeSlots; i++)

{

os << DS.appointments[i].GetTime();

if( DS.appointments[i].IsScheduled())

os << " *** ";

else

os << " ";

if( i % 4 == 3 ) os << '\n';

}

return os;

}

49

The Doctor classFString Doctor::doctorName[NumDoctors]; //Static member.

Doctor::Doctor()

{ id = 0;}

int Doctor::AddToSchedule( const Appointment & app )

{ if( schedule.IsTimeSlotFree( app.GetTime()))

{ schedule.SetAppointment( app );

return 1;

}

return 0;

}

50

The Doctor class

void Doctor::ShowAppointments( ostream & os ) const

{

os << "Appointments for Dr. "

<< lastName << '\n'

<< ".................................."

<< '\n';

schedule.ShowAppointments( os );

os << endl;

}//cis601source/chap5/doctors/

51

52

53

54

Booch’s OOD

Booch-93 Notations An object is an entity that has a:

A.state: attributes B.behavior: the operations C.Identity: each instance is unique

55

Booch-93 Notations

Modem rate, status, settings;

tranmit(), receive(), and status()

1.A class: Modem

Dashed line symbolizes a class

Class name

Class attributes(data)

Methods,operations or functions

56

Booch-93 Notations

A B: Class A and B are associated

Mouse

Computer

Processor

Memory

Disk

Hard Disk Floppy Disk

A :Abstract Type

57

Booch-93 Notations A B: Class A is-a Class B(inherits) A B: Class A has a Class B (contains) A B: Class A uses Class B (send messages)

Mouse

Computer

Processor

Memory

Disk

Hard DiskFloppy Disk

Printer

Monitor

Keyboard

58

Booch-93 Notations

Process diagram Category diagram Module diagram Class diagram Class specification Object diagram State Transaction diagram Interaction diagram

Static Model

Dynamic Model

59

Module diagram

Subsystemnames

Subsystemnames

SpecificationName(.h)

Body name(.cpp) Main program

name

A B:Module A is dependent on module B

• The module diagram presents a high-level view of the system and partitions a system in terms of subsystems and modules;• A subsystem is a collection of modules;• A module is a collection of classes.

60

Module diagram

Aircraft

Maintenance log Spare Parts

Maintenance subsystem

User Interface Subsystem GUI

Repair Manuals

Multimedia

Is dependent on

61

Category diagram

The category diagram facilitates the presentation and partitioning of a subsystem and module into logical and cohesive categories.

A category organizes a group of classes in a set.

62

Category diagramCategory Name

ClassSpare Parts

List

F16Spare Parts List

F15Spare Parts List

Spare Parts on ordergloabal

63

Class diagram• A class diagram is used to show the

relationships between the classes.• Containment: Identify how a system class

maintains its subsystem class: external & internal.• Cardinality: specify the number of instances

associated classes.• Exactly one: 1• 0 or more : n, 0..n• 1 or more:1..n• Range: 10..30• Range or number:2..4, 8

64

Class diagram

• Properties: is enclosed in an upside-down triangle.• Abstract• Friend• virtual

• Expert controls: identify access levels.• Public• Protected• Private• Implementation.

65

Class diagram

F-14

Engine Wheel

1

1

2 3

Internal Containment

External Containment

A :Abstract Type

F :Friend Type

:Virtual TypeV

66

State Transaction Diagram

Stateactivities

Event[condition]/action

Stop

Start

• Defines the dynamic behavior of an object by identifying possible states. Identifies the events and operations that cause the object to transition from one state to another.

• An event occurs• Guarded Condition is evaluated • Action is performed• State transition takes place

67

Example

Idle

Setup . Do configure modem for receive/transmit

. Do initialize modem buffer/pointers

.Do synchronize communications

Receiving.Do store data in modem buffer

Transmitting.Do transmit data a byte a time

Error.Do log error conditions

Termination.Do flush modem buffer

.Do release phone line

.Do disable modem interrupt

.Do reset hardware Stop

Terminate()Receive()

Initialize Modem Steam

Transmit()

[modem buffer is empty]

Transmit[modem buffer not empty]

Transmit[time out]/set comm. status

[buffer overflow]/set comm. status

Receive()

Start

68

Interaction Diagram

Time Object ObjectEvents

Operation()

• Traces events within a design and defines the messages (operations and events) between the objects.

69

Example

Manager EngineerWork Assignment

Marketing Customer

Design()

Review()

deliver product Sell()Report sales

Lay off()

70

Object Diagram Presents the same information as the interactive

diagram except that it shows greater details Interaction Synchronization Role Visibility Data flow Direction

SourceObject

TargetObject

Order:message

71

Object Diagram

Synchronization:

X

Simple: to depict a single thread control

Synchronous: the operation that takes place after the target object accepts the request.

Timeout: the operation must be completed within a specified amount of time

Asynchronous: sends a message, continues without waiting

Balking: the message is passed only if the target is ready to receive it. The operation is abandoned if not ready

72

Example

Engineer

CustomerMarketing

Manager

1:Work Assignment7:Lay off()

3:Review()

2:Design()

4:deliver Product

6:Report Sales

5:Sell()

73

Maintenance for Object-Oriented Software

Object-Oriented paradigm promotes maintenance

Product consists of independent units Encapsulation (conceptual independence) Information hiding (physical independence) Message-passing is sole communication

74

Obstacles

Three obstacles Complete inheritance hierarchy can be

large Consequences of polymorphism and

dynamic binding Consequences of inheritance

75

Size of Inheritance Hierarchy

class UndirectedTree { ... void displayNode (Node a);

... }

class DirectedTree public: UndirectedTree {

...}

class RootedTree public: DirectedTree { ... void displayNode (Node a);

...

}

76

Size of Inheritance Hierarchy

class BinaryTree public: RootedTree {

… }

class BalancedBinaryTree public: BinaryTree { Node hhh;

displayNode (hhh);

}

77

Size of Inheritance Hierarchy

To find out what displayNode does in BalancedBinaryTree Must scan entire tree Inheritance tree may be spread over entire

product Opposite to ”independent units”

Solution CASE tools can flatten inheritance tree

78

Consequences of Inheritance

Create new subclass by inheritance Does not affect superclasses Does not affect any other subclasses

Modify this new subclass Again, no affect

Modify a superclass All descendent subclasses are affected

79

Consequences of Inheritance

Inheritance can have positive effects on development, negative effects on maintenance

80

Polymorphism and Dynamic Binding

Product fails on invocation myFile.open () Which version of open contains the fault?

CASE tool cannot help (static tool) must trace, need run-time tracer (debugger).

Polymorphism and dynamic binding can have positive effect on development, negative effect on maintenance

81

Software Maintenance

Usually means redesign and re-implementation.

When flexibility, extensibility, and portability are emphasized in the design, maintenance problems can be addressed easily.

82

Re-use code re-use and design are often reasons

behind choosing a new programming language or a new design strategy.

Not enough emphasis is placed on re-use: productivity measured in lines of code. managers may be valued by the size of their

group. profit may be a percentage of the development

cost.

83

Software Re-use Software is reusable if:

it works it is comprehensible it can co-exist with other software not written to co-

exist with. it is supported it is economical (maintenance cost)

Object-Orientation supports re-use, but need tools and standards, such as COM/OLE, CORBA.

84

Readings & Assignments

Reading: Chapter 5