Introduction to Software Technology 3. Software...

Post on 19-Aug-2020

0 views 0 download

transcript

IntroductiontoSoftwareTechnology3.SoftwareDesign

KlausOstermann

EinführungindieSoftwaretechnik1

GoalofSoftwareDesign

EinführungindieSoftwaretechnik2

}  Foreachdesiredprogrambehaviorthereareinfinitelymanyprogramsthathavethisbehavior}  Whatarethedifferencesbetweenthevariants?}  Whichvariantshouldwechoose?

}  Sinceweusuallyhavetosynthesizeratherthanchoosethesolution…}  Howcanwedesignavariantthathasthedesiredproperties?

Example

EinführungindieSoftwaretechnik3

}  Sortingwithconfigurableorder,variantA

void sort(int[] list, String order) { … boolean mustswap; if (order.equals(“up”)) { mustswap = list[i] < list[j]; } else if (order.equals(“down”)) { mustswap = list[i] > list[j]; } … }

Example

EinführungindieSoftwaretechnik4

}  Sortingwithconfigurableorder,variantBvoid sort(int[] list, Comparator cmp) { … boolean mustswap; mustswap = cmp.compare(list[i], list[j]); … } interface Comparator { boolean compare(int i, int j); } class UpComparator implements Comparator { boolean compare(int I, int j) { return i<j; }} class DownComparator implements Comparator { boolean compare(int I, int j) { return i>j; }}

(bytheway,thisdesigniscalled“strategypattern”)

QualityofaSoftwareDesign

EinführungindieSoftwaretechnik5

}  Howcanwemeasuretheinternalqualityofasoftwaredesign?}  Extensibility,Maintainability,Understandability,Readability,…}  Robustnesstochange}  LowCoupling&HighCohesion}  Reusability}  Allthesequalitiesaretypicallysummarizedbythetermmodularity

}  …asopposedtoexternalquality}  Correctness:Validimplementationofrequirements}  EaseofUse}  Resourceconsumption}  Legalissues,politicalissues,…

Modularity

EinführungindieSoftwaretechnik6

Modularity

EinführungindieSoftwaretechnik7

}  Asoftwareconstructionmethodismodularifithelpsdesignerstoproducesoftwaresystemsmadeofautonomouselementsconnectedbyacoherent,simplestructure

}  Inthefollowingwe’llelaborateonthat:}  Fivecriteria}  FiveRules}  FivePrinciples

FiveCriteria:ModularDecomposability

EinführungindieSoftwaretechnik8

AsoftwareconstructionmethodsatisfiesModularDecomposabilityifithelpsinthetaskofdecomposingasoftwareproblemintoasmallnumberoflesscomplexsubproblems,connectedbyasimplestructure,and

independentenoughtoallowfurtherworktoproceedseparatelyoneachofthem.

FiveCriteria:ModularDecomposability

EinführungindieSoftwaretechnik9

}  ModularDecomposabilityimplies:DivisionofLaborpossible!

}  Example:Top-DownDesign}  Counter-Example:Productionofaglobalinitializationmodule

FiveCriteria:ModularComposability

EinführungindieSoftwaretechnik10

AmethodsatisfiesModularComposabilityifitfavorstheproductsofsoftwareelementswhichmaythenbefreelycombinedwitheachothertoproducenewsystems,

possiblyinanenvironmentquitedifferentfromtheoneinwhichtheywereinitiallydeveloped.

FiveCriteria:ModularComposability

EinführungindieSoftwaretechnik11

}  Isdualtomodulardecomposability}  Isdirectlyconnectedwithreusability

}  Old“dream”ofprogramming:programmingasconstructionboxactivity

}  Example1:Librarieshavebeenreusedsuccessfullyincountlessdomains

}  Example2:UnixShellCommands}  Counter-Example:Preprocessors

FiveCriteria:ModularUnderstandability

EinführungindieSoftwaretechnik12

AmethodfavorsModularUnderstandabilityifithelpsproducesoftwareinwhichahumanreadercanunderstandeachmodulewithouthavingtoknowtheothers,or,atworst,byhavingtoexamineonlyafewoftheothers.

FiveCriteria:ModularUnderstandability

EinführungindieSoftwaretechnik13

}  Importantformaintenance}  Appliestoallsoftwareartifacts,notjustcode}  Counter-example:Sequentialdependenciesbetweenmodules

FiveCriteria:ModularContinuity

EinführungindieSoftwaretechnik14

AmethodsatisfiesModularContinuityif,inthesoftwarearchitecturesthatityields,asmallchangeintheproblemspecificationwilltriggerachangeofjustonemodule,ora

smallnumberofmodules.

FiveCriteria:ModularContinuity

EinführungindieSoftwaretechnik15

}  Example1:Symbolicconstants(asopposedtomagicnumbers)

}  Example2:Hidingdatarepresentationbehindaninterface

}  Counter-Example:Programdesignsdependingonfragiledetailsofhardwareorcompiler

FiveCriteria:ModularProtection

EinführungindieSoftwaretechnik16

AmethodsatisfiedModularProtectionifityieldsarchitecturesinwhichtheeffectofanabnormal

conditionoccurringatruntimeinamodulewillremainconfinedtothatmodule,oratworstwillonlypropagate

toafewneighboringmodules.

FiveCriteria:ModularProtection

EinführungindieSoftwaretechnik17

}  Motivation:Bigsoftwarewillalwayscontainbugsetc.,failuresunavoidable

}  Example:DefensiveProgramming}  Counter-Example:Anerroneousnullpointerinonemoduleleadstoanerrorinadifferentmodule

FiveRules

EinführungindieSoftwaretechnik18

}  FiveRuleswillfollowwhichwemustobservetoensurehigh-qualitydesign

FiveRules:DirectMapping

EinführungindieSoftwaretechnik19

Themodularstructuredevisedintheprocessofbuildingasoftwaresystemshouldremaincompatiblewithanymodularstructuredevisedintheprocessof

modelingtheproblemdomain.

FiveRules:DirectMapping

EinführungindieSoftwaretechnik20

}  Followsfromcontinuityanddecomposability}  A.k.a.“lowrepresentationalgap”[C.Larman]

FiveRules:FewInterfaces

EinführungindieSoftwaretechnik21

Iftwomodulescommunicate,theyshouldexchangeaslittleinformationaspossible

FiveRules:FewInterfaces

EinführungindieSoftwaretechnik22

}  Wanttopologywithfewconnections}  Followsfromcontinuityandprotection;otherwisechanges/errorswouldpropagatemore

FiveRules:SmallInterfaces

EinführungindieSoftwaretechnik23

Iftwomodulescommunicate,theyshouldexchangeaslittleinformationaspossible

FiveRules:SmallInterfaces

EinführungindieSoftwaretechnik24

}  Followsfromcontinuityandprotection,requiredforcomposability

}  Counter-Example:BigInterfacesJ

FiveRules:ExplicitInterfaces

EinführungindieSoftwaretechnik25

WhenevertwomodulesAandBcommunicate,thismustbeobviousfromtheinterfaceofAorBorboth.

FiveRules:ExplicitInterfaces

EinführungindieSoftwaretechnik26

}  Counter-Example1:GlobalVariables}  Counter-Example2:Aliasing–mutationofsharedheapstructures

Intermezzo:LawofDemeter(LoD)

EinführungindieSoftwaretechnik27

}  LoD:Eachmoduleshouldhaveonlylimitedknowledgeaboutotherunits:onlyunits"closely"relatedtothecurrentunit

}  Inparticular:Don’ttalktostrangers!}  Forinstance,noa.getB().getC().foo()}  Motivatedbycontinuity

FiveRules:InformationHiding

EinführungindieSoftwaretechnik28

Thedesignerofeverymodulemustselectasubsetofthemodule’spropertiesastheofficialinformationaboutthemodule,tobemadeavailabletoauthorsofclientmodules.

FiveRules:InformationHiding

EinführungindieSoftwaretechnik29

FiveRules:InformationHiding

EinführungindieSoftwaretechnik30

}  Reynolds’parableaboutcomplexnumbers…}  Impliedbycontinuity}  Theiceberganalogyisslightlymisleading,sinceaninterfacealsoabstractsovertheimplementation

FivePrinciples

EinführungindieSoftwaretechnik31

}  Fromtheprecedingrules,andindirectlyfromthecriteria,fiveprinciplesofsoftwareconstructionfollow:}  TheLinguisticModularUnitsprinciple.}  TheSelf-Documentationprinciple.}  TheUniformAccessprinciple.}  TheOpen-Closedprinciple.}  TheSingleChoiceprinciple.

FivePrinciples:LinguisticModularUnits

EinführungindieSoftwaretechnik32

Modulesmustcorrespondtosyntacticunitsinthelanguageused.

FivePrinciples:LinguisticModularUnits

EinführungindieSoftwaretechnik33

}  Excludesmethodsthatsuggestacertainmoduleconceptandalanguagethatdoesnotofferthecorrespondingmodularconstruct

}  Impliedbycontinuityanddirectmapping}  Bothrequiredirectcorrespondencebetweenspecification,design,andimplementationmodules

}  Impliedbydecomposabilityandcomposability}  Theimplementationofeverytaskmustresultinawell-delimitedsyntacticunit

FivePrinciples:Self-DocumentationPrinciple

EinführungindieSoftwaretechnik34

Thedesignerofamoduleshouldstrivetomakeallinformationaboutthe

modulepartofthemoduleitself.

FivePrinciples:Self-DocumentationPrinciple

EinführungindieSoftwaretechnik35

}  Precludeskeepinginformationaboutthemoduleinaseparatedocument

}  Justification:}  Modularunderstandabilityprinciple}  Continuity,hardtokeepseparatedocuments“insync”}  Ingeneral:Changeability

}  Traditional“heavy-weight”SEprocesseshaveadifferentpointofviewonthis

}  Seealsomaterialofpreviouslectureaboutliterateprogrammingandgooddocumentationingeneral

FivePrinciples:UniformAccess

EinführungindieSoftwaretechnik36

Allservicesofferedbyamoduleshouldbeavailablethroughauniform

notation,whichdoesnotbetraywhethertheyareimplementedthrough

storageorthroughcomputation

FivePrinciples:UniformAccess

EinführungindieSoftwaretechnik37

}  Justification:Continuitycriterion,specialcaseofinformationhiding

}  Example:Thebalanceofanaccountmaybestoredasdata,oritmaybecomputedfromthelistoftransactions}  Thisisatime/spacetradeoff}  Differenceshouldnotbevisibleforaclient

}  Somelanguagessupportthisprincipledirectly}  Ruby,Eiffel,Python(*),Smalltalk(*)}  Adesignconventioninotherlanguages

}  “getter/setter”methodsinJava

FivePrinciples:Open-ClosedPrinciple

EinführungindieSoftwaretechnik38

Modulesshouldbebothopenandclosed.

FivePrinciples:Open-ClosedPrinciple

EinführungindieSoftwaretechnik39

}  Amoduleissaidtobeopenifitisstillavailableforextension.}  Forexample,itshouldbepossibletoexpanditssetofoperationsoraddfieldstoitsdatastructures.

}  Amoduleissaidtobeclosedifitisavailableforusebyothermodules.}  Well-definedstableinterface}  Canbecompiled,stored,…

}  Motivation:Opennessforfutureextensions,closednessforcomposition

FivePrinciples:Open-ClosedPrinciple

EinführungindieSoftwaretechnik40

}  Example:ClassesinOOlanguagesareopenthroughinheritanceyetcanbeusedthroughconstructorcalls

}  Counter-Example:PackagesinJava}  Whathappensifmodulesarenotopen:

}  “Monkeypatching”inJavascript

(youdon’tneedtounderstandthisexampleindetail)

eval("getBrowser().removeTab ="+ getBrowser().removeTab.toString().replace( 'this.addTab("about:blank");', 'if (SpeedDial.loadInLastTab) {this.addTab(' +'"chrome://speeddial/content/speeddial.xul"' +')} else { this.addTab("about:blank")}' ));

FivePrinciples:SingleChoice

EinführungindieSoftwaretechnik41

Wheneverasoftwaresystemmustsupportasetofalternatives,oneandonlyonemoduleinthesystemshouldknowtheirexhaustivelist.

FivePrinciples:SingleChoice

EinführungindieSoftwaretechnik42

}  SpecialcaseoftheDRYprinciple(Don’trepeatyourself):}  Everypieceofknowledgemusthaveasingle,unambiguous,authoritativerepresentationwithinasystem

}  Typicalexamplesofviolationsofthisprinciple:}  MultipleIf/then/elseorcasestatementswithidenticalconditions

}  PatternMatchinginfunctionalprogramming

}  Isaconsequenceofopen-closedprinciple}  Isaformofinformationhiding

FivePrinciples:SingleChoice

EinführungindieSoftwaretechnik43

}  AvoidedinOOlanguagesbyusingsubtypingandlatebinding}  Cf.sortingexampleinthebeginningofthispresentation}  However,OOviolatestheprincipleitselfinthatthelistofmethodsinaninterfaceisclosedandreplicatedinallimplementations

}  Simpleprinciplebutquitehardtorealize}  Cf.solutionstotheso-called‘expressionproblem’

Discussion

EinführungindieSoftwaretechnik44

}  Examinethemodularstructuresofanyprogramminglanguagewhichyouknow

}  Assesshowtheysupportthecriteriaandprinciplespresentedinthislecture

Reusability

EinführungindieSoftwaretechnik45

Reusability

EinführungindieSoftwaretechnik46

}  Olddreamof“mass-producedsoftwarecomponents”byMcIlroyatNATOconference}  Idea:Mimicengineering}  However,cf.pitfallsofconfusingproductandplan,seefirstlecture

}  Other(equallyproblematic)commonanalogy:SoftwareasLEGO

}  Althoughthesevisionsarebothproblematic,reuseisamajorconcerninsoftwaredesign

GoalsofReuse

EinführungindieSoftwaretechnik47

}  Timeliness:Havinglesssoftwaretodevelopmeansthatwecanbuilditfaster

}  Decreasedmaintenanceeffort:Ifsomeoneelseisresponsibleforthesoftwareheorsheisalsoresponsibleforitsevolution}  Andhedoessoonceforallclients:Fixonce,profitmanytimes

}  Redundancyisasourceofinconsistency.Reusecanavoidredundancy.

}  Reliability}  Ifsoftwareisreusedmanytimesmoreeffortisputintosoftware

quality}  Efficiency

}  Bythesameargumentsasreliability}  Consistency}  Investment

Whatshouldwereuse?

EinführungindieSoftwaretechnik48

}  Reuseofpersonnel}  E.g.avoidlossofknow-howbytransferringsoftwareengineersfromprojecttoproject

}  Reuseofdesignsandspecifications}  Notionofdesign/specificationassoftwareproductindependentofimplementationisdubious,cf.self-documentationprinciple

}  Theimplementationisthe(detailed)design}  Withcontinuity,directmappingetc.,thedistinctionbetweenreusingmodulesandreusingdesignstendstofadeaway}  High-LevelDesign(e.g.classdiagram)islikeatableofcontentsofthedetaileddesign(implementation)

Whatshouldwereuse?

EinführungindieSoftwaretechnik49

}  DesignPatterns}  =architecturalideasapplicableacrossabroadrangeofapplicationdomains

}  Animportantformofarchitecturereusewhichwewillstudyindetaillateron

}  SourceCode}  Wewanttoreusesomethingthat“runs”,sinceeventuallywewanttorunprograms(“Bubblesdon’tcrash!”)

Reuseofabstractedmodules

EinführungindieSoftwaretechnik50

}  Ifwewanttoreusesourcecode,inwhatformshouldwereuseit?

}  Reusingitintheformoftheactualsourcetextisproblematic}  Itremovesinformationhiding:Usersmayrelyonimplementationdetailsonlyvisiblebystudyingthesourcetext

}  Developersofsoftwaredistributedinsourcetextmaybetemptedtoviolatemodularityrules

}  Whatwewanttoreuseareabstractedmodules}  Softwaredescribedthroughawell-definedinterfacethathidesimplementationdetails

}  Thesoftwaremaystillbedistributedinsourcetext;thedifferenceistheprimarysourceofinformationaboutit

ReuseandPatterns

EinführungindieSoftwaretechnik51

}  Areusablepieceofcodeabstractsovercertainpatterns(patternsinthegeneralsense,notdesignpatterns)

}  Conversely,aprogramcontainsopportunitiesforreuseifitcontainspatterns}  Canbeformalizedas:TheKolmogorovcomplexityoftheprogramissmallerthantheprogram

}  Let’slookatsometypicalpatternsofredundancy(patternsofpatternsJ)andwaystoabstractoverthem

Reuse:Constants

EinführungindieSoftwaretechnik52

}  Sometimesthesamenumber/string/…showsupmanytimesinaprogram(“magicnumber”)}  Asourceofinconsistency,ifthenumber/stringmaychange

}  E.g.,thevalueofPiisunlikelytochangeJ

}  Nodocumentationoftheintentionofthenumber/string/…}  Reusebydefiningaconstant

}  Canreusetheconstantinallplaceswhereitisneeded}  Canchangeinoneplace}  Cangivemeaningfulnametoconstant

Reuse:CommonSubexpressions

EinführungindieSoftwaretechnik53

}  Codemaycontainthesamesubexpressionsinmanyplaces,e.g.,5*89+3orx+y/2 }  Mustkeeptrackofscopingrulesifvariablesareinvolved

}  Canabstractoverpatternbyusingalocalvariable}  Ifthesubexpressionperformsside-effects(I/O,mutation,…)canabstractoverpatternusingprocedure/method

}  Thismayormaynotyieldmoreefficientcode}  Dependingonhowsmartthecompileris

}  Moreimportantly,itwilltypicallyimprovethecode}  Givestheideabehindthecommonsubexpressionaname}  Lessredundancy,…

Reuse:Almostcommonsubexpressions

EinführungindieSoftwaretechnik54

}  Codecontainssimilar,butnotidenticalsubexpressions}  Differonlyinthevalueof“first-class”expressions

}  Canabstractoverpatternusingproceduralabstraction(or,methods,functions,lambdas,…)

}  E.g.average(x,y)=x+y/2insteadofcomputingaveragesinplace

}  Givesabstractionaname,avoidsredundancy,…

Reuse:Almostcommonsubexpressions

EinführungindieSoftwaretechnik55

}  Whatiftheexpressionsdifferinthesubroutinestheycall?}  Nothingchangesinalanguagewithfirst-classsubroutines;canabstractoverthesecallsandturnthemintoparameters}  E.g.functionallanguages

}  InOOlanguages,thisproblemhasgivenrisetodesignpatternssuchas“strategy”and“templatemethod”whichwewilldiscussindetaillateron

Reuse:Almostcommonsubexpressions

EinführungindieSoftwaretechnik56

}  Whatiftheexpressionsdifferinthetypestheyuse?}  E.g.quicksortalgorithmonintegersvs.quicksortonstrings

}  Canusegenerictypes!}  List<T>sort<T>(List<T>in,Comparator<T>cmp){…}

Reuse:Similarclassdefinitions

EinführungindieSoftwaretechnik57

}  Canfactoroutcommonalitiesincommonsuperclass}  Latebindingandpossibilitytoextendfields/methodsallowonetospecializeinpowerfulways}  However,subtypinglimitsthewayshowasubclasscanbedifferentfromasuperclass}  “LiskovSubstitutionPrinciple”àSEDesignLecture

}  However,differentpointsofviewonwhentouseinheritance}  “Scandinavian”styleofinheritance:Mechanismforconceptualspecialization,drivenbymodeling

}  “American”styleofinheritance:Reuseandpatchcode

Somepatternsarehardtoabstractover,though

EinführungindieSoftwaretechnik58

ReuseandEfficiency

EinführungindieSoftwaretechnik59

}  Abstractdesignscanbelessefficient(intermsofspace/timebehavior)thantheirredundantexpansions}  “Alldesignisjustaddingmorelevelsofindirection”}  Aconflictbetweenreuseandefficiency?

}  Mostofthetimenotarealconcern}  Compilertechniquesremovemuchabstractionoverhead

}  Inlining,devirtualization,tail-calloptimization,partialevaluation,staging,…

}  Costofmethod/functioncallingrarelythemainbottleneck}  Onlyafractionofthecodeisperformance-criticalanyway

}  Canbeaconcernifveryinefficientabstractiontechniquesareused}  E.g.,reflection

Literature

EinführungindieSoftwaretechnik60

}  BertrandMeyer,Object-OrientedSoftwareConstruction,PrenticeHall,1997[Chapter3,4]