Académique Documents
Professionnel Documents
Culture Documents
Doesthishelp?
static int[] a = new int[] {1000, 900, 500, 400, 100,90, 50, 40, 10, 9, 5, 4, 1 };
static String[] b = new String[] {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
Whatelsewouldhavehelped?
UWO
TheComputerScienceDepartment
80minutes
Design Decision
Question:Whataresomeofthethingsyouthink,asa
programmer,areimportantinordertosayapieceof
softwareisWellDesigned?
Question:Weallhavetomakedesigndecisionswhen
creatingsoftware.Letssaythatwedecidetonotusea
database.
Whymightwemakethatdecision?(Onereasonis
thatyourcs2212instructorwontletyou,whatare
otherpossiblereasons?)
Whatdowehavetothinkaboutwhenmakingthat
decision?
UWO
TheComputerScienceDepartment
Andwhileadheringtogeneralprinciplesofgood
quality
UWO
TheComputerScienceDepartment
Facebook Help
https://github.com/jsuwo/facebookappletserver
Lookatfbproxy.php(124160)and
FacebookClient.java(line155and354401)
UWO
TheComputerScienceDepartment
UWO
TheComputerScienceDepartment
Making decisions
Tomakeeachdesigndecision,thesoftwareengineer
uses:
Knowledgeof
therequirements
thedesignascreatedsofar
thetechnologyavailable
softwaredesignprinciplesandbestpractices
whathasworkedwellinthepast
UWO
TheComputerScienceDepartment
Design space
Thespaceofpossibledesignsthatcouldbeachievedbychoosing
differentsetsofalternativesisoftencalledthedesignspace
Forexample:
UWO
TheComputerScienceDepartment
Component
Anypieceofsoftwareorhardwarethathasaclearrole.
Acomponentcanbeisolated,allowingyoutoreplaceitwith
adifferentcomponentthathasequivalentfunctionality.
Manycomponentsaredesignedtobereusable.
Conversely,othersperformspecialpurposefunctions.
UWO
TheComputerScienceDepartment
Module
Acomponentthatisdefinedattheprogramming
languagelevel
Forexample,methods,classesandpackagesare
modulesinJava.
UWO
TheComputerScienceDepartment
10
System
Alogicalentity,havingasetofdefinableresponsibilitiesor
objectives,andconsistingofhardware,softwareorboth.
Asystemcanhaveaspecificationwhichisthenimplementedbya
collectionofcomponents.
Asystemcontinuestoexist,evenifitscomponentsarechangedor
replaced.
Thegoalofrequirementsanalysisistodeterminethe
responsibilitiesofasystem.
Subsystem:
Asystemthatispartofalargersystem,andwhichhasa
definiteinterface
UWO
TheComputerScienceDepartment
11
UWO
TheComputerScienceDepartment
12
UWO
TheComputerScienceDepartment
13
TheComputerScienceDepartment
14
UWO
TheComputerScienceDepartment
15
UWO
TheComputerScienceDepartment
16
UWO
TheComputerScienceDepartment
17
TheComputerScienceDepartment
18
UWO
TheComputerScienceDepartment
19
Functional cohesion
Thisisachievedwhenallthecodethatcomputesa
particularresultiskepttogetherandeverythingelseis
keptout
i.e. when a module only performs a single computation,
andreturnsaresult,withouthavingsideeffects.
Benefitstothesystem:
Easiertounderstand
Morereusable
Easiertoreplace
Modulesthatupdateadatabase,createanewfileor
interactwiththeuserarenotfunctionallycohesive
UWO
TheComputerScienceDepartment
20
UWO
TheComputerScienceDepartment
21
Layer cohesion
Allthefacilitiesforprovidingoraccessingasetofrelated
servicesarekepttogether,andeverythingelseiskeptout
Thelayersshouldformahierarchy
Higherlayerscanaccessservicesoflowerlayers,
Lowerlayersdonotaccesshigherlayers
Thesetofproceduresthroughwhichalayerprovidesits
servicesistheapplicationprogramminginterface(API)
Youcanreplacealayerwithouthavinganyimpactonthe
otherlayers
YoujustreplicatetheAPI
UWO
TheComputerScienceDepartment
22
UWO
TheComputerScienceDepartment
23
Communicational cohesion
Allthemodulesthataccessormanipulatecertaindata
arekepttogether(e.g.inthesameclass)and
everythingelseiskeptout
Aclasswouldhavegoodcommunicationalcohesion
if all the systems facilities for storing and
manipulatingitsdataarecontainedinthisclass.
iftheclassdoesnotdoanythingotherthanmanage
itsdata.
Mainadvantage:Whenyouneedtomakechangesto
thedata,youfindallthecodeinoneplace
UWO
TheComputerScienceDepartment
24
Sequential cohesion
Procedures,inwhichoneprocedureprovidesinputto
thenext,arekepttogetherandeverythingelseiskept
out
Youshouldachievesequentialcohesion,onlyonceyou
havealreadyachievedtheprecedingtypesofcohesion.
UWO
TheComputerScienceDepartment
25
Procedural cohesion
Keeptogetherseveralproceduresthatareusedone
afteranother
Evenifonedoesnotnecessarilyprovideinputtothe
next.
Weakerthansequentialcohesion.
UWO
TheComputerScienceDepartment
26
Temporal Cohesion
Operationsthatareperformedduringthesamephaseof
theexecutionoftheprogramarekepttogether,and
everythingelseiskeptout
Forexample,placingtogetherthecodeusedduring
systemstartuporinitialization.
Weakerthanproceduralcohesion.
UWO
TheComputerScienceDepartment
27
Utility cohesion
Whenrelatedutilitieswhichcannotbelogicallyplaced
inothercohesiveunitsarekepttogether
Autilityisaprocedureorclassthathaswide
applicabilitytomanydifferentsubsystemsandis
designedtobereusable.
Forexample,thejava.lang.Mathclass.
UWO
TheComputerScienceDepartment
28
Question
Categorizethefollowingaspectsofdesignbythetypeof
cohesionthattheywouldexhibitifproperlydesigned:
Allinformationconcerningabookingofanappointmentiskeptinsidea
particularclass
AmoduleiscreatedtoconvertabitmapimagetoaJPEGformat
Aseparatesubsystemiscreatedthatrunseverynighttogeneratestats
aboutthepreviousdayssales
Adataprocessingoperationinvolvesreceivinginputfromseveral
sources,sortingit,summarizinginformationbyinputsource,sorting
accordingtotheinputsourcethatgeneratedthemostdataandthen
returningtheresultsfortheuseofothersubsystems.Thecodeforthese
stepsisallkepttogether,althoughutilitiesarecalledtodooperations
suchassorting
UWO
TheComputerScienceDepartment
29
Another Question
Whatiswrongwiththefollowingdesignfromthe
perspectiveofcohesionandwhatcouldbedonetoimprove
it?
Thereare2subsystemsinauniversityregistrationsystemthatdothe
following:
SubsystemAdisplayslistsofcoursestoastudent,acceptsrequestsfrom
thestudenttoregisterincourses,ensuresthatthestudenthasno
scheduleconflictsandiseligibletoregisterinthecourses,storesthe
datainthedatabaseandperiodicallybacksupthedatabase.
SubsystemBallowsfacultymemberstoinputstudentgrads,andallows
administratorstoassigncoursestofacultymembers,addnewcourses,
andchangeastudentsregistration.Italsoprintsthebillsthataresentto
students.
UWO
TheComputerScienceDepartment
30
Functionswhichperformaseriesofactionsrelatedonlybythetimewe
needtodothem
Exampleofhowthiscanarise:
Wehavea300linefunctionwewanttobreakup
Webreakitupinto6functions
Lines150
Lines51100
Webrokeupthefunctionintosmallerpiecesallright
However,eachpieceisjustwhateverweneededtodonext
Disadvantagesfordebugging:
Weareunlikelytorememberwheninthesequenceofactionsweneeded
todosomething
Hence,weneedtoscaneachofthefunctionsinturn
Basicallyequivalenttoscanningtheoriginalfunction
UWO
TheComputerScienceDepartment
31
UWO
TheComputerScienceDepartment
32
UWO
TheComputerScienceDepartment
33
Content coupling:
Occurswhenonecomponentsurreptitiouslymodifiesdata
thatisinternaltoanothercomponent
Toreducecontentcouplingyoushouldtherefore
encapsulateallinstancevariables
declarethemprivate
andprovidegetandsetmethods
Aworseformofcontentcouplingoccurswhenyoudirectly
modifyaninstancevariableofaninstancevariable
UWO
TheComputerScienceDepartment
34
UWO
TheComputerScienceDepartment
35
TheComputerScienceDepartment
36
Common coupling
Occurswheneveryouuseaglobalvariable
Allthecomponentsusingtheglobalvariablebecome
coupledtoeachother
Aweakerformofcommoncouplingiswhenavariable
canbeaccessedbyasubsetofthesystemsclasses
e.g.aJavapackage
Canbeacceptableforcreatingglobalvariablesthat
representsystemwidedefaultvalues
TheSingletonpatternprovidesencapsulatedglobalaccess
toanobject
UWO
TheComputerScienceDepartment
37
UWO
TheComputerScienceDepartment
38
UWO
TheComputerScienceDepartment
39
Control coupling
Occurswhenoneprocedurecallsanotherusingaflag
orcommandthatexplicitlycontrolswhatthesecond
proceduredoes
Tomakeachangeyouhavetochangeboththecalling
andcalledmethod
Theuseofpolymorphicoperationsisnormallythebest
waytoavoidcontrolcoupling
Onewaytoreducethecontrolcouplingcouldbetohave
alookuptable
commandsarethenmappedtoamethodthatshould
becalledwhenthatcommandisissued
UWO
TheComputerScienceDepartment
40
UWO
TheComputerScienceDepartment
41
TheComputerScienceDepartment
42
}
}
PersoncodingafunctionwhichcallsprintReporthastoremember
number,orgocheckprintReportcode
Easiertorememberfunctionnamethancodenumber
Toavoid:
Breakupfunctionsdoingtwodifferentthingsintoindividualones
withdescriptivenames
UWO
TheComputerScienceDepartment
43
TheComputerScienceDepartment
44
Stamp coupling:
Occurswheneveroneofyourapplicationclassesis
declaredasthetypeofamethodargument
Sinceoneclassnowusestheother,changingthesystem
becomesharder
Reusingoneclassrequiresreusingtheother
Twowaystoreducestampcoupling,
usinganinterfaceastheargumenttype
passingsimplevariables
UWO
TheComputerScienceDepartment
45
UWO
TheComputerScienceDepartment
46
Usingsimpledatatypestoavoidit:
public class Emailer
{
public void sendEmail(String name, String email, String text)
{...}
...
}
UWO
TheComputerScienceDepartment
47
UWO
TheComputerScienceDepartment
48
Data coupling
Occurswheneverthetypesofmethodargumentsare
eitherprimitiveorelsesimplelibraryclasses
Themoreargumentsamethodhas,thehigherthe
coupling
Allmethodsthatusethemethodmustpassallthe
arguments
Youshouldreducecouplingbynotgivingmethods
unnecessaryarguments
Thereisatradeoffbetweendatacouplingandstamp
coupling
Increasingoneoftendecreasestheother
UWO
TheComputerScienceDepartment
49
UWO
TheComputerScienceDepartment
50
UWO
TheComputerScienceDepartment
51
UWO
TheComputerScienceDepartment
52
TheComputerScienceDepartment
53
External coupling
Whenamodulehasadependencyonsuchthingsasthe
operatingsystem,sharedlibrariesorthehardware
It is best to reduce the number of places in the code
wheresuchdependenciesexist.
TheFaadedesignpatterncanreduceexternalcoupling
UWO
TheComputerScienceDepartment
54
Questions
Categorizethefollowingaspectsofadesignbythetypes
ofcouplingtheyexhibit:
ClassCourseSectionhaspublicclassvariablescalledminClassSizeand
maxClassSize.Thesearechangedfromtimetotimebytheuniversity
administration.ManymethodsinclassesStudentandRegistrationaccess
thesevariables.
AuserinterfaceclassimportsalargenumberofJavaclasses,including
thosethatdrawgraphics,thosethatcreateUIcontrolsandanumberof
otherutilityclasses.
AsystemhasaclasscalledAddress.Thisclasshas4publicvariables
constitutingdifferentpartsofanaddress.Severaldifferentclasses,suchas
PersonandAirportmanipulateinstancesofthisclass,directly
modifyingthefieldsofaddress.Also,manymethodsdeclareoneoftheir
argumentstobeanAddress
UWO
TheComputerScienceDepartment
55
UWO
TheComputerScienceDepartment
56
UWO
TheComputerScienceDepartment
57
Detailed Design
DecomposingFunctions
Couplingerrors
Cohesionerrors
Exampleofbreakingupafunction
Decomposing Functions
Oneofthemainproblemsweface:Howdoyoubreakupthetaskofcoding
alargesystemintosmallertasks?
Wewanttoendupwithfunctions(methods,procedures,etc)whichare
Conceptuallysimple:
Sowecankeepthemainconceptsinmind
Conceptuallyseparatefromothers
Sowedonthavetothinktoomuchaboutotherfunctionswhen
designing/writingthisone
Ifdonethisway:
Eachmodulecanbecodedmoreeasily
Modulescanbecodedeither
Onebyonebythesameperson,OR
Simultaneouslybymorethanoneperson
UWO
TheComputerScienceDepartment
59
UWO
TheComputerScienceDepartment
60
Functionswithalargenumberofparametersareverypickyto
callcorrectly
Also,functionswithalargenumberofparametersareusually
tryingtodotoomanythings
Howmanyparametersistoomany?
Dependsonthefunction
8parametersisalmostcertainlytoomany
Parametersshouldhaveaclearpurposeinthefunction
Otherwise,hardtotellhowtocallthefunctionjustfromthe
headerandcomments
Parameterswithaclearpurposecanbegivenparameternames
whichdescribetheirexactrolesinthefunction
UWO
TheComputerScienceDepartment
61
TheComputerScienceDepartment
62
TheComputerScienceDepartment
63
TheComputerScienceDepartment
64
Cohesion Errors
Wewilllookatseveralkindsoferrorsincohesion:
Functionwithnorealunifyingconcept(nofunctionalcohesion,
onlycoincidentalcohesion)WORST!
Functionperformsseveralrelatedbutdistinctactions(logical
cohesion)
Functionswhichperformaseriesofactionsrelatedonlybythetime
weneedtodothem(temporalcohesion)
Oftenarisefromtheneedtobreakupalargefunctionintoseveral
ormanysmallones
UWO
TheComputerScienceDepartment
65
TheComputerScienceDepartment
66
Onebadway:
Putlines196315inonefunctions(about2pageslong)
Putrestoflines(316462)inanotherfunction(alittleover2pageslong
Firstfunctionhasnoclearunifyingconcept(allocatesbuffer,eliminates
extension,extractsinfofromfname.000)
Cohesionerror ProceduralCohesion(wecandobetter!)
Secondfunctionhasclearunifyingconcept(writesrejoinedfile),butstilltoo
long
Otherbadideasinbreakingupthefunction:
Passeachofthe6piecesofinformationextractedfromthe.000filebackto
joinasaseparateparameter
ToomanyparametersDataCouplingError
Passentirewaystructuretocalledfunctions
Toomuchirrelevantdatainway StampCouplingError
UWO
TheComputerScienceDepartment
67
TheComputerScienceDepartment
68
TheComputerScienceDepartment
69
UWO
TheComputerScienceDepartment
70
Lethbridge/Laganire2005
Chapter9:Architectinganddesigningsoftware
71
Chapter9:Architectinganddesigningsoftware
72
Lethbridge/Laganire2005
Chapter9:Architectinganddesigningsoftware
73
Lethbridge/Laganire2005
Chapter9:Architectinganddesigningsoftware
74
Lethbridge/Laganire2005
Chapter9:Architectinganddesigningsoftware
75
Chapter9:Architectinganddesigningsoftware
76
Lethbridge/Laganire2005
Chapter9:Architectinganddesigningsoftware
77
Lethbridge/Laganire2005
Chapter9:Architectinganddesigningsoftware
78
Lethbridge/Laganire2005
Chapter9:Architectinganddesigningsoftware
79
Design by contract
Atechniquethatallowsyoutodesigndefensivelyinan
efficientandsystematicway
Keyidea
eachmethodhasanexplicitcontractwithitscallers
Thecontracthasasetofassertionsthatstate:
Whatpreconditionsthecalledmethodrequirestobe
truewhenitstartsexecuting
Whatpostconditionsthecalledmethodagreesto
ensurearetruewhenitfinishesexecuting
Whatinvariantsthecalledmethodagreeswillnot
changeasitexecutes
Lethbridge/Laganire2005
Chapter9:Architectinganddesigningsoftware
80