chapters 4&5 design principles: correctness, robustness, flexibility, reusability, and...

36
Chapter Chapter s s 4 4 &5 &5 Design Design Principles Principles : : Correctness Correctness , , Robustness Robustness , , Flexibility, Reusability, Flexibility, Reusability, and Efficiency and Efficiency

Upload: diane-oneal

Post on 29-Jan-2016

408 views

Category:

Documents


17 download

TRANSCRIPT

Page 1: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

ChapterChapterss 4 4&5 &5 Design Design PrinciplesPrinciples::CorrectnessCorrectness, , RobustnessRobustness, , Flexibility, Reusability, and Flexibility, Reusability, and EfficiencyEfficiency

Page 2: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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

Page 3: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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 …

Page 4: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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

Page 5: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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 )

Page 6: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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

Page 7: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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

Page 8: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

Package Package iinterfacesnterfaces

Pricing

purchases

Furniture

Clothing

Appliance

Selection

ClothingTryout

«singleton»PurchasesIF

Page 9: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

Participant-services

Conversation-services

Example of Example of ppackage ackage iinterfacesnterfaces

chatServer

chatClient

Display

ConversationManager

ClientComm

ServerComm

billing

Accounting BillFinancial

Message-reception

Conversation

Page 10: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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

Page 11: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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

Page 12: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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

Page 13: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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

Page 14: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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……

}}

Page 15: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

Refactoring: introducing Refactoring: introducing abstractsabstracts

PersonSSN

NamegetSSN()

getName()

FacultySSN

NamegetSSN()

getName()office

getOffice()

StaffSSN

NamegetSSN()

getName()dept

getDept()

StudentSSN

NamegetSSN()

getName()major

getMajor()

Page 16: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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

Page 17: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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();……}}

Page 18: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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

Page 19: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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

Page 20: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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.

Page 21: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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

Page 22: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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

Page 23: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

Flexibility: more of the same Flexibility: more of the same kindkind

WebSite Member0..n

StandardMemberXMemberYMember

members

The open-close principle!

Page 24: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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

Page 25: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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

Page 26: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

ReusabilityReusability

Design reuse– Design patterns– Frameworks

Implementation reuse– Foundation classes (e.g., Java API)– Library functions

Page 27: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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.

Page 28: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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

Page 29: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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!

Page 30: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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; }}

Page 31: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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; }}

Page 32: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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; }}

Page 33: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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

Page 34: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

Efficiency - Efficiency - Space-Time Trade-Space-Time Trade-offsoffs

Time to process one item

Typical target

Space

Page 35: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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

Page 36: Chapters 4&5 Design Principles: Correctness, Robustness, Flexibility, Reusability, and Efficiency

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