Transcript Document

Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică

Object Oriented Programming

Lect. Dr. Daniel POP

Course #13 Agenda

Object-Oriented Design Overview and concepts OOD principles Error handling in OO systems Case study (continued) Programming II Object-Oriented Programming 2

Object-oriented design

DEFINITION [Object-oriented design] OOD analysis.

is the discipline of defining the objects and their interactions to solve a business problem that was identified and documented during object oriented

Covers software architecture activities of software development process.

Inputs of OOD step: Deliverables of OOA step (conceptual model, use cases, UI documentation, other documents) • Deliverables (output) of OOD step • Class diagram – static structure diagram that describes the structure of a system by showing the system's classes, their attributes, and the relationships between the classes; • Sequence diagram – shows different processes or objects that live simultaneously, and the messages exchanged between them, in the order in which they occur.

Programming II Object-Oriented Programming 3

OOD concepts

WHAT DO WE DO IN OOD STEP?

Define objects: i dentify attributes, behavior and services exposed by objects.

Create class diagram from conceptual diagram. Define application framework (if applicable): Application framework is a term usually used to refer to a set of libraries or classes that are used to implement the standard structure of an application for a specific operating system. By bundling a large amount of reusable code into a framework, much time is saved for the developer, since he/she is saved the task of rewriting large amounts of standard code for each new application that is developed. Identify persisted objects/data (if applicable): Identify objects that have to be persisted. If relational database is used design the object relation mapping (data layout and database services). Identify, define remote objects (if applicable).

Evaluate existing OO programming language and choose the most appropriate one Evaluate the OO design Define the testing strategy: unit testing, non-regression testing, integration testing etc.

HOW DO WE DO IT?

Base on experience, “common-sense”, using OOD principles and design patterns.

Programming II Object-Oriented Programming 4

Structuring objects

Generalization-specialization hierarchies (is-a) – use inheritance to factor-out common attributes and behavior of discovered objects does the union of all specializations cover the set described by generalization?

are the specializations mutually exclusive?

Example: Shape, Ellipse, Point Multiple inheritance tend to complicate the hierarchy; conflicts may appear between similar attributes/behavior inherited from the two distinct base classes; should be used with “caution”; Java-like approach: extend a single representation and implement many behaviors “Multiple inheritance is like a parachute; you don’t always need it, but when you do, you’re really happy to have it at hand.”, G. Booch Whole-part hierarchies (has-a) Example: Person has 1 Body, 0 or 2 Arms, 1 Head etc.; A Polyline has 2..N Points.

the whole does not inherit behavior from parts => inheritance is not applicable here.

usually, whole-part relationships are identified after gen-spec Note: Attributes and behavior are added in later steps.

Programming II Object-Oriented Programming 5

Object attributes

Discovering attributes use a “first-person” perspective (“personification”); analyze the problem, interview the customer Placing attributes in a class hierarchy – which class in a hierarchy is the most appropriate place-holder for an attribute?

Define attribute domain, i.e. what are the legal values the attribute can take.

The relationships between objects are implemented as attributes as well, but these attributes aren’t explicitly presented as “normal” object’s attributes, though they are part of the object’s state During this phase, the class hierarchy is revised Examples: a Point has 2 coordinates, denoted X, Y that can only take positive values.

Programming II Object-Oriented Programming 6

Object behavior

DEFINITION [Behavior, Service] A behavior describes an activity of an object. A service defines the relationship to other model components.

Represented using UML’s behavior and interaction diagrams (e.g. Activity, State Machine etc.) Identify possible object’s states and then explore meaningful connections (state changes).

Have all states been defined? Are all the states reachable? In each state, does the object respond properly to all possible conditions?

Involve interactions with other objects that will be detailed in object services.

Example: Add Department Add Department - this diagram shows how new departments are added to the system. The process starts by the user pressing the “Add Department” button on the University window. This brings up a small dialog where the name of the new department can be entered. When the user presses OK, a create message is sent to create the new Department. This message contains a single attribute: the name of the new Department. Programming II Object-Oriented Programming 7

Object services (I)

Discovering required services (= member functions) based on their types: implicit services: create a new instance (constructor), destructor, get/set value of attributes (getter/setter) etc. (usually not shown in diagrams) services associated with message connections: identify the messages sent to that objects in previous steps and add services to handle them; can be suggested by behavior diagram(s) services associated with object relationships: establish/disconnect the relationships between objects (relationships have been identified in OOA phase) (e.g. Polyshape has Points => add/remove/change points to polyshape object) services associated with attributes: protect some attributes, modify an attribute only together with other attribute, synchronization in real-time systems etc.

Programming II Object-Oriented Programming 8

Object services (II)

Messages are exchanged between objects in order to carry out a service.

Graphical representation: as member functions in class diagram as message connectors in various interaction diagrams (Collaboration/Sequence, Communication, Interaction etc.) Implemented as public member functions Example: dynamic representation – see AddSection in the Case Study section static representation Programming II

Person

+ Age() : double Object-Oriented Programming 9

OOD key principles (I)

Motto: “Imitation is the sincerest form of not being stupid.”

DEFINITION [Design principle] A design principle is a basic tool or technique that can be applied to designing or writing code to make that code more maintainable, flexible, or extensible.

Key principles are: OCP DRY SRP LSP Programming II Object-Oriented Programming 10

OOD key principles (II)

(1) The Open-Closed Principle (OCP). Classes should be open for extension and closed for modification.

Allowing change, but without modifying existing code. Use inheritance to extend/change existing working code and don’t touch working code.

Example: class Shape, method draw It offers flexibility.

OCP can also be achieved using composition.

Programming II Object-Oriented Programming 11

OOD key principles (III)

(2) The Don’t Repeat Yourself Principle (DRY). Avoid duplicate code by abstracting out things that are common and placing those things in a single location.

No duplicate code => ONE requirement in ONE place!

This principle can and should be applied everywhere (e.g. in Analysis phase – don’t duplicate requirements or features!) Code is easier and safer to maintain because we have to change only one place.

Example (Lab 4, class String, methods: constructor and set): } String::String(const char* pch) { if(pch!=NULL) { str = new char[(sz=strlen(pch))+1]; strcpy(str, pch); } else { str = NULL; sz = 0; } Programming II void String::set(const char* pch) { if(str!=NULL) delete [] str; if(pch!=NULL) { str = new char[(sz=strlen(pch))+1]; strcpy(str, pch); } else { str = NULL; sz = 0; }

WRONG!!

12

Solution: corrected String class

OOD key principles (IV)

} /*private*/ void String::init(const char* pch) { if(pch!=NULL) { str = new char[(sz=strlen(pch))+1]; strcpy(str, pch); } else { str = NULL; sz = 0; } } String::String(const char* pch) { init(pch); } void String::set(const char* pch) { if(str!=NULL) delete [] str; init(pch)

GOOOOD!

!

Programming II Object-Oriented Programming 13

OOD key principles (V)

(3) The Single Responsibility Principle (SRP). Every object in your system should have a single responsibility, and all the object’s services should be focused in carrying out that single responsibility.

ONLY one reason to change!

Code will be simpler and easier to maintain.

Example: Container and Iterator (Container stores objects; Iterator traverses the container) Spotting multiple responsibilities.

Example: Automobile class

Automobile

Start() Stop() ChangeTires() Drive() CheckOil() GetOil() The Automobile start itself.

The Automobile The Automobile The Automobile The Automobile The Automobile stop itself.

changeTires itself.

Drive itself.

CheckOil itself.

GetOil itself.

Programming II Object-Oriented Programming Follows SRP.

Violates SRP.

14

OOD key principles (VI)

Solution: corrected Automobile class

Automobile

Start() Stop() GetOil() Drive

Driver

Drive(Automobile)

Mechanic

ChangeTires(Automobile) CheckOil(Automobile) Programming II Object-Oriented Programming 15

OOD key principles (VII)

(4) The Liskov Substitution Principle (LSP). Subtypes must be substitutable for their base types.

Well-designed class hierarchies Subtypes must be substitutable for their base class without things going wrong.

Example:

Board

tiles: Tile[][] } void f() { Board* board = new 3DBoard; // ok!

board->getTile(1,7); // doesn’t make sense for a 3D board getTile(int, int) setTile(Tile, int, int)

3DBoard

tiles3D: Tile[][][]

WRONG: VIOLATES LSP!!

All member functions of Board are members of 3DBoard as well (that’s inheritance).

Member functions of Board class, being defined for 2D world, don’t make sense in the new context (3D world) getTile(int, int, int) setTile(Tile, int, int, int) Programming II Object-Oriented Programming 16

OOD key principles (VIII)

Solution: use association instead of inheritance

Board 3DBoard

tiles: Tile[][] getTile(int, int) setTile(Tile, int, int) * boards boards: Board[] getTile(int, int, int) setTile(Tile, int, int, int) Remark: A 3DBoard stores an array of Board objects. Member functions of 3DBoard use the functionality of Board, rather than extend it (delegate responsibilities).

Tile 3DBoard::getTile(int a, int b, int c) { return boards[a].getTile(b, c); } Programming II Object-Oriented Programming 17

Delegation (“design pattern”)

DEFINITION [Delegation] Delegation is handing of a task over another object.

Alternative to inheritance.

Advantage over inheritance: behavior can be changed at run-time Example: class A { public: virtual void foo() { printf("Object A doing the job."); } }; class B { A a; public: virtual void foo() { // delegate the task to object a a.foo(); } }; class B { A* pa; public: B(A* aa) : pa(aa) { } virtual void foo() { // delegate the task to object pa pa->foo(); } }; class AA : public A { public: virtual void foo() { printf("AA at work."); } }; Delegation is best used when you want to use another class’s behavior as is, without changing that behavior. Example: Board, 3DBoard example } void f() { // A behavior B b1(new A); b1.foo(); // AA behavior B b2(new AA); b2.foo(); Programming II Object-Oriented Programming 18

Other OOD principles

Inheritance Classes (implementation, representation) – tend to couple implementation Interfaces (functionality) – provide a clean and powerful way of expressing concepts (and relationships between them) without encumbering them with impl. details or run-time overheads

Program to interfaces

use interfaces (and classes on top of classes hierarchies) for objects use creational design patterns to create objects

Achieve new functionalities by combining objects Encapsulate what varies

Programming II Object-Oriented Programming 19

Class inheritance vs. object composition

Class inheritance (white-box)

Visibility Static (compile time) Easy to understand (and use) Breaks encapsulation principle Reusing problems Large class hierarchies; fewer objects Example: Board, 3DBoard

Object composition (black-box)

Reuse Dynamic (can change at run-time through instantiation) Difficult to understand Doesn’t break encapsulation principle Keeps each class encapsulated and focused on one task Small class hierarchies; more objects Programming II Object-Oriented Programming 20

OOD advices

Programming II Object-Oriented Programming 21

Error handling in OO systems

Exception-handling is not local (i.e. exception are thrown in one part of the program and handled elsewhere)  We need a simple, explicit, and global strategy.

can Error handling involves a multi-level approach: each level copes with as many errors as it terminate() – used if error handling system is “corrupted” unexpected() – intended to provide an escape when exception-specifications firewall fails (function written in other languages don’t obey to this, implementing locally reliability dramatically increases complexity and overhead of large programs) Use a consistent error handling mechanism (based on exceptions) convert/adapt other mechanism (e.g. based on errno global variable, or based on return codes) to the common one  we need to Use hierarchies to handle various types of error; Advantages: easy to understand, avoid infinite loops, embodies semantic information in types.

Use resource allocation is initialization and other similar techniques to make the code more regular.

Programming II [Stroustrup, 1997] Bjarne Stroustrup – The C++ Programming Language 3rd Edition, Addison Wesley, 1997 [Section 14.9] Object-Oriented Programming 22

Class Diagrams

Case study (I)

This diagram shows that Teacher and Student are both subclasses of Person.

Each Person object contains a name and an address.

Each Teacher object contains a name and an address (both inherited from Person) and a title.

Each Student object contains a name and an address (again inherited from Person) and a total number of credits received so far.

Programming II Object-Oriented Programming 23

Class Diagrams

Programming II

Case study (II)

These diagrams show the view classes associated with the University, Department, Course and Section classes. The UniversityView class contains a method which creates a university window. This window displays the University’s name, address, and phone number. It also displays a list of the departments in the university.

The UniversityView class also contains code for creating a small dialog where the name of a new department can be entered. This dialog is brought up by pressing the “Add Department” button on the university window.

The DepartView class contains a method which creates a department window. This window displays the department’s name. It displays a list of the teachers employed by the department. It displays a list of the students supervised by the department. The last item displayed by the window is a list of the courses offered by the department. There are buttons on the window for adding new teachers, new students, and new courses.

The DepartView class also contains code which creates a small dialog where a new course’s number and title can be entered. This dialog is brought up by pressing the “Add New Course” button on the department window.

The AddSectionView class contains a method for creating the AddSection window. This window has fields for entering a new section’s course number, teacher’s name, days of the week, and start and end times. The OK button at the bottom is pressed to actually add the section to the system. The new section will be assigned the next available section number, ie. if the course already has sections 1 and 2, then this section will get a section number of 3.

The AddStudentToSectionView class contains methods for interacting with a student via a touch-tone telephone. The student can enter the course number and section number and their name.

The CourseView class contains a method which creates a Course window. This window displays the course’s title, number, description, and credits. This window also displays a list of the sections offered.

The SectionView class contains a method which creates a Section window. This window displays the section’s number, days of the week, and start and end times. The window also displays the teacher teaching this section and a list of the students signed up for this section.

Object-Oriented Programming 24

Case study (III)

Collaboration / Sequence Diagrams

Programming II Add Department - this diagram shows how new departments are added to the system. The process starts by the user pressing the “Add Department” button on the University window. This brings up a small dialog where the name of the new department can be entered. When the user presses OK, a create message is sent to create the new Department. This message contains a single attribute: the name of the new Department. Add Section - this diagram shows how a new section is added to the system. The process starts in the AddSectionView where a course number, teacher’s name, days of the week, and start and end times are entered. When the user presses the “OK” button, an addSection message is sent to the Department object. This message contains all the information entered. The Department object receives this message and converts the course number to a pointer to the Course object so that it can then send a message to this Course Object. The teacher’s name is converted to a pointer to the Teacher object. Then an addSection message is sent from the Department object to the Course object. This message contains a pointer to the teacher who is teaching the course, the days of the week, and the start and end times.

The Course object receives this message and then sends a create message to get this new Section object created. This create message contains six arguments: a pointer back to the Course object (needed because all Section objects have links back to the associated Course object), a pointer to the teacher teaching this Course, the number of this Section (computed by the Course object since it will know how many Sections have already been created), the days of the week, and the start and end times. The Course object will get back a pointer to this new Section which it should add to its list of Sections.

During the creation of the new Section, an addSection message must be sent to the Teacher who is teaching the course so that this Teacher object can update its list of Sections which it is teaching.

To consider: — How does the CSDept object convert “Mary Smith” to a pointer (t) to the corresponding teacher object?

— How does the CSDept object convert 302 to the CS302 Course object?

Object-Oriented Programming 25

Case study (IV)

Homework :

Complete the design phase (for the following functionalities: add course, add teacher, add student, add student to section, print student’s course list, print teacher’s section rosters) Implement the system in C++ Programming II Object-Oriented Programming 26

Further Reading

[McLaughlin, 2006] Brett McLaughlin , Gary Pollice , David West Oriented Analysis and Design, O'Reilly, 2006 [Pages 376-406] – Head First Object-

[Sussenbach, 1999] Rick Sussenbach – Object-oriented Analysis & Design (5 Days), DDC Publishing Inc, 1999, ISBN 1562439820, [Chapter 13, 14] [Yourdon, 1994] Edward Yourdon – Object-oriented Systems Design, Prentice-Hall International Inc, 1994 [Chapter 12, 13, 14] [Stroustrup, 1997] Bjarne Stroustrup – The C++ Programming Language 3rd Edition, Addison Wesley, 1997 [Section 12.4 – 12.6] – A OOD case study for a user interface hierarchy Programming II Object-Oriented Programming 27