48
Chapter 17 – Chapter 17 – Object-Oriented Object-Oriented Design Design

Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Embed Size (px)

Citation preview

Page 1: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Chapter 17 – Chapter 17 – Object-Oriented Object-Oriented

DesignDesign

Page 2: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Chapter GoalsChapter Goals To learn about the software life cycle To learn about the software life cycle

To learn how to discover new classes and methods To learn how to discover new classes and methods

To understand the use of CRC cards for class To understand the use of CRC cards for class

discovery discovery

To be able to identify inheritance, aggregation, To be able to identify inheritance, aggregation,

and dependency relationships between classes and dependency relationships between classes

To master the use of UML class diagrams to To master the use of UML class diagrams to

describe class relationships describe class relationships

To learn how to use object-oriented design to To learn how to use object-oriented design to

build complex programs build complex programs

Page 3: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Software Life CycleSoftware Life Cycle

Software Life Cycle: all activities from Software Life Cycle: all activities from initial analysis until obsolescence initial analysis until obsolescence Formal process for software developmentFormal process for software development

Describes phases of the development Describes phases of the development process process

Gives guidelines for how to carry out the Gives guidelines for how to carry out the phases phases

Page 4: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Software Life CycleSoftware Life Cycle

1.1. Analysis Analysis

2.2. Design Design

3.3. Implementation Implementation

4.4. Testing Testing

5.5. Deployment / OperationDeployment / Operation

Page 5: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

1. Analysis1. Analysis

Decide Decide whatwhat the project is suppose to do, the project is suppose to do, what the goal of the final product iswhat the goal of the final product is Do Do NOTNOT think about think about howhow the program will the program will

accomplish tasks accomplish tasks

Output of this phase - requirements Output of this phase - requirements document document Describes what program will do once Describes what program will do once

completed completed Example – Example –

User manual: tells how user will operate program User manual: tells how user will operate program Performance criteria (will complete X tasks in Y Performance criteria (will complete X tasks in Y

time)time)

Page 6: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

2. Design2. Design

Plan for implementationPlan for implementation

Decide what structures will best suit your taskDecide what structures will best suit your task

In object-oriented programming, this is In object-oriented programming, this is choosing the classes and methods to use (and choosing the classes and methods to use (and create)create)

Output: Classes and methods descriptionOutput: Classes and methods description Usually diagramed using UML, can use CRC cardsUsually diagramed using UML, can use CRC cards

Page 7: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

3. Implementation3. Implementation

Actual coding part of the processActual coding part of the process

Edit Edit Compile Compile Run Run

Output: Completed programOutput: Completed program

Page 8: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

4. Testing4. Testing

Run tests to verify the program works Run tests to verify the program works correctlycorrectly

Remember the two main types of Remember the two main types of testingtesting Unit TestingUnit Testing System TestingSystem Testing

Output: a report of the tests and their Output: a report of the tests and their

results results

Page 9: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

5. Deployment5. Deployment

AKA Operation, MaintenanceAKA Operation, Maintenance Users install program Users install program

Users use program for its intended Users use program for its intended purpose purpose

Bug fixesBug fixes

New featuresNew features

Page 10: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

ExampleExample

Analysis – the specs we provideAnalysis – the specs we provide Design – We provided for first four Design – We provided for first four

assignments, what you did for A5assignments, what you did for A5 Implementation – the code you write Implementation – the code you write

to solve the specsto solve the specs Testing – PathTester, Testing – PathTester,

BankAccountTester, etc.BankAccountTester, etc. Deployment – TAs using your program Deployment – TAs using your program

on sample runs. Our reaction is your on sample runs. Our reaction is your gradegrade

Page 11: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Perfect WorldPerfect World

In a perfect world, everything would In a perfect world, everything would flow perfectly in this processflow perfectly in this process Output from one phase signifies it is Output from one phase signifies it is

complete and can start the next phasecomplete and can start the next phase

Doesn’t really workDoesn’t really work You’ve probably noticed thisYou’ve probably noticed this Was anyone’s A5 perfect?Was anyone’s A5 perfect? Have your tests every worked Have your tests every worked

completely?completely?

Page 12: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Waterfall ModelWaterfall Model

Page 13: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Problems with Waterfall Problems with Waterfall ModelModel Specs usually have flawsSpecs usually have flaws

ContradictionsContradictions Non-thorough (what needs to happen on Non-thorough (what needs to happen on

bad input?)bad input?)

Design too complicated, Design too complicated, implementation flawedimplementation flawed

Testing incompleteTesting incomplete

Page 14: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

What’s the flaw?What’s the flaw?

Customer didn’t know what to Customer didn’t know what to expectexpect How can you fully specify what the How can you fully specify what the

program needs to do without seeing it?program needs to do without seeing it?

Analogous to the edit-compile-run Analogous to the edit-compile-run cyclecycle Never get it right the first time, have to Never get it right the first time, have to

iterate back to prior phasesiterate back to prior phases

Page 15: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Spiral ModelSpiral Model

Breaks development process down Breaks development process down into multiple phases into multiple phases

Early phases focus on the Early phases focus on the construction of construction of prototypesprototypes Shows some aspects of the final product Shows some aspects of the final product

quick implementation quick implementation Aren’t deployed to the user, used to Aren’t deployed to the user, used to

reconsider analysisreconsider analysis Lessons learned from development of Lessons learned from development of

one prototype can be applied to the one prototype can be applied to the next iteration next iteration

Page 16: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Deployment

Testing

Implementation

Design

Analysis

SpiralSpiral

Prototype 2

Final Product

Prototype 1

Page 17: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

SpiralSpiral

Increased probability of developing a Increased probability of developing a quality interface/systemquality interface/system

Problem: can lead to many Problem: can lead to many iterations, and process can take too iterations, and process can take too long to complete long to complete high cost and high cost and low throughputlow throughput

Page 18: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Extreme ProgrammingExtreme Programming

Approach suggested by Kent Back in Approach suggested by Kent Back in 19991999

Goal: SimplicityGoal: Simplicity Cut out formal structureCut out formal structure Focus on set of practices to make Focus on set of practices to make

programming more efficient and programming more efficient and satisfactorysatisfactory

Page 19: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Extreme ProgrammingExtreme Programming

Realistic planningRealistic planning: Customers make : Customers make business decisions (what should it look business decisions (what should it look like?), programmers make technical ones like?), programmers make technical ones (how do we that?)(how do we that?)

Small Releases Small Releases – start small, update later– start small, update later MetaphorMetaphor – common story among – common story among

programmersprogrammers Simplicity Simplicity – simple solution is best– simple solution is best TestingTesting – by everyone! – by everyone! Refactoring Refactoring – restructure as you go– restructure as you go

Page 20: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Extreme ProgrammingExtreme Programming

Pair ProgrammingPair Programming Collective OwnershipCollective Ownership Continuous OrganizationContinuous Organization 40-hour week40-hour week On-site customerOn-site customer Coding standardsCoding standards

Page 21: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Surprising resultsSurprising results

Studies have shown that the common Studies have shown that the common sense approaches are synergistic, work sense approaches are synergistic, work better togetherbetter together

Shows coding is not all of software Shows coding is not all of software developmentdevelopment

Let’s talk more about designing…Let’s talk more about designing…

Page 22: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Discovering ClassesDiscovering Classes

Recall that part of the design phase is Recall that part of the design phase is deciding what structures you need to deciding what structures you need to solve a tasksolve a task

In OOD this translates into 3 stepsIn OOD this translates into 3 steps Discover classesDiscover classes Determine the responsibilities of each Determine the responsibilities of each

classclass Describe relationships between each classDescribe relationships between each class

Page 23: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Discovering ClassesDiscovering Classes

Recall that a class represents a Recall that a class represents a conceptconcept Some are concrete (i.e. real world)Some are concrete (i.e. real world)

A bank accountA bank account Rental itemsRental items Database of itemsDatabase of items PilePile

Others are abstractOthers are abstract ScannerScanner Streams, MathStreams, Math

Page 24: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Discovering ClassesDiscovering Classes

Simple Rule:Simple Rule:

Look for nouns in task description Look for nouns in task description (specs)(specs) Obviously not all nouns are classesObviously not all nouns are classes But can create a list of But can create a list of candidate classescandidate classes

Then determine which ones are usefulThen determine which ones are useful Cross them off your listCross them off your list

Page 25: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover
Page 26: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Example: InvoiceExample: Invoice

To describe an invoice, you can start To describe an invoice, you can start with a few ideas by looking at the with a few ideas by looking at the nounsnouns

Invoice, LineItem, CustomerInvoice, LineItem, Customer

Page 27: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Key pointsKey points

Class represents set of objects with Class represents set of objects with the the same behavior same behavior Entities with Entities with multiple occurrencesmultiple occurrences in in

problem description are good problem description are good candidates for objects candidates for objects

Find out what they have in common Find out what they have in common Design classes to capture Design classes to capture

commonalities commonalities

Why is Why is SongSong a good class? a good class? MenuMenu a bad a bad one?one?

Page 28: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Key PointsKey Points

Not all nouns need a new classNot all nouns need a new class Address needs to represented, do we Address needs to represented, do we

need a new class or can we use a need a new class or can we use a String?String?

Represent some entities as objects, Represent some entities as objects, others as primitive types others as primitive types

Could have argument for both – but Could have argument for both – but must balance generality with limiting must balance generality with limiting designdesign

Page 29: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Key PointsKey Points

Not all classes can be discovered in Not all classes can be discovered in analysis phase analysis phase Creating a database class may not be Creating a database class may not be

evident from specifications, but further evident from specifications, but further analysis and actual implementation analysis and actual implementation dictate that one is betterdictate that one is better

Some classes may already exist Some classes may already exist Can use inheritance to add capabilitiesCan use inheritance to add capabilities

Page 30: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

BehaviorBehavior

After set of classes have been sketched After set of classes have been sketched up, define behavior/purpose, of each classup, define behavior/purpose, of each class

Verbs = methodsVerbs = methods

Example: Compute amount due for Example: Compute amount due for invoice programinvoice program Which class? Which class? CustomerCustomer?? Invoice Invoice?? LineItem LineItem??

Page 31: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

CRC CardCRC Card

Describes a Describes a cclass, its lass, its rresponsibilities, esponsibilities, and its and its ccollaborators ollaborators

Use an index card for each class Use an index card for each class Pick the class that should be Pick the class that should be

responsible for each method (verb) responsible for each method (verb) Write the responsibility onto the class Write the responsibility onto the class

card card Indicate what other classes are needed Indicate what other classes are needed

to fulfill responsibility (collaborators) to fulfill responsibility (collaborators)

Page 32: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover
Page 33: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

CRC CRC Design Design

Informal methodInformal method Not complete (only high level activity)Not complete (only high level activity) Defines what classes define each Defines what classes define each

methodmethod Also helps find other methodsAlso helps find other methods

Why is Why is LineItemLineItem a collaborator? What info a collaborator? What info do I need from it? How do I get it?do I need from it? How do I get it?

getPrice()getPrice() method for method for LineItemLineItem

Page 34: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Relationships Between Relationships Between ClassesClasses

Good practice to document relationship Good practice to document relationship between classesbetween classes Can uncover common behaviorCan uncover common behavior Divide uncommon classes among Divide uncommon classes among

programming teamsprogramming teams We have learned about inheritance as a We have learned about inheritance as a

relationshiprelationship 3 total important relationships3 total important relationships Inheritance is often overused, recognize its Inheritance is often overused, recognize its

unique applicationunique application

Page 35: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

3 relationships3 relationships

Inheritance Inheritance Aggregation Aggregation Dependency Dependency

Page 36: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

InheritanceInheritance

Is-aIs-a relationship relationship Relationship between a more general Relationship between a more general

class (superclass) and a more class (superclass) and a more specialized class (subclass) specialized class (subclass)

Every Every savings account is a bank accountsavings account is a bank account DVD rental is a rentalDVD rental is a rental King is a chess pieceKing is a chess piece

Page 37: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

InheritanceInheritance

Every circle is an ellipse (with equal Every circle is an ellipse (with equal width and height) width and height)

It is sometimes abused It is sometimes abused Should the class Tire be a subclass Should the class Tire be a subclass

of a class Circle? of a class Circle? The The has-ahas-a relationship would be more relationship would be more

appropriate hereappropriate here

Page 38: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

AggregationAggregation

Has-aHas-a relationship relationship

Objects of one class contain Objects of one class contain references to objects of another class references to objects of another class

Use an instance variable Use an instance variable

Class A aggregates class B if A Class A aggregates class B if A contains an instance field of type Bcontains an instance field of type B

Page 39: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Aggregation vs. Aggregation vs. InheritanceInheritance

Two are often confusedTwo are often confused ExampleExample

Why not make Why not make BankAccountBankAccount an instance an instance field of field of CheckingAccountCheckingAccount??

How about extend a Circle for TireHow about extend a Circle for Tire

A Tire is not a circle – it is a car partA Tire is not a circle – it is a car part But it can be described by a circleBut it can be described by a circle

Page 40: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

AggregationAggregation

A tire has a circle as its boundary: A tire has a circle as its boundary: class Tireclass Tire

{{. . .. . .private String rating;private String rating;private Circle boundary;private Circle boundary;

} }

Page 41: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

ExampleExample

Car Car is ais a Vehicle – Inheritance Vehicle – Inheritance Car Car has ahas a set of Tires – Aggregation set of Tires – Aggregation

class Car extends Vehicleclass Car extends Vehicle

{{. . .. . .private Tire[] tires;private Tire[] tires;

}}

Page 42: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover
Page 43: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

DependencyDependency

Dependency occurs when a class uses Dependency occurs when a class uses another class methodsanother class methods

UsesUses relationship relationship Example: many of our applications Example: many of our applications

depend on the depend on the ScannerScanner class to read input class to read input Aggregation is a stronger form of Aggregation is a stronger form of

dependency dependency Obviously uses the class if it is an instance Obviously uses the class if it is an instance

fieldfield

Page 44: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

DependencyDependency Reverse not trueReverse not true

Just because there is a dependency, it Just because there is a dependency, it doesn’t mean aggregation is presentdoesn’t mean aggregation is present

Could be a local variableCould be a local variable Example: local Scanner is not aggregationExample: local Scanner is not aggregation

Aggregation is needed when an object Aggregation is needed when an object needs to be remembered in between needs to be remembered in between method callsmethod calls I.e. cannot be sent as a parameter every I.e. cannot be sent as a parameter every

timetime

Page 45: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Relationship Symbol Line Style Arrow Tip

Inheritance

                                         

Solid Triangle

Interface Implementation

                         

                 Dotted Triangle

Aggregation

                                          

Solid Diamond

Dependency

                                         

Dotted Open

Page 46: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Class DiagramClass Diagram

Page 47: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Attributes and Methods in Attributes and Methods in UML DiagramsUML Diagrams

Do not need to list all attributes and Do not need to list all attributes and methods in a UML diagrammethods in a UML diagram

List important onesList important ones Key to meeting a requirement in the Key to meeting a requirement in the

specspec Useful for implementation to noticeUseful for implementation to notice Don’t have to repeat aggregation Don’t have to repeat aggregation

relationshipsrelationships Trivial internal structureTrivial internal structure

Page 48: Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To learn about the software life cycle To learn how to discover

Aggregation and Aggregation and AssociationAssociation

Association: more general Association: more general relationship between classes relationship between classes

Use early in the design phase Use early in the design phase A class is associated with another if A class is associated with another if

you can navigate from objects of one you can navigate from objects of one class to objects of the other class to objects of the other

Given a Given a BankBank object, you can navigate object, you can navigate to to CustomerCustomer objects objects