Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To...
-
Upload
shon-parrish -
Category
Documents
-
view
221 -
download
0
Transcript of Chapter 17 – Object- Oriented Design. Chapter Goals To learn about the software life cycle To...
Chapter 17 – Chapter 17 – Object-Oriented Object-Oriented
DesignDesign
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
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
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
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)
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
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
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
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
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
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?
Waterfall ModelWaterfall Model
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
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
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
Deployment
Testing
Implementation
Design
Analysis
SpiralSpiral
Prototype 2
Final Product
Prototype 1
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
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
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
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
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…
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
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
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
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
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?
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
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
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??
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)
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
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
3 relationships3 relationships
Inheritance Inheritance Aggregation Aggregation Dependency Dependency
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
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
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
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
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;
} }
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;
}}
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
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
Relationship Symbol Line Style Arrow Tip
Inheritance
Solid Triangle
Interface Implementation
Dotted Triangle
Aggregation
Solid Diamond
Dependency
Dotted Open
Class DiagramClass Diagram
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
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