Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 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 2 Activities in Software Development u Problem Analysis u Solution Design u Coding u Documenting u Testing u Maintenance

3 3 Strategy u One basic way to deal with complexity: Divide and Conquer. u Systems can be divided into modules (Objects or Classes). u The challenge is to ensure effective communication between different parts of the program without destroying the divisions.

4 4 Objectives u We are concerned with producing software that satisfies user requirements. u The primary means to do so is to produce software with a clean internal structure.

5 5 The Tasks of OO Design We need to specify: u The needed classes u The public interface u The protected interface

6 6 The Need for a Clean Internal Structure To simplify: u Testing u Porting u Maintenance u Extension u Re-organization u Understanding

7 7 Characteristics of Successful Software It has an extended life where it might be: u worked on by a succession of programmers and designers u ported to new hardware u adapted to unanticipated uses

8 8 The Development Cycle u Create an overall design u Find standard components and then customize the components for this design. u Create new standard components and then customize the components for this design. u Assemble design.

9 9 Design for Change u The system must be designed to remain as simple as possible under a sequence of changes. u Aim for: u flexibility u extensibility u portability u OOD can support the above.

10 10 Design Steps of OOD u Find the Concepts/Classes and their fundamental relationships. u Refine the Classes by specifying the sets of Operations on them u classify these operations: constructors, destructors, etc. u consider minimalism, completeness, and convenience

11 11 Design Steps u Refine the classes by specifying their dependencies on other classes: u Inheritance u Use dependencies u Specify the interfaces for the classes: u separate functions into public and protected operations u specify the exact type of the operations on the classes.

12 12 Finding Classes u Good design must capture and model some aspects of reality. u Look at the application rather than the abstractions. u Usually nouns correspond to classes and verbs represent functions.

13 13 Example u When ordering new videotapes from a supplier, the store manager creates a purchase order, fills in the date, the suppliers 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 stores 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 14 Specifying operations u Consider how an object of the class is constructed, copied, and destroyed. u Define the minimal set of operations required by the concept the class is representing. u Consider which operations could be added for notational convenience and include only important ones.

15 15 Specifying Operations u Consider which operations are to be virtual. u Consider what commonality of naming and functionality can be achieved across all the classes of the component.

16 16 Operations on a Class u Foundation: u Constructors, destructors, and copy operators u Selectors: u Operations that do not modify the state of an object. u Modifiers: u Operations that modify the state of an object.

17 17 Operations on a Class u Conversion Operators: u Operations that produce an object of another type based on the value (state) of the object to which they are applied. u Iterators: u Operations that process data members containing collections of objects.

18 18 Specifying Dependencies u The key dependencies to consider in the context of design are inheritance and use relationships. u Overuse can lead to inefficient and incomprehensible designs.

19 19 Specifying Interfaces u Private functions are not considered at this stage. u The interface should be implementation independent (more than one implementation should be possible). u All operators in a class should support the same level of abstraction.

20 20 Reorganizing the Class Hierarchy u Typically, initial organization of classes may not be adequate and therefore, may have to be reorganize to improve the design and/or implementation. u The two most common reorganizations of a class hierarchy are: u factoring of two classes into a new class. u splitting a class into two new ones.

21 21 Use of Models u Whenever possible, design and programming should be based on previous work. u This allows the designer to focus on a the important issues at any given time.

22 22 Experimentation and Analysis u Prototyping is frequently used for experimenting. u Different aspects of a system may be prototyped independently, such as the graphical user interface. u Analysis of a design and/or implementation can be an important source of insight.

23 23 Example: Doctors office scheduling u Specification: u The program allows to schedule appointments for patients. u The office has multiple doctors, each with a daily schedule divided into 15-minute appointment slots beginning from 8:00am to 6:00pm. u We also want to print out separate daily schedules for each doctor, listing the time and patient name of each appointment. u All output directed to the screen, except for the doctors schedules, which will be written to a file for later printing. u For simplicity: Each doctor has only one appointment day.

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

25 25 Scenario of the process Scheduler requests the patients name; Patient chooses a doctor; Scheduler displays doctors schedule, showing available appointment slots; Patient requests the specific slot; Scheduler adds the appointment to the doctors schedule, and adds the appointment to the patients record; Scheduler confirms the appointment.

26 26 Class dependencies Scheduler Doctor DailyScheduleAppointment Patient :composite(contains) :link(requests, send messages) Fstring(LastName) Fstring(FirstName)

27 27 Operations u Doctor 1. AddToSchedule: Add an appt. to the Drs Sch. 2. ShowAppointment:Display the sch u Patient 1.InputName: 2.ChooseDoctor: 3.ChooseTimeSlot: 4.SetAppointment: Schedule an Appt.

28 28 Operations u 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 u Appointment 1.Constructor: 2.IsScheduled: Find out if an appt schd for the current Appt u Scheduler 1.ScheduleOneAppointment: p-appt-d 2.ScheduleAllAppointments: input p, request d, update d 3.PrintAllAppointment: print all the schd appt for all Ds

29 29 Additional Classes u TimeSlot: u Handles the translation and formatting of appointment times. u FString: u Deals with string data members.

30 30 The TimeSlot class class 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 31 The Appointment class class 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 32 The Patient class class 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 33 The DailySchedule class class 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 34 The Doctor class class 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 35 The Scheduler class class Scheduler { public: Scheduler( Doctor * docs ); void PrintAllAppointments( const char * fileName); int ScheduleOneAppointment(); void ScheduleAllAppointments(); private: Doctor * doctors; };

36 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 37 The Implementation u The Time Slot u h : hour value u sa: the starting appointment time u aph: appointments per hour u m: minute value u al: the appointment length in minutes timeslot = (h-sa)*aph+m/al E.g: timeslot = (12-8)*4+20/15=17 The 17 th slot.

38 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 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 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 41 The Appointment class ostream & operator <<( ostream & os, const Appointment & A ) { os << "Dr. " << Doctor::GetDoctorName(A.doctorNum) << ", " << "Time: " << A.timeSlot; return os; }

42 42 The Patient class void Patient::InputName() { cout << "Patient's last name: "; cin >> lastName; cout << "Patient's first name: "; cin >> firstName; }

43 43 The Patient class unsigned 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 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 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 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 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 48 The DailySchedule class ostream & 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 49 The Doctor class FString 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 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 51

52 52

53 53

54 54 Boochs OOD u Booch-93 Notations u An object is an entity that has a: u A.state: attributes u B.behavior: the operations u C.Identity: each instance is unique

55 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 56 Booch-93 Notations u A B: Class A and B are associated MouseComputerProcessorMemoryDiskHard DiskFloppy Disk A :Abstract Type

57 57 Booch-93 Notations u A B: Class A is-a Class B(inherits) u A B: Class A has a Class B (contains) u A B: Class A uses Class B (send messages) MouseComputerProcessorMemoryDiskHard DiskFloppy Disk PrinterMonitorKeyboard

58 58 Booch-93 Notations u Process diagram u Category diagram u Module diagram u Class diagram u Class specification u Object diagram u State Transaction diagram u Interaction diagram Static Model Dynamic Model

59 59 Module diagram Subsystem names Subsystem names Specification Name(.h) Body name (.cpp) Main program name AB: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 60 Module diagram Aircraft Maintenance log Spare Parts Maintenance subsystem User Interface Subsystem GUI Repair Manuals Multimedia Is dependent on

61 61 Category diagram u The category diagram facilitates the presentation and partitioning of a subsystem and module into logical and cohesive categories. u A category organizes a group of classes in a set.

62 62 Category diagram Category Name Class Spare Parts List F16 Spare Parts List F15 Spare Parts List Spare Parts on order gloabal

63 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 64 Class diagram Properties: is enclosed in an upside- down triangle. Abstract Friend virtual Expert controls: identify access levels. Public Protected Private Implementation.

65 65 Class diagram F-14EngineWheel 1 1 2 3 Internal Containment External Containment A :Abstract Type F :Friend Type :Virtual Type V

66 66 State Transaction Diagram State activities 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 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 68 Interaction Diagram Time Object Events Operation() Traces events within a design and defines the messages (operations and events) between the objects.

69 69 Example Manager Engineer Work Assignment Marketing Customer Design() Review() deliver product Sell() Report sales Lay off()

70 70 Object Diagram u Presents the same information as the interactive diagram except that it shows greater details u Interaction u Synchronization u Role u Visibility u Data flow u Direction Source Object Target Object Order:message

71 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 72 Example EngineerCustomerMarketingManager 1:Work Assignment 7:Lay off() 3:Review() 2:Design() 4:deliver Product 6:Report Sales 5:Sell()

73 73 Maintenance for Object- Oriented Software u Object-Oriented paradigm promotes maintenance u Product consists of independent units u Encapsulation (conceptual independence) u Information hiding (physical independence) u Message-passing is sole communication

74 74 Obstacles u Three obstacles u Complete inheritance hierarchy can be large u Consequences of polymorphism and dynamic binding u Consequences of inheritance

75 75 Size of Inheritance Hierarchy class UndirectedTree {... void displayNode (Node a);... } class DirectedTree public: UndirectedTree {...} class RootedTree public: DirectedTree {... void displayNode (Node a);... }

76 76 Size of Inheritance Hierarchy class BinaryTree public: RootedTree { … } class BalancedBinaryTree public: BinaryTree { Node hhh; displayNode (hhh); }

77 77 Size of Inheritance Hierarchy u To find out what displayNode does in BalancedBinaryTree u Must scan entire tree u Inheritance tree may be spread over entire product u Opposite to independent units u Solution u CASE tools can flatten inheritance tree

78 78 Consequences of Inheritance u Create new subclass by inheritance u Does not affect superclasses u Does not affect any other subclasses u Modify this new subclass u Again, no affect u Modify a superclass u All descendent subclasses are affected

79 79 Consequences of Inheritance u Inheritance can have u positive effects on development, u negative effects on maintenance

80 80 Polymorphism and Dynamic Binding u Product fails on invocation myFile.open () u Which version of open contains the fault? u CASE tool cannot help (static tool) u must trace, need run-time tracer (debugger). u Polymorphism and dynamic binding can have u positive effect on development, u negative effect on maintenance

81 81 Software Maintenance u Usually means redesign and re- implementation. u When flexibility, extensibility, and portability are emphasized in the design, maintenance problems can be addressed easily.

82 82 Re-use u code re-use and design are often reasons behind choosing a new programming language or a new design strategy. u Not enough emphasis is placed on re-use: u productivity measured in lines of code. u managers may be valued by the size of their group. u profit may be a percentage of the development cost.

83 83 Software Re-use u Software is reusable if: u it works u it is comprehensible u it can co-exist with other software not written to co- exist with. u it is supported u it is economical (maintenance cost) u Object-Orientation supports re-use, but need tools and standards, such as COM/OLE, CORBA.

84 84 Readings & Assignments u Reading: u Chapter 5


Download ppt "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."

Similar presentations


Ads by Google