You are on page 1of 57

Object Oriented System

Object Oriented Design


MANISH ARYAL
What is an OBJECT
An instance of a CLASS
Contains meaningful data
Concepts that occupy memory space at runtime are, according to the definition,
objects
◦ If not, they are CLASSES

OO DESIGN 2
Object…
#1 Class or Object?
Dog

Dog is a generalization of Scooby-Doo

Scooby-Doo

OO DESIGN 3
Object…
#2 Class or Object?

Dog

Dog is a subclass of the Animal class


Animal Animal is a generalization of Dog

Scooby-Doo

The concept of subclass!


OO DESIGN 4
Objects and object classes
Objects are entities in a Employee
software system which name: string
represent instances of real- address: string
dateOfBirth: Date
world and system entities employeeNo: integer
socialSecurityNo: string
Object classes are templates department: Dept
for objects ma nager: Employee
salary: integer
◦ Classes may be used to create status: {current, left, retired}
objects taxCode: integer
. ..
Object classes may inherit join ()
attributes and services from leave ()
retire ()
other object classes changeDetails ()

OO DESIGN 5
Object communication
Conceptually, objects communicate by message passing
Messages
◦ The name of the service requested by the calling object.
◦ Copies of the information required to execute the service
and the name of a holder for the result of the service.
In practice, messages are often implemented by procedure (method)
calls
◦ Name = method name
◦ Information = parameter list
◦ Result holder = method return value

OO DESIGN 6
Message examples
// Call a method associated with a buffer
// object that returns the next value
// in the buffer
v = circularBuffer.Get() ;

// Call the method associated with a


// thermostat object that sets the
// temperature to be maintained
thermostat.setTemp(20) ;

OO DESIGN 7
Generalisation and inheritance

Objects are members of classes which define attribute types and operations
Classes may be arranged in a class hierarchy where one class (a super-class) is a
generalisation of one or more other classes (sub-classes)
A sub-class inherits the attributes and operations from its super class and may
add new methods or attributes of its own
It is a reuse mechanism at both the design and the programming level
Inheritance introduces complexity and this is undesirable, especially in critical
systems

OO DESIGN 8
A generalisation hierarchy
Employee

Ma nager Programmer

budgetsControlled project
progLanguage
dateAppointed

Project De pt. Strategic


Ma nag er Ma nager Ma nag er
projects dept responsibilities

OO DESIGN 9
Object Relationships
Objects and object classes participate in relationships with other objects and
object classes
◦ In UML, such a relationship is indicated by an association

Associations may be annotated with information that describes the association

Employee
is-member-of Department

is-managed-by

manages
Manager

OO DESIGN 10
Object identification

Identifying objects (or object classes) is the most difficult part of


object oriented design
There is no “magic formula” for object identification
◦ It relies on the skill, experience and domain knowledge of system designers
Object identification is an iterative process
◦ You are unlikely to get it right first time

OO DESIGN 11
Approaches to identification
Use a grammatical approach based on a natural language description of the system
(used in HOOD method)
Base the identification on tangible things in the application domain
Use a behavioural approach and identify objects based on what participates in what
behaviour
Use a scenario-based analysis – the objects, attributes and methods in each scenario
are identified

OO DESIGN 12
Examples of design models
Sub-system models that show logical groupings of objects into coherent
subsystems
◦ UML package diagrams
Sequence models that show the sequence of object interactions
◦ UML sequence diagrams
State machine models that show how individual objects change their state in
response to events
◦ UML state chart diagrams
Other models include use-case models, aggregation models, generalisation
models, etc.

OO DESIGN 13
Weather station subsystems

OO DESIGN 14
Weather station - data collection sequence

:CommsController :WeatherStation :WeatherData

request (report)

acknowledge ()
report ()
summarise ()

send (report)
reply (report)

acknowledge ()

OO DESIGN 15
State charts

Operation calibrate () Calibrating

calibration OK
startup () Waiting test () Testing
Shutdown

shutdown () transmission done test complete

Transmitting
clock collection
done reportWeather ()
weather summary
Summarising complete
Collecting

OO DESIGN 16
Object Oriented Design Process
Design the view layer classes
◦ Design the macro & micro level user interface, identifying view layer objects
◦ Test usability and user satisfaction
From the UML class diagram, begin to extrapolate the classes to build and
classes to reuse.
Also think about the inheritance structure.
If we have several classes that seem related but have specific differences,
probably it means an inheritance structure.
All designed components must trace back to the user requirements.

OO DESIGN 17
Example: Invoice

OO DESIGN 18
Finding Classes
Keep the following points in mind:
◦ Class represents set of objects with the same behavior
◦ Entities with multiple occurrences in problem description are good candidates for
objects
◦ Find out what they have in common
◦ Design classes to capture commonalities
◦ Represent some entities as objects, others as primitive types
◦ Should we make a class Address or use a String?
◦ Not all classes can be discovered in analysis phase
◦ Some classes may already exist
OO DESIGN 19
CRC Card
CRC Card
Describes a class, its responsibilities, and its collaborators
Use an index card for each class
Pick the class that should be responsible for each method (verb)
Write the responsibility onto the class card
Indicate what other classes are needed to fulfill responsibility
(collaborators)

OO DESIGN 20
CRC Card

OO DESIGN 21
1. Suppose the invoice is to be saved to a file. Name a likely
collaborator.
2. Looking at the invoice, what is a likely responsibility of the
Customer class?
3. What do you do if a CRC card has ten responsibilities?

OO DESIGN 22
Answers
1. FileWriter
2. To produce the shipping address of the customer.
3. Reword the responsibilities so that they are at a higher level, or
come up with more classes to handle the responsibilities.

OO DESIGN 23
Printing an Invoice – Requirements
Task: print out an invoice
Invoice: describes the charges for a set of products in certain quantities
Omit complexities
◦ Dates, taxes, and invoice and customer numbers

Print invoice
◦ Billing address, all line items, amount due

Line item
◦ Description, unit price, quantity ordered, total price

For simplicity, do not provide a user interface


Test program: adds line items to the invoice and then prints it
OO DESIGN 24
Sample Invoice

OO DESIGN 25
Discover classes
Nouns are possible classes

Invoice
Address
LineItem
Product
Description
Price
Quantity
Total
Amount Due

OO DESIGN 26
Analyze classes

Invoice
Address
LineItem // Records the product and the quantity
Product
Description // Field of the Product class
Price // Field of the Product class
Quantity // Not an attribute of a Product
Total // Computed–not stored anywhere
Amount Due // Computed–not stored anywhere

Continued…
OO DESIGN 27
Classes after a process of elimination

Invoice
Address
LineItem
Product

OO DESIGN 28
CRC Cards for Printing Invoice
Invoice must be populated with products and quantities:

OO DESIGN 29
Method Documentation
Use javadoc documentation to record the behavior of the classes
Leave the body of the methods blank
Run javadoc to obtain formatted version of documentation in HTML format
Advantages:
◦ Share HTML documentation with other team members
◦ Format is immediately useful: Java source files
◦ Supply the comments of the key methods

OO DESIGN 30
Method Documentation – Invoice class
/**
Describes an invoice for a set of purchased products.
*/
public class Invoice
{
/**
Adds a charge for a product to this invoice.
@param aProduct the product that the customer ordered
@param quantity the quantity of the product
*/
public void add(Product aProduct, int quantity)
{
}

/**
Formats the invoice.
@return the formatted invoice
*/
public String format()
{
}
}

OO DESIGN 31
Implementation
Invoice aggregates Address and LineItem
Every invoice has one billing address
An invoice can have many line items:

public class Invoice


{
. . .
private Address billingAddress;
private ArrayList<LineItem> items;
}

OO DESIGN 32
Implementation
A line item needs to store a Product object and quantity:

public class LineItem


{
. . .
private int quantity;
private Product theProduct;
}

OO DESIGN 33
Implementation
The methods themselves are now very easy
Example:
◦ getTotalPrice of LineItem gets the unit price of the product and multiplies it
with the quantity
/**
Computes the total cost of this line item.
@return the total price
*/
public double getTotalPrice()
{
return theProduct.getPrice() * quantity;
}

OO DESIGN 34
Which class is responsible for computing the amount due? What are
its collaborators for this task?

OO DESIGN 35
The Invoice class is responsible for computing the amount due. It
collaborates with the LineItem class.

OO DESIGN 36
Suh’s Axioms of OOD

The independence axiom: Maintain independence of components. Each


component must satisfy its requirements without affecting other
requirements.
The information axiom: Minimize the information content of the design.
It is concerned with simplicity. Rely on Occam’s Razor

*Axiomatic design
The methodology was developed by Dr. Suh Nam Pyo at MIT, Department of Mechanical Engineering

OO DESIGN 37
Occum’s Razor rule of simplicity
The best designs usually involve the least complex code but not necessarily
the fewest number of classes or methods.

Minimizing complexity should be the goal, because that produces the most
easily maintained and enhanced application.

In an object-oriented system, the best way to minimize complexity is to use


inheritance and the system’s built-in classes and to add as little as possible
to what already is there.

OO DESIGN 38
Class Design Principles
SRP: The Single Responsibility Principle
OCP: The Open/Closed Principle
LSP: The Liskov Substitution Principle
ISP: The Interface Segregation Principle
DIP: The Dependency Inversion Principle

OO DESIGN 39
The Single Responsibility Principle
A class should have one, and only one, functionality.

OO DESIGN 40
Open/Closed Principle
“Modules should be open for extension, but closed for modification”
-Bertrand Meyer

A principle which states that we should add new functionality by


adding new code, not by editing old code.
Defines a lot of the value of OO programming
Abstraction is the key

OO DESIGN 41
Liskov Substitution Principle
Derived classes must be usable through the base class
interface, without the need for the user to know the difference.

All derived classes must be substitutable for their base classes


This principle guides us in the creation of abstractions.

OO DESIGN 42
Dependency Inversion Principle

Details should depend on abstractions.


Abstractions should not depend on details.

OO DESIGN 43
Dependency Inversion Principle

I. High-level modules should not depend on low-level modules.


Both should depend on abstractions.
II. Abstractions should not depend on details.
Details should depend on abstractions
R. Martin, 1996

 OCP states the goal; DIP states the mechanism


 A base class in an inheritance hierarchy should not know any of its subclasses
 Modules with detailed implementations are not depended upon, but depend
themselves upon abstractions

OO DESIGN 44
Interface Segregation Principle
Helps deal with inappropriate interfaces
Sometimes class methods have various groupings.
These classes are used for different purposes.
Not all users rely upon all methods.
This lack of cohesion can cause serious dependency problems
These problems can be refactored away.

OO DESIGN 45
ATM UI Example
Withdraw Deposit Chenge PIN

«interface»
ATM UI

+ GetWithdrawAmountAndAccount()
+ GetBalanceInfo()
+ GetNewPIN()

French ATM UI English ATM UI

46
A Segregated ATM UI Example
Balance enquiry Withdraw Change PIN

«interface» «interface» «interface»


ATM Balance enquiry UI ATM Withdraw UI ATM PIN Change UI

+ GetBalanceInfo() + GetWithdrawAmountAndAccount + GetNewPIN()

«interface»
ATM UI

+ GetWithdrawAmountAndAccount()
+ GetBalnceInfo()
+ GetNewPIN()

French ATM UI English ATM UI

47
Dependency Management
What is dependency?
What is dependency management?
What bearing does DM have on software?
What is the result of poor DM?
What is the advantage of good DM?

48
What is dependency?
Cohesion
◦ Internal dependency

Coupling
◦ External dependency

49
What is dependency management?
A simple idea - as interdependencies increase, features like reusability,
flexibility, and maintainability decrease.
Dependency management is controlling interdependencies.

50
What bearing does DM have on software?
Coupling and cohesion are the eternal concerns of software
development
One can say that OO is just a set of tools and techniques for Dependency
Management

51
What is the penalty for practicing poor
DM?
A system with poor dependency structure will typically exhibit these
four negative traits:

It is rigid
It is fragile
It is not reusable

52
It is Rigid
Rigidity is the inability to be changed

The impact of a change cannot be predicted


If not predicted, it cannot be estimated
Time and cost cannot be quantified
Managers become reluctant to authorize change

53
It is Fragile
Software changes seem to exhibit non-local effects
A single change requires a cascade of subsequent
changes
New errors appear in areas that seem unconnected to
the changed areas
Quality is unpredictable.
The development team loses credibility

54
It is not reusable
Desirable parts of the design are
dependent upon undesirable parts
The work and risk of extracting the
desirable part may exceed the
cost of redeveloping from scratch.

55
What is the benefit of good DM?
Interdependencies are managed, with firewalls separating
aspects that need to vary independently.
More Flexible
Easier to reuse
Less fragile,
the bugs are boxed in
Easier to make the right change
56
Thank You.

You might also like