chapters 4&5 design principles: correctness, robustness, flexibility, reusability, and...
TRANSCRIPT
ChapterChapterss 4 4&5 &5 Design Design PrinciplesPrinciples::CorrectnessCorrectness, , RobustnessRobustness, , Flexibility, Reusability, and Flexibility, Reusability, and EfficiencyEfficiency
Correctness and SufficiencyCorrectness and Sufficiency
Goal:Goal:– That each artifact satisfies That each artifact satisfies
designated requirements, and that designated requirements, and that together they satisfy all of the together they satisfy all of the application’s requirements.application’s requirements.
Approaches to correctnessApproaches to correctness– Informal approachesInformal approaches– Formal approachesFormal approaches
Sufficient DesignsSufficient Designs
A design sufficient to implement the
requirements.a correct design
Also called …
the design must be entirely understandable
It follows that …
the design very modular
A common way to achieve this is to make …
Formal approaches to Formal approaches to correctnesscorrectness
InvariantsInvariants– Unchanging relationships among variablesUnchanging relationships among variables
Class invariantsClass invariants– Keep objects in correct statesKeep objects in correct states– Make attributes Make attributes privateprivate so no one can so no one can
change the state of an object directly.change the state of an object directly.– Encapsulate Encapsulate private attributes with private attributes with
operations operations – Operations act as guards keep the object in Operations act as guards keep the object in
a correct statea correct state– Operations throw exceptions when a request Operations throw exceptions when a request
may put the object into a wrong statemay put the object into a wrong state
Invariants for Class Invariants for Class AutomobileAutomobile
mileage > 0 mileage < 1000000 vehicleID has at least 8 characters value >= -300 ($300 is the disposal
cost of a worthless automobile) originalPrice >= 0 ( type == “REGULAR” && value <= originalPrice )
|| ( type == “VINTAGE” && value >= originalPrice )
Introducing InterfacesIntroducing Interfaces
The interface of a module defines the uses The interface of a module defines the uses of the module.of the module.
Interface to classesInterface to classes– It is often beneficial to group them into several It is often beneficial to group them into several
interfaces when a class supports many methodsinterfaces when a class supports many methods– The interface segregation principleThe interface segregation principle
Interface to packagesInterface to packages– Group the functions of the package into Group the functions of the package into
interfacesinterfaces– Use a designated object to provide the Use a designated object to provide the
interfaces interfaces
Interface to classesInterface to classes
ShipmentsetVehicle()perishable()getWidth()
printRoute()getType()
getLength()getDuration()
setType()
Shipment
DimensionsgetWidth()getLength()getWeight()
TranspMeansgetDuration()setVehicle()printRoute()
GoodsTypegetType()setType()
perishable()
ShipmentDimensions
TranspMeans
GoodsType
Original form
Package Package iinterfacesnterfaces
Pricing
purchases
Furniture
Clothing
Appliance
Selection
ClothingTryout
«singleton»PurchasesIF
Participant-services
Conversation-services
Example of Example of ppackage ackage iinterfacesnterfaces
chatServer
chatClient
Display
ConversationManager
ClientComm
ServerComm
billing
Accounting BillFinancial
Message-reception
Conversation
Modularization: choosing Modularization: choosing classesclasses
Domain classesDomain classes– Particular to the applicationParticular to the application– Examples: Examples: BankCustomer, BankTransaction, TellerBankCustomer, BankTransaction, Teller – Typically not GUI classesTypically not GUI classes– Sufficient to classify all requirementsSufficient to classify all requirements
Non-Domain classes: Non-Domain classes: – Generic to all software systemsGeneric to all software systems– Examples: abstract classes, utility classesExamples: abstract classes, utility classes– Arise from design and implementation Arise from design and implementation
considerationsconsiderations Select domain classes first and then add non-Select domain classes first and then add non-
domain classesdomain classes
Modularization: choosing Modularization: choosing packagespackages
An essential part of choosing an An essential part of choosing an application’s architectureapplication’s architecture
Decompose the system into a set Decompose the system into a set of of threethree to to tenten packages packages
Modularization: choosing Modularization: choosing packagespackages
Mechanics
Application tracking trajectory of rocket carrying orbit-bound satellite into position
Position
Ground control
On board navig.
Alternative 1
Control
Trajectory
Weather
Alternative 2
RefactoringRefactoring
Refactoring: Change the design and Refactoring: Change the design and implementation with changing the implementation with changing the behaviorbehavior
Philosophy of Extreme programmingPhilosophy of Extreme programming– Design only for the requirements givenDesign only for the requirements given– Revise the design and implementation when Revise the design and implementation when
more requirements are addedmore requirements are added Refactoring examplesRefactoring examples
– Promote a primitive attributes to classPromote a primitive attributes to class– Introducing abstract base classes or interfaceIntroducing abstract base classes or interface
Refactoring: promote attributeRefactoring: promote attribute
class Automobile {class Automobile {int mileage;int mileage; // Promote it to a class// Promote it to a class……
}}
class Mileage {class Mileage {int nominalMileage = 0;int nominalMileage = 0;int chassisMileage = 0;int chassisMileage = 0;int engineMileage = 0;int engineMileage = 0;……public int computerEffectiveMileage() { … }public int computerEffectiveMileage() { … }
}}class Automobile {class Automobile {
Mileage mileage;Mileage mileage; // Promoted to a class// Promoted to a class……
}}
Refactoring: introducing Refactoring: introducing abstractsabstracts
PersonSSN
NamegetSSN()
getName()
FacultySSN
NamegetSSN()
getName()office
getOffice()
StaffSSN
NamegetSSN()
getName()dept
getDept()
StudentSSN
NamegetSSN()
getName()major
getMajor()
Improving RobustnessImproving Robustness
1.1. Protection from faulty InputProtection from faulty Inputo User inputUser inputo Input, not from userInput, not from user
• Data communicationData communication• Function calls made by other Function calls made by other
applicationsapplications
2.2. Protection from developer errorProtection from developer error – Faulty designFaulty design– Faulty implementationFaulty implementation
Initializing variables & Initializing variables & objectsobjects
Desirable practiceDesirable practice– IInitialize all variables before using themnitialize all variables before using them– IInitialized variables may offer more valuable info nitialized variables may offer more valuable info
on debuggingon debugging Initialize objectsInitialize objects
class Client {class Client {MyClass c = new MyClass(1, ‘a’); // take class MyClass c = new MyClass(1, ‘a’); // take class
defaultdefault}}BetterBetterclass MyClass {class MyClass { static MyClass getInstance() {static MyClass getInstance() {
return new MyClass(1, ‘a’);return new MyClass(1, ‘a’); }}}}CClass Client {lass Client {
MyClass c = MyClass.getInstance();MyClass c = MyClass.getInstance();……}}
Constraints on ParametersConstraints on Parameters 11
Example: Example: int computeArea(int aLength, int aBreadth) int computeArea(int aLength, int aBreadth)
{ … }{ … } Capture parameter constraints in classes if Capture parameter constraints in classes if
feasiblefeasibleint computeArea( RectangleDimension int computeArea( RectangleDimension
aaRRDimension )Dimension ) Specify all parameter constraints in Specify all parameter constraints in
method commentsmethod comments aLength > 0 andaLength > 0 andaBreadth > 0 andaBreadth > 0 andaLength >= aBreadthaLength >= aBreadth
Constraints on ParametersConstraints on Parameters 22
Callers obey explicit requirements on Callers obey explicit requirements on parameters parameters o Problem is method programmers have no control Problem is method programmers have no control
over callersover callers Check constraints first within the method Check constraints first within the method
codecodeif( aLength <= 0 ) ……if( aLength <= 0 ) ……– Throw exception if this is a predictable Throw exception if this is a predictable
occurrenceoccurrence– Otherwise abort if possible Otherwise abort if possible – Otherwise return default if it makes sense in Otherwise return default if it makes sense in
contextcontext And generate warning or log to a fileAnd generate warning or log to a file
Wrapping ParametersWrapping Parameters in a in a classclass
Replace
int computeArea( int aLength, int aBreadth) {..}
With
int computeArea(Rectangle aRectangle) {..}
where class Rectangle { … Rectangle( int aLength, int aBreadth ) {
if( aLength > 0 ) this.length = aLength; else …..
} … }
Rectangle class checks the parameters.
FlexibilityFlexibility
Aspects of flexibilityAspects of flexibilityadding more of the same kind of adding more of the same kind of
functionalityfunctionality Example (banking application): handle Example (banking application): handle
more kinds of accounts without having more kinds of accounts without having to change the existing design or codeto change the existing design or code
adding different functionalityadding different functionality Example: add withdraw function to Example: add withdraw function to
existing deposit functionalityexisting deposit functionalitychanging functionality changing functionality
Example: allow overdraftsExample: allow overdrafts
Flexibility: more of the same Flexibility: more of the same kindkind
WebSiteregister()
Member0..nmembers
class Website {Member[] members;void register(Member aMember) { … }….
}
Make the design flexible enough to accept new kinds of members! Next page
Flexibility: more of the same Flexibility: more of the same kindkind
WebSite Member0..n
StandardMemberXMemberYMember
members
The open-close principle!
Flexibility: more of different Flexibility: more of different func.func.
A list of related functions– Example: add print to an air travel
itinerary functions – Solution: add the new function to the
existing set An existing base class
– Example: add “print road- and ship- to air itinerary ” next page
Neither– Example: add “print itineraries for
combinations of air, road and ship transportation”
– Solution: design patternsSolution: design patterns
Flexibility: more of different Flexibility: more of different func.func.
TripprintItinerary()
StandardTripprintItinerary()
SomeApplicationClass
Method(s) callprintItinerary()
TripprintItinerary()
SeaTripprintItinerary()
SomeApplicationClass
LandTripprintItinerary()
StandardTripprintItinerary()
Print out the part common to all subclasses
ReusabilityReusability
Design reuse– Design patterns– Frameworks
Implementation reuse– Foundation classes (e.g., Java API)– Library functions
Reusability – function reuseReusability – function reuse
Specify completed or well document– Pre- and post-conditions, assumptions, etcPre- and post-conditions, assumptions, etc
Avoid unnecessary coupling with the Avoid unnecessary coupling with the enclosing classenclosing class– Make static if feasibleMake static if feasible– Include parameterizationInclude parameterization
Use meaningful namesUse meaningful names– Understandability promotes reusabilityUnderstandability promotes reusability
Explain the algorithmExplain the algorithm– Reusers need to know how the algorithm Reusers need to know how the algorithm
works.works. If the algorithm comply with the government or If the algorithm comply with the government or
company’s regulation.company’s regulation.
Reusability – class reuseReusability – class reuse
Describe the class completely. Make the class name and functionality Make the class name and functionality
match a real world conceptmatch a real world concept Define a useful abstractionDefine a useful abstraction Reduce dependencies on other classesReduce dependencies on other classes
– When class A depends on B, no use of A When class A depends on B, no use of A can be made without B. Thus it limits can be made without B. Thus it limits reuse of A.reuse of A.
– Sometimes, certain dependencies may be Sometimes, certain dependencies may be acceptable in some applicationsacceptable in some applications
A A HouseHouse may depend on an may depend on an EntryDoorEntryDoor since since every house has an entry doorevery house has an entry door
A A PianoPiano may depend on may depend on PianoManufacturePianoManufacture
Reusability – class Reusability – class dependenciesdependencies
Customer Piano
Customer PianoPianoOrder
Class Piano is dependent on class Customer. This limits the reusability of Piano. Why a piano warehouse application needs to know Customer?
A possible solution is to separate the relationship between Customerand piano into a new class, PianoOrder. Now Customer and Piano Are independent of each other – both can be easily reused.
The mediator design pattern!
Reusability – class Reusability – class combinationscombinations
CustomercomputeBill()
RegularCustomercomputeBill()
Leveraging inheritance: The base class Customer provides computeBill() for all subclasses.Subclass RegularCustomer may use super.computeBill().
CustomercomputeBill()
class RegularCustomer extends Customer { public int computeBill() { int baseAmnt = super.computerBill(); // add specials to baseAmnt; return value; }}
abstract class Customer {public int computerBill() { // do required computation for // customers of all types return value; }}
Reusability – class Reusability – class combinationscombinations
CustomercomputeBill()
Billcompute()
Leveraging aggregation: Computation for bills is delegated to an aggregate class Bill
CustomercomputeBill()
class Bill { … public int compute() { // do computation return value; }
class Customer { private Bill bill; public int computerBill() { int value = this.bill.compute(); return value; }}
Reusability – class Reusability – class combinationscombinations
CustomercomputeBill( Orders )
Ordersvalue()
Leveraging dependency: Customer has a method computerBills() which takes a parameter of Orders.
CustomercomputeBill()
class Orders { … public int computeValue() { // do computation return value; }
class Customer { public int computerBills(Orders someOrders) { int value = someOrders.computeValue(); return total; }}
Efficiency - timeEfficiency - time
Design for Other Criteria, Then Consider EfficiencyDesign for Other Criteria, Then Consider Efficiency
– Design for flexibility, reusability , …Design for flexibility, reusability , …
– At some point, identify inefficient placesAt some point, identify inefficient places
– Make targeted changes to improve efficiencyMake targeted changes to improve efficiency
Design for Efficiency From the StartDesign for Efficiency From the Start
– Identify key efficiency requirements up frontIdentify key efficiency requirements up front
– Design for these requirements during all phases Design for these requirements during all phases
Combine These Two ApproachesCombine These Two Approaches
– Make trade-offs for efficiency requirements during designMake trade-offs for efficiency requirements during design
– Address remaining efficiency issues after initial designAddress remaining efficiency issues after initial design
Efficiency - Efficiency - Space-Time Trade-Space-Time Trade-offsoffs
Time to process one item
Typical target
Space
Summary of Chapter 4Summary of Chapter 4
Correctness of a Design or CodeCorrectness of a Design or Code– Supports the requirementsSupports the requirements– In general, many correct designs existIn general, many correct designs exist
Robustness of a Design or CodeRobustness of a Design or Code– Absorbs errorsAbsorbs errors
– -- of the user-- of the user– -- of developers-- of developers
Summary of Chapter 5Summary of Chapter 5
Flexibility Flexibility – readily changeable readily changeable
Reusability Reusability – in other applicationsin other applications
EfficiencyEfficiency – in timein time– in spacein space