Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring...

23
Programming 2 Object Oriented Programming Daniel POP

Transcript of Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring...

Page 1: Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring objects, attributes and services • OOD principles Case study: University Registration

Programming 2Object Oriented Programming

Daniel POP

Page 2: Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring objects, attributes and services • OOD principles Case study: University Registration

Week 14

Page 3: Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring objects, attributes and services • OOD principles Case study: University Registration

• Software Development Process

– Activities

– Approaches (models)

• Object-Oriented Analysis

– Overview

– Discovering objects

– Object relationships

– Use cases

– Designing the user interface

• Case study: University Registration System

Wrap-up last week

Page 4: Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring objects, attributes and services • OOD principles Case study: University Registration

Agenda

Object-Oriented Design

• Overview and concepts

• Structuring objects, attributes and services

• OOD principles

Case study: University Registration System

Page 5: Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring objects, attributes and services • OOD principles Case study: University Registration

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

Page 6: Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring objects, attributes and services • OOD principles Case study: University Registration

OOD concepts

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

WHAT DO WE DO IN OOD STEP?

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

patterns.

HOW DO WE DO IT?

Page 7: Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring objects, attributes and services • OOD principles Case study: University Registration

Structuring objectsGeneralization-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.

Page 8: Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring objects, attributes and services • OOD principles Case study: University Registration

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.

Page 9: Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring objects, attributes and services • OOD principles Case study: University Registration

Object behaviour

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.

Page 10: Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring objects, attributes and services • OOD principles Case study: University Registration

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.

Page 11: Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring objects, attributes and services • OOD principles Case study: University Registration

Messages are exchanged between objects in order to execute a full 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

Person

+ Age() : double

Object services (II)

Page 12: Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring objects, attributes and services • OOD principles Case study: University Registration

OOD Key PrinciplesMotto: “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 OOD principles are:

• OCP

• DRY

• SRP

• LSP

Page 13: Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring objects, attributes and services • OOD principles Case study: University Registration

Open-Close Principle

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

modification.

Allowing change, but without modifying existing code. It offers flexibility.

Use inheritance to extend/change existing working code and don’t touch working code.

OCP can also be achieved using composition.

class Shape {int type;void drawPolygon() { /* ... */ }void drawPoint() { /* ... */ }

public:void draw();

};

void Shape::draw() {switch(type) {

case POLYGON:drawPolygon();break;

case POINT:drawPoint();break;

}}

class Shape {public:

virtual void draw() = 0;};

class Polygon : public Shape {public:

void draw();};

class Point : public Shape {public:

void draw();};

void Polygon::draw() { /* ...*/ }Void Point::draw() { /* ... */ }

NOK

OK

Page 14: Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring objects, attributes and services • OOD principles Case study: University Registration

Don’t Repeat Yourself

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.

String::String(const char* pch) {if(pch!=NULL) {

str = new char[(sz=strlen(pch))+1];strcpy(str, pch);

}else {

str = NULL;sz = 0;

}}

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;

}}

NOK

OK

/* private */ 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);}

Page 15: Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring objects, attributes and services • OOD principles Case study: University Registration

Single Responsibility PrincipleThe 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 something!

Code will be simpler and easier to maintain.

Example: Container and Iterator (Container manages objects; Iterator traverses the

container)

How to spot multiple responsibilities? Forming sentences ending in itself.

Automobile

Start()Stop()ChangeTires()Drive()GetOilLevel()

The Automobile start itself.

The Automobile stop itself.

The Automobile changeTires itself.

The Automobile Drive itself.

The Automobile getOilLevel itself.

Automobile

Start()Stop()GetOilLevel()

Driver

Drive(Automobile)

Mechanic

ChangeTires(Automobile)

NOK

OK

Page 16: Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring objects, attributes and services • OOD principles Case study: University Registration

Liskov Substitution PrincipleThe 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.

Board

tiles: Tile[][]

getTile(int, int)setTile(Tile, int, int)

3DBoard

tiles3D: Tile[][][]

getTile(int, int, int)setTile(Tile, int, int, int)

void f() {Board* board = new 3DBoard; // ok!// doesn’t make sense for a 3D boardboard->getTile(1,7);

}

All member functions of Board are members of

3DBoard as well (that’s inheritance), but, being

defined for 2D world, they don’t make sense in the

new context (3D world).

NOK

OKTile 3DBoard::getTile(int x, int y, int z) {

return boards[x].getTile(y, z);}

Board

tiles: Tile[][]

getTile(int, int)setTile(Tile, int, int)

3DBoard

boards: Board[]

getTile(int, int, int)setTile(Tile, int, int, int)

Page 17: Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring objects, attributes and services • OOD principles Case study: University Registration

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

Alternative to inheritance.

Advantage over inheritance: behavior can be changed at run-time

class A { public:

virtual void foo() { printf(“An A at work.");

} };

class AA : public A { public:

virtual void foo() { printf("An AA at work.");

} };

class B { A* pa;

public: B(A* aa) : pa(aa) { }

void setA(A* aa) { pa = aa; }

virtual void foo() { // delegate the task to object papa->foo();

}};

void main() {B b(new A);b.foo(); // A behaviorb.setA(new AA);b.foo(); // AA behavior

}

Delegation is best used when you want to use another class’s behavior as is, without changing that

behavior. Example: Board, 3DBoard example

Page 18: Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring objects, attributes and services • OOD principles Case study: University Registration

Class 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 Doesn’t break encapsulation principle

Reusing problems Keeps each class encapsulated and

focused on one task

Large class hierarchies; fewer objects Small class hierarchies; more objects

Page 19: Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring objects, attributes and services • OOD principles Case study: University Registration

Case study: Class Diagrams

• 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), plus

a title.

• Each Student object contains a name and an address (again, inherited from Person) and

a total number of credits earned so far.

Page 20: Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring objects, attributes and services • OOD principles Case study: University Registration

Case study: Class Diagrams• 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.

Page 21: Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring objects, attributes and services • OOD principles Case study: University Registration

Case study: Collaboration DiagramsAdd 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.

Page 22: Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring objects, attributes and services • OOD principles Case study: University Registration

Further 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

Page 23: Design Patterns: Case Study · Object-Oriented Design • Overview and concepts • Structuring objects, attributes and services • OOD principles Case study: University Registration

This is NOT the end….

If you like object oriented analysis and design, you will find design patterns very

interesting. Here is a starting point:

https://popdaniel.wordpress.com/category/teaching/design-patterns/

…or you may want to take a look inside Bruce Eckel’s “Thinking in C++” book:

http://www.lib.ru.ac.th/download/e-books/TIC2Vone.pdf

http://www.lib.ru.ac.th/download/e-books/Tic2Vtwo.pdf

…or to its Java counterpart:

http://pervasive2.morselli.unimo.it/~nicola/courses/IngegneriaDelSoftware/ja

va/ThinkingInJava.pdf

…or join the Timisoara’s Java user group community at

http://www.meetup.com/Timisoara-Java-User-Group/