Title: Object Oriented Programming
1Object Oriented Programming
Universitatea de Vest din Timisoara
Facultatea de Matematica si Informatica
2Course 13 Agenda
- Object-Oriented Design
- Overview and concepts
- OOD principles
- Error handling in OO systems
- Case study (continued)
3Object-oriented design
- DEFINITION Object-oriented design OOD is the
discipline of defining the objects and their
interactions to solve a business problem that was
identified and documented during object oriented
analysis. - 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.
4OOD concepts
WHAT DO WE DO IN OOD STEP?
- Define objects identify 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.
5Structuring 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
dont always need it, but when you do, youre
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
gt inheritance is not applicable here. - usually, whole-part relationships are identified
after gen-spec - Note Attributes and behavior are added in
later steps.
6Object 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 arent explicitly presented as
normal objects attributes, though they are
part of the objects state - During this phase, the class hierarchy is
revised - Examples a Point has 2 coordinates, denoted X,
Y that can only take positive values.
7Object behavior
- DEFINITION Behavior, Service A behavior
describes an activity of an object. A service
defines the relationship to other model
components. - Represented using UMLs behavior and
interaction diagrams (e.g. Activity, State
Machine etc.) - Identify possible objects 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.
8Object 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 gt
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.
9Object 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
10OOD 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
11OOD 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 dont touch working code. - Example class Shape, method draw
- It offers flexibility.
- OCP can also be achieved using composition.
12OOD key principles (III)
- (2) The Dont 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 gt ONE requirement in ONE
place! - This principle can and should be applied
everywhere (e.g. in Analysis phase dont
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)
StringString(const char pch)
if(pch!NULL) str new
char(szstrlen(pch))1 strcpy(str,
pch) else str NULL
sz 0
void Stringset(const char pch)
if(str!NULL) delete str if(pch!NULL)
str new char(szstrlen(pch))1
strcpy(str, pch) else
str NULL sz 0
WRONG!!
13OOD key principles (IV)
- Solution corrected String class
/private/ void Stringinit(const char pch)
if(pch!NULL) str new
char(szstrlen(pch))1 strcpy(str,
pch) else str NULL
sz 0
StringString(const char pch)
init(pch) void Stringset(const char pch)
if(str!NULL) delete str
init(pch)
GOOOOD!!
14OOD key principles (V)
- (3) The Single Responsibility Principle (SRP).
Every object in your system should have a single
responsibility, and all the objects 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
Follows SRP. Violates SRP.
The Automobile start itself. The Automobile
stop itself. The Automobile changeTires
itself. The Automobile Drive itself. The
Automobile CheckOil itself. The Automobile
GetOil itself.
Automobile Start() Stop() ChangeTires() Drive
() CheckOil() GetOil()
15OOD key principles (VI)
- Solution corrected Automobile class
16OOD 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
void f() Board board new 3DBoard //
ok! board-gtgetTile(1,7) // doesnt make
sense for a 3D board
- All member functions of Board are members of
3DBoard as well (thats inheritance). - Member functions of Board class, being defined
for 2D world, dont make sense in the new context
(3D world)
WRONG VIOLATES LSP!!
17OOD key principles (VIII)
- Solution use association instead of inheritance
boards
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 3DBoardgetTile(int a, int b, int c)
return boardsa.getTile(b, c)
18Delegation (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
- Delegation is best used when you want to use
another classs behavior as is, without changing
that behavior. Example Board, 3DBoard 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-gtfoo() class AA public A
public virtual void foo() printf("AA at
work.")
void f() // A behavior B b1(new A)
b1.foo() // AA behavior B b2(new
AA) b2.foo()
19Other 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
20Class inheritance vs. object composition
Class inheritance (white-box) Object composition (black-box)
Visibility Reuse
Static (compile time) Dynamic (can change at run-time through instantiation)
Easy to understand (and use) Difficult to understand
Breaks encapsulation principle Doesnt break encapsulation principle
Reusing problems Keeps each class encapsulated and focused on one task
Large class hierarchies fewer objects Small class hierarchies more objects
21OOD advices
22Error 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. - Error handling involves a multi-level approach
each level copes with as many errors as it can - terminate() used if error handling system is
corrupted - unexpected() intended to provide an escape
when exception-specifications firewall fails
(function written in other languages dont obey
to this, implementing locally reliability
dramatically increases complexity and overhead of
large programs) - Use a consistent error handling mechanism
(based on exceptions) ? we need to convert/adapt
other mechanism (e.g. based on errno global
variable, or based on return codes) to the common
one - 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.
Stroustrup, 1997 Bjarne Stroustrup The C
Programming Language 3rd Edition, Addison Wesley,
1997 Section 14.9
23Case 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.
24Case 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 Universitys 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 departments 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 courses
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 sections course
number, teachers 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
courses 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 sections 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.
25Case study (III)
- Collaboration / Sequence Diagrams
- 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, teachers 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 teachers 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?
26Case study (IV)
- Complete the design phase (for the following
functionalities add course, add teacher, add
student, add student to section, print students
course list, print teachers section rosters) - Implement the system in C
27Further Reading
-
- McLaughlin, 2006 Brett McLaughlin, Gary
Pollice, David West Head First Object-Oriented
Analysis and Design, O'Reilly, 2006 Pages
376-406 - 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