Sei sulla pagina 1di 67

Object Oriented Programming

Thinking in Objects

Pratian Technologies (India) Pvt. Ltd.


www.pratian.com

Fundamentals of OO Approach

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Fundamentals of Object Oriented Approach


Topics Procedural approach vs. Object-Oriented approach Why choose the OO approach Identifying Classes Building an Object Model
Exercises

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

The procedural approach


APPLICATION

Module 1

Module 2

..

Module N

Program 1

Program 2

Program N

Function 1

Function 2

Function N

Developing an application using the procedural approach would involve


Identification of modules Programs inside each module

Every program would contain several functions and data


The data would be the information necessary for the program and its functions
Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

The procedural approach


Unox Multiplexes Inc

User Module

Admin Module

View Movie Schedule

View movie Review

Book Tickets

Add new Movie

Add new actor

Add new reviewer

Upcoming releases

Search Movie

Add new review

Make movie schedule

Programs

The above example shows a typical procedural approach where we have identified the Modules and Programs

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

{
Programs

The procedural approach


Admin Module Program

Add new Movie

Add new actor

Add new reviewer

Add new review Accept movie information() Set release status of movie() Store Movie information()

Make movie schedule

{
Functions
Copyright 2009 Pratian Technologies www.pratian.com

Assign roles to actor()

We now identify the functions in each program


These are derived from the REQUIREMENTS DOCUMENT The functions are essentially the functionalities to be supported by the program

Thinking in Objects

The procedural approach


We now identify the variables (data) in each program
Program: AddNewMovie Functions: AcceptMovieInformation() SetReleaseStatusOfMovie() StoreMovieInformation() AssignRolesToActor() Data: movieName rating releaseStatus starcast genre posterImage actorRole

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

The procedural approach


Representation of the Program in C
AddNewMovie.h AddNewMovie.c

includes

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

The procedural approach

Client Code starts here

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

The procedural approach


CLIENT
includes includes accesses accesses

X
is comprised of

AcceptMovieInformation(); all the functions share data movieName rating releaseStatus starcast genre posterImage actorRole

AddNewMovie.h

StoreMovieInformation();

SetReleaseStatusOfMovie();

AssignRolesToActor();

includes

// implementations of the functions AcceptMovieInformation() { } StoreMovieInformation() { } SetReleaseStatusOfMovie() { } AssignRolesToActor() { }

AddNewMovie.c

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

The procedural approach


Summary
Deals with functions as the building blocks Easy to start with Higher comfort level for a new programmer Uses Top-Down Design and Decomposition Simple decomposition technique for Modularity Reusability Top down decomposition Managing Complexity

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

The OO Approach
APPLICATION

Module 1

Module 2

..

Module N

Use Case 1

Use Case 2 Use Case N

Class 1

Class 2

Class N

Use Cases are not specific to OO approach. They are popularly used here. However Use Cases can be used in the Procedural approach too.

Developing an application using the Object Oriented approach would involve


Identification of modules Use Cases inside each module

Every Use Case would consist of several classes


For now, treat USE CASES as different functionalities to be supported by a MODULE A detailed discussion about USE CASES is out of scope of our discussion
Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

The OO Approach
User Module: Use Cases

View Movie Schedule WebUser Search Movie

View Movie Reviews

WebUser

Book Tickets WebUser

View upcoming releases

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

The OO Approach
Admin Module: Use Cases

Add new movie

Admin

Admin
Add new actor

Add new r eviewer

Make movie schedule

Admin

Add new review

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Procedural to OO

Actor Info Movie Info

}
We now realize classes from each Use Case
Copyright 2009 Pratian Technologies www.pratian.com

Manager of Movie Info

Essentially classes are identified by using different techniques One of the simple techniques is NOUN-IDENTIFICATION

Thinking in Objects

The OO Model
The OO Model for the Use Case Add New Movie has the following classes
The OO Model shows the classes and the relationships between the classes

AddMovieForm

has

MovieMgr
has

Actor
*

Movie

has

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

The OO approach
Representation of the Classes in Java

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Object-Oriented Programming
Object-oriented programming is a method of implementation in which programs are organized as cooperative collections of objects, each of which represents an instance of some class... Grady Booch

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Why choose the Object Oriented approach?


The OO approach
Deals with classes as the building blocks Allows Real World Modeling The idea of OOP is to try to approach programming in a more natural way by grouping all the code that belongs to a particular object such as an account or a customer together
Project * * ProjMgr 1 1 * * ProjLead

Raise the level of abstraction


Applications can be implemented in the same terms in which they are described by users
Employee

Easier to find nouns and construct a system centered around the nouns than actions in isolation

Manager 1 *

Salesperson

Easier to visualize an encapsulated representation of data and responsibilities of entities present in the domain The modern methodologies recommend the object-oriented approach even for applications developed in C or Cobol

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Classification Identifying Classes

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Identifying Classes
Develop an Object Model for the following requirement in an ILT (instructor-led training): A trainer trains many trainees on a given course. Every course has many modules each module is comprised of different units and each unit has many topics. Identify the different classes from the above problem statement

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Identifying Classes
Recommended Class Identification Technique
Focus on identifying NOUNS (Data Driven approach) We will look at other techniques subsequently

Trainer Trainee Course

Module Unit Topic

Identify the different connections (relationships) between the above classes


Connections between classes established through Relationships Focus on Is-a and Has-a relationships

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Identifying Relationships
Trainer - Trainee Trainer HAS many Trainees Every Trainee HAS a Trainer
Trainer
1

has
*

Trainee

Course - Module Course HAS many Modules

Course
has
*

Module

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Identifying Relationships
Module Unit Module HAS many Units
Module
has
*

Unit

Unit Topic Unit HAS many Topics


Unit
has
*

Topic

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

The OO Model
Trainer
1

has
*

Trainee

Course
has
*

Module
has
*

Unit

has
*

Topic

How do you relate the Trainer & Trainee to the Course?


Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Conceptual Entity - Training


Trainer Training A Trainer (HAS) conducts many Trainings A Training HAS a Trainer Trainer
1

has

Trainee Training A Trainee (HAS) attends many Trainings A Training HAS many Trainees
Trainee
*

Training
*

has

Training
*
Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Conceptual Entity
Training - Course The Training (HAS) (is conducted for) a Course A Course HAS (can have) many Trainings
Training
*

has
1

Course

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Solution
Trainer
1 1

has
*

Trainee
*

has

has

Training
* * 1 * Easy to model real-world problems using the OO approach

Course
has
*

Module
has
*

Unit
Copyright 2009 Pratian Technologies www.pratian.com

has
*

Topic
Thinking in Objects

Acompanysellsdifferentitemstocustomerswhohave A company sells different items to customers who have placedorders.Anordercanbeplacedforseveralitems. However,acompanygivesspecialdiscountstoits However, a company gives special discounts to its registeredcustomers.
Identify the different classes from the above problem statement Identify the different connections (relationships) between the above classes

Object Oriented Programming Concepts

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Object Oriented Programming Concepts


Topics
Types of Objects Structure & Behavior of a Class State, Behavior & Identity Abstraction Encapsulation Hierarchies Inheritance Polymorphism Delegation

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

What are Objects?


An object represents an entity physical, conceptual or software
Physical entity

Employee, Customer, Supplier


Conceptual entity

Sales, Policy, TaxCalculator


Software entity

Linked List, Expression, Connection, etc.


A programmer should make a good effort to capture the conceptual entities in addition to physical entities which are relatively straight forward to identify

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Structure & Behavior


Employee

Mary

Joe are all employees

David

employeeID : integer name : String department : String signIn() signOut() work() takeSalaray()

Classes are set of objects that share a common structure and behavior The structure of a class includes its Primary structure Reused structure The behavior of a class includes its Visible behavior Implementation behavior

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

State, Behavior and Identity


An object is an entity with a well-defined
State Behavior Identity

State
The set of values that an object holds

Behavior
How an object acts and reacts, in terms of its state changes and message passing The visible behavior of an object is modeled by the set of messages it can respond to

Identity
That property of an object which distinguishes it from all other objects

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Basic Object-oriented Principles


Abstraction Encapsulation Hierarchies

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Abstraction
Simply put, public view of an object
Order
AddItems GetItems GetTotal GetStatus Cancel

What should an Order object do?

Abstraction is used to manage complexity


Focus on the essential characteristics To start with, WHAT an Order object does is more important Eliminate the details How the Order object maintains the items How do we Cancel an Order How do we compute the total

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Abstraction
Defines the public contract (The Outside View)
Client1 Order
add Item s() getItems() getOrd erTotal() getStatu s() ca ncel ()

Client2

Client3

Represents commonalities among objects


InternalOrder Order
addItem s() getItems() getOrderTotal () getStatus() cancel ()

getTotal() cancel()

ExternalOrder
getTot al() cancel()

Two types of orders

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Encapsulation
Hide Implementation Details
Encapsulation is
The grouping of related ideas into a single unit, which can thereafter be referred to by a single name. The process of compartmentalizing the elements of an abstraction that constitute its structure and behavior.
Employee
empId : String name : String address : Address getEmpID() : String setEmpId(empId : String) getName() : String setName(name : String) getAddress() : Address setAddress(address : Address)

Encapsulation hides implementation


Promotes modular software design data and methods together Data access always done through methods Often called information hiding

Provides two kinds of protection:


State cannot be changed directly from outside Implementation can change without affecting users of the object

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Encapsulation - Example
Implementation Order
orderNum AS INT custNum AS INT CalculatePrice( ) Public methods of Order

Outside View

PUBLIC: CreateOrder( ) UpdateOrder( ) GetOrderTotal( ) Next( )

CreateOrder UpdateOrder GetOrderTotal Next

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Hierarchies
Object Relationships
Define relationships between objects
Objects defined in terms of other objects Allows state and behavior to be shared and specialized as necessary Encourages code reuse

Two important hierarchy types:


Inheritance (Is-a) Aggregation (Has-a)
Is-a relationship is static (white box) reuse Has-a relationship is dynamic (black box) reuse

Employee

Company

Employee

Manager

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Inheritance
An object oriented system organizes classes into a subclass-super class hierarchy
Inheritance encourages code reuse
Generalization

Each subclass reuses the implementations in the base class


Can add new responsibilities

Mary

Employee

Specialization

Manager
David

Salesperson
Joe

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Polymorphism
One function, many implementations
All employees do some work Mary

Employee work()

Manager
David David does a managers work

Salesperson work()
Joe

work()

Joe does a salespersons work

Early binding
Function Call mapped compilation Function Overloading at

Runtime Polymorphism (late binding) has three requirements:


Hierarchy with overridden method in derived class Base class reference used to call the method

Late binding
Function Call mapped at run-time Function Overriding
Copyright 2009 Pratian Technologies www.pratian.com

Derived class assigned to base class reference Thinking in Objects

Delegation
Delegation is the use of other within a class class
Class forwards method calls to the contained class

Class wraps the delegate class


Creates an instance of the class Defines a stub method for any referenced methods that should be public No access to protected or private members

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Delegation Example
Order references a ShipInfo object

Order
PRIVATE: ShipInfo shipObj = NEW ShipInfo( ) PUBLIC: GetShipDate( ) shipObj:GetDate( )

ShipInfo
PRIVATE: id shipdate promisedate PUBLIC: SetDate( ) GetDate( )

calls

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Thinking in Objects A Case Study

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Thinking in Objects
Topics
Is-a, Has-a and Uses relationships Multiplicity, navigability & role name Case Study
Identifying objects real time Analyze object relationships Handle the complexity of these relationships The tricks of designing a complex system with several collaborating objects

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Classes and Relationships


Six types of relationships can exist between classes
Generalization Realization Association Aggregation Composite Aggregation (Composition) Dependency

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Relationships
Classification
<<Is-a>> <<Has-a>> <<Uses>>

Generalization Realization

Association Aggregation Composition

Dependency

For all practical purposes we will represent Is-a relationship as Has-a relationship as Uses relationship as

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Multiplicity, Navigability & Role name


The Has-a relationships are qualified by Multiplicity
The number of instances with which a class is associated Can be 1, 0..1, *, 1..*, 0..*, 2..*, 5..10, etc. Multiplicity is by default 1

Navigability
Can be unidirectional or bidirectional Navigability is by default bi-directional

Role name
The name of the instance in the relationship Multiple has-a based on different roles are possible

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Exercise 1
See Exercise1.doc Identify the classes Identify the relationships Please focus on relevant OO principles Convey your ideas using simple has-a, is-a or uses notations Specify multiplicity, navigability and role name (where necessary) Focus on classes more than the attributes and methods

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Solution
Consider the following classes
Company Branch Address

Company

2..*

Company has two or more instances of the Branch Instances of Branch called corporate office and registered office are mandatory

Branch

Address

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Explicit role-naming technique


Using this technique it is possible to add greater clarity to the representation
Explicit role-naming Company class Company { Branch cor; Branch reg; Branch[ ] others; };

-others
1

0..*

-reg Branch -cor


1

Address

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Mixed Instance Cohesion


Let us now consider the Customer class and its attributes

Mixed Instance Cohesion (MIC)

Customer
name age c ustId dtMem fees discount t ype dtReg

Not all instances of Customer will need the complete information. Different instances have different cohesion Mixed Instance Cohesion, which is a problem
Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Specialization
Use Specialization to resolve the problem of Mixed Instance Cohesion Customer
name age custId dtMem

RegCustomer
dt Reg t ype fees dis count renewDate t imesRenewed

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Check for instance level cohesion


Notice that the information pertaining to type, fees and discount needs to be properly updated across all the instances of the RegCustomer
Customer
name age custId dtMem

C001 C002 C003 C004 C005 C006 C007 C008

ABC ABC ABC ABC ABC ABC ABC ABC

35 35 35 35 35 35 35 35

10/10/05 10/10/05 10/10/05 10/10/05 10/10/05 10/10/05 10/10/05 10/10/05

A A A B B B C C

2000 2000 2000 5000 5000 5000 15000 15000

5% .... 5% .... 5% .... 10% .... 10% .... 10% .... 15% .... 15% ....

RegCustomer
dtReg t ype fees dis count renewDate t imesRenewed

There is redundancy in the information contained in the RegCustomer class, which is replicated unnecessarily across all its instances belonging to a given type
Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Decompose the class


It is hence important to check for instance level cohesion and eliminate redundancies
RegCustomer
dtR eg renewDate ti mesRenewed

Category
type fees discount

Move the redundant information out of the RegCustomer class into the Category class However, RegCustomer needs to still reuse the information. How do you reuse this information is-a or has-a ?

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Controlled multiplicity
Use has-a there is multiplicity whenever controlled
Customer
custId dtMem

There are many instances of RegCustomer There are a few instances of Category But each instance of RegCustomer does not have its own unique copy of category information (controlled multiplicity)

Controlled Multiplicity

RegCustomer
dtReg renewDate timesRenewed

Category
t ype fees discount

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Class Hierarchy
Consider the Employee classes. A hierarchy is created by the Salesperson and BranchMgr classes. Employee
Branch
empId basic band exp getSalary()

BranchMgr

Salesperson

Every Branch has a BranchMgr A BranchMgr manages a Branch

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Problem of reuse
Both the Employee class and Customer class have some common information like Employee Customer Name
Age Address
empId basic band exp getS alary()
custId dtMem

BranchMgr

Salesperson

RegCustomer
dtReg renewDate timesRenewed

It is hence important to decouple the common information from these two classes into another class and reuse the same How do you promote the reuse (is-a or has-a) ?

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Reuse through Inheritance


Address Person
name age

Employee
empId basic band exp getSalary()

Customer
custId dtMem

Do the Employee and Customer classes have any common abstractions?

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Reuse through Has-a


Address PersonalInfo
name age

Peer classes cannot have common abstractions

Employee
empId basic band exp getSalary()

Customer
custId dtMem

The Employee and Customer classes do not have any common abstractions (i.e. behavior), but only common structure They are known as peer classes Whenever two classes have only common structure (information) and not behavior use has-a relationship
Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Changing rules
Consider the implementation of getSalary() in the Employee class What if the rules change frequently?
Do not associate rules with an entity class Decouple the rules into a conceptual entity known as the SalCalc

Employee
empId basic band exp getSalary()

SalCalc
fi ndSal() fi ndIncen() fi ndAllow()

How will the Employee invoke the methods of the SalCalc ?


Delegation through uses

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Delegation through uses


Employee
empId basic band exp getSalary()

SalCalc
findSal() findIncen() findAllow()

This delegation need not be done by using has-a as the SalCalc does not contain any information, but only methods
Consider making the methods static Avoid creating the instance of SalCalc for each call made to getSalary()

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Associations to the Company


Company
*

Employee
* empId basic band exp getSalary() *

Customer
custId dtMem

Company has many Customers A Customer is associated with many Companies Company has many Employees

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Solution
Explicit role-naming Company
*

Address

PersonalInfo
name age

Peer classes cannot have common abstractions Mixed Instance Cohesion (MIC)

Employee
-others
1
0..*

-reg Branch -cor


1

empId basic band exp getSalary()

Customer
custId dtMem

SalCalc BranchMgr
fi ndSal () fi ndIncen() fi ndAl low()

Controlled Multiplicity Salesperson RegCustomer


dtReg renewDate timesRenewed

Category
type fees discount

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Conclusion

Thinking in objects

The real world is full of objects

Owning a hammer doesnt make one an architect Knowing an object-oriented language is a necessary but insufficient first step to create object systems. Knowing how to think in objects is critical

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Question Time

Copyright 2009 Pratian Technologies www.pratian.com

Thinking in Objects

Potrebbero piacerti anche