Professional Documents
Culture Documents
Lecture 02 (OO Design)
Lecture 02 (OO Design)
OO DESIGN 2
Object…
#1 Class or Object?
Dog
Scooby-Doo
OO DESIGN 3
Object…
#2 Class or Object?
Dog
Scooby-Doo
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() ;
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
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
Employee
is-member-of Department
is-managed-by
manages
Manager
OO DESIGN 10
Object identification
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
request (report)
acknowledge ()
report ()
summarise ()
send (report)
reply (report)
acknowledge ()
OO DESIGN 15
State charts
calibration OK
startup () Waiting test () Testing
Shutdown
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
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:
OO DESIGN 32
Implementation
A line item needs to store a Product object and quantity:
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
*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.
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
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.
OO DESIGN 42
Dependency Inversion Principle
OO DESIGN 43
Dependency Inversion Principle
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()
46
A Segregated ATM UI Example
Balance enquiry Withdraw Change PIN
«interface»
ATM UI
+ GetWithdrawAmountAndAccount()
+ GetBalnceInfo()
+ GetNewPIN()
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
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.