Vous êtes sur la page 1sur 80

What does this code do?

public static String cvt(int x, int y, int z)


{
StringBuilder result = new StringBuilder();
if (x < 0 || x > 3999)
System.out.println("Value must be in the range 0 - 3,999.");
if (x == 0) return "N";
for (int i = 0; i < 13; i++)
{
while (x >= values[i])
{
x -= a[i];
result = result.append(b[i]);
}
}
return result.toString();
}

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

Object-Oriented Software Engineering


Practical Software Development using UML and Java
Chapter9:
Architecting and Designing Software
http://www.today.com/video/today/53341315#53341315

Design Decision
Question:Whataresomeofthethingsyouthink,asa
programmer,areimportantinordertosayapieceof
softwareisWellDesigned?
Question:Weallhavetomakedesigndecisionswhen
creatingsoftware.Letssaythatwedecidetonotusea
database.
Whymightwemakethatdecision?(Onereasonis
thatyourcs2212instructorwontletyou,whatare
otherpossiblereasons?)
Whatdowehavetothinkaboutwhenmakingthat
decision?
UWO

TheComputerScienceDepartment

9.1 The Process of Design


Definition:
Designisaproblemsolvingprocesswhoseobjectiveis
tofindanddescribeaway:
Toimplementthesystemsfunctional
requirements...
Whilerespectingtheconstraintsimposedbythe
nonfunctionalrequirements...
includingthebudget

Andwhileadheringtogeneralprinciplesofgood
quality

UWO

TheComputerScienceDepartment

Facebook Help
https://github.com/jsuwo/facebookappletserver
Lookatfbproxy.php(124160)and
FacebookClient.java(line155and354401)

UWO

TheComputerScienceDepartment

Design as a series of decisions


Adesignerisfacedwithaseriesofdesignissues
Thesearesubproblemsoftheoveralldesignproblem.
Eachissuenormallyhasseveralalternativesolutions:
designoptions.
Thedesignermakesadesigndecisiontoresolveeach
issue.
Thisprocessinvolveschoosingthebestoptionfrom
amongthealternatives.

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

UML diagram of system parts

UWO

TheComputerScienceDepartment

12

Top-down and bottom-up design


Topdowndesign
Firstdesigntheveryhighlevelstructureofthesystem.
Then gradually work down to detailed decisions about
lowlevelconstructs.
Finallyarriveatdetaileddecisionssuchas:
theformatofparticulardataitems;
theindividualalgorithmsthatwillbeused.

UWO

TheComputerScienceDepartment

13

Top-down and bottom-up design


Bottomupdesign
Makedecisionsaboutreusablelowlevelutilities.
Then decide how these will be put together to create
highlevelconstructs.
Amixoftopdownandbottomupapproachesare
normallyused:
Topdowndesignisalmostalwaysneededtogivethe
systemagoodstructure.
Bottomupdesignisnormallyusefulsothatreusable
componentscanbecreated.
UWO

TheComputerScienceDepartment

14

Different aspects of design


Architecturedesign:
Thedivisionintosubsystemsandcomponents,
Howthesewillbeconnected.
Howtheywillinteract.
Theirinterfaces.
Classdesign:
Thevariousfeaturesofclasses.
Userinterfacedesign
Algorithmdesign:
Thedesignofcomputationalmechanisms.
Protocoldesign:
Thedesignofcommunicationsprotocol.

UWO

TheComputerScienceDepartment

15

9.2 Principles Leading to Good Design


Overallgoalsofgooddesign:
Increasingprofitbyreducingcostandincreasingrevenue
Ensuringthatweactuallyconformwiththerequirements
Acceleratingdevelopment
Increasingqualitiessuchas
Usability
Efficiency
Reliability
Maintainability
Reusability

UWO

TheComputerScienceDepartment

16

Design Principle 1: Divide and conquer


Tryingtodealwithsomethingbigallatonceisnormally
muchharderthandealingwithaseriesofsmallerthings
Separatepeoplecanworkoneachpart.
Anindividualsoftwareengineercanspecialize.
Eachindividualcomponentissmaller,andtherefore
easiertounderstand.
Partscanbereplacedorchangedwithouthavingto
replaceorextensivelychangeotherparts.

UWO

TheComputerScienceDepartment

17

Ways of dividing a software system


Adistributedsystemisdividedupintoclientsand
servers
Asystemisdividedupintosubsystems
Asubsystemcanbedividedupintooneormore
packages
Apackageisdividedupintoclasses
Aclassisdividedupintomethods
UWO

TheComputerScienceDepartment

18

Design Principle 2: Increase cohesion where


possible
Asubsystemormodulehashighcohesionifitkeeps
togetherthingsthatarerelatedtoeachother,andkeeps
outotherthings
Thismakesthesystemasawholeeasiertounderstand
andchange
Typeofcohesion:
Functional,Layer,Communicational,Sequential,
Procedural,Temporal,Utility

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

Cohesion Error 1: No Unifying Concept


Functionwithnorealunifyingconcept
Thiscanhappenif,forinstance
Wesetarbitrarylimitsonthesizeofafunctionormodule
Wenoticedacommonsectionofcode,soputitinaseparate
functionwithoutconsideringwhatitdoes
Disadvantagesfordebugging
Hardtofigureoutwhatthefunctiondoes
Hardtoknowwhatfunctiontolookinwhenlookingforafault
Toavoidwhenbreakingupafunction
Trytoextractfunctionswithmoreintuitivemeaning

UWO

TheComputerScienceDepartment

21

Layer cohesion
Allthefacilitiesforprovidingoraccessingasetofrelated
servicesarekepttogether,andeverythingelseiskeptout
Thelayersshouldformahierarchy
Higherlayerscanaccessservicesoflowerlayers,
Lowerlayersdonotaccesshigherlayers
Thesetofproceduresthroughwhichalayerprovidesits
servicesistheapplicationprogramminginterface(API)
Youcanreplacealayerwithouthavinganyimpactonthe
otherlayers
YoujustreplicatetheAPI

UWO

TheComputerScienceDepartment

22

Example of the use of layers

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

Cohesion Errors: Time-Linked Actions


Think about WHY you have divided up
your code the way you have?

Functionswhichperformaseriesofactionsrelatedonlybythetimewe
needtodothem
Exampleofhowthiscanarise:
Wehavea300linefunctionwewanttobreakup
Webreakitupinto6functions
Lines150
Lines51100

Webrokeupthefunctionintosmallerpiecesallright
However,eachpieceisjustwhateverweneededtodonext
Disadvantagesfordebugging:
Weareunlikelytorememberwheninthesequenceofactionsweneeded
todosomething
Hence,weneedtoscaneachofthefunctionsinturn
Basicallyequivalenttoscanningtheoriginalfunction
UWO

TheComputerScienceDepartment

31

Avoiding Cohesion Errors


Grouptasksthatthefunctiondoesconceptually
Haveadeeperhierarchoffunctions;e.g.
Before:functionfcallsf1,f2,f3,f4,f5,f6
After:
fcallsg1,g2
g1callsh1,h2,h3
etc.
Similartohighleveldesignissueofavoidingpancake
structuretomodules

UWO

TheComputerScienceDepartment

32

Design Principle 3: Reduce coupling where


possible
Couplingoccurswhenthereareinterdependenciesbetween
onemoduleandanother
Wheninterdependenciesexist,changesinoneplacewill
requirechangessomewhereelse.
Anetworkofinterdependenciesmakesithardtoseeata
glancehowsomecomponentworks.
Typeofcoupling:
Content,Common,Control,Stamp,Data,RoutineCall,
Typeuse,Inclusion/Import,External

UWO

TheComputerScienceDepartment

33

Content coupling:
Occurswhenonecomponentsurreptitiouslymodifiesdata
thatisinternaltoanothercomponent
Toreducecontentcouplingyoushouldtherefore
encapsulateallinstancevariables
declarethemprivate
andprovidegetandsetmethods
Aworseformofcontentcouplingoccurswhenyoudirectly
modifyaninstancevariableofaninstancevariable

UWO

TheComputerScienceDepartment

34

Content Coupling: Changing Local Variables


Onefunctionchanginglocalvariablesofanotherfunction
Assumesthatfunctionshavetheirownlocaldata
ThisisthecaseinFortran,C,etc.
NotreallypossibleinOOlanguagessincedataassociatedwith
object,notfunctions
Disadvantage:iff changesgslocalvariables,thenchangingf often
requireschanginggorviceversa
Havetokeepbothinmindwhenchangingeither
Note,notthesameasoneobjectchangingattributesofanotherinan
OOlanguage
Dataisheldwithinanobjectinstance
CanbeOKifthechangedobjectisdesignedtoexpectit

UWO

TheComputerScienceDepartment

35

Example of content coupling


public class Line
{
private Point start, end;
...
public Point getStart() { return start; }
public Point getEnd() { return end; }
}
public class Arch
{
private Line baseline;
...
void slant(int newY)
{
Point theEnd = baseline.getEnd();
theEnd.setLocation(theEnd.getX(),newY);
}
}
UWO

TheComputerScienceDepartment

36

Common coupling
Occurswheneveryouuseaglobalvariable
Allthecomponentsusingtheglobalvariablebecome
coupledtoeachother
Aweakerformofcommoncouplingiswhenavariable
canbeaccessedbyasubsetofthesystemsclasses
e.g.aJavapackage
Canbeacceptableforcreatingglobalvariablesthat
representsystemwidedefaultvalues
TheSingletonpatternprovidesencapsulatedglobalaccess
toanobject

UWO

TheComputerScienceDepartment

37

Common Coupling: Global Variable


Communication
Functionscommunicatingviaglobalvariables
Onesetsvariable,anotherreferstovalue
ThisiscertainlypossibleinOOlanguages
Onestaticobjectcontainsallglobaldata
Thisobjectsattributesaresetandreferredto
Disadvantage:considerdebuggingtask:e.g.
Globalvariablecounthasgottensomestrangevalue
Bothfandghavebeencalled
Whichchangedittothestrangevalue?
Mustflipbackandforthbetweenfandgtofindout
Arethereotherfunctionswhichchangecount
Havetokeepwholeprograminmindwhendebugging

UWO

TheComputerScienceDepartment

38

Avoiding Common Coupling


Dontdeclarevariablesasglobal
Dontkeeptheminsomepublicaccessibleglobalobjecteither
Passtheminsteadasparameters
Passthemonlytothosefunctionswhichreallyneedthem
Thisway:
Weknowwhichfunctionschangethedata
Whenthereareproblemswiththatdata,wecanignorethefunctions
whichdontchangeit

UWO

TheComputerScienceDepartment

39

Control coupling
Occurswhenoneprocedurecallsanotherusingaflag
orcommandthatexplicitlycontrolswhatthesecond
proceduredoes
Tomakeachangeyouhavetochangeboththecalling
andcalledmethod
Theuseofpolymorphicoperationsisnormallythebest
waytoavoidcontrolcoupling
Onewaytoreducethecontrolcouplingcouldbetohave
alookuptable
commandsarethenmappedtoamethodthatshould
becalledwhenthatcommandisissued
UWO

TheComputerScienceDepartment

40

Control Coupling: Selecting Different Behaviour


Afunctionexpectingaparameterwhichselectsforcompletelydifferent
behaviours
Example1:
int testStack(int kind, Stack S) {
if ( ((kind==1) && (S.num == 0)) || ((kind==2) && (S.num == MAX) ) )
return 1;
else return 0;
}
WhatdoestestStackdo?
Seemstodotwocompletelydifferentthings
kindisamagicparameter
Selectsfromoneofthetwobehaviours
CanttellwhatvalueitshouldbewithoutlookingatcodefortestStack

UWO

TheComputerScienceDepartment

41

Control Coupling contd


Bettertohavetwofunctionsandnamethemintuitively:
int emptyStack (Stack S) {
if (S.num == 0)
return 1;
else return 0;
}
int fullStack (Stack S) {
if (S.num == MAXSTACK)
return 1;
else return 0;
}
Previouscodeworkedfine(ifcalledcorrectly)However,withnewcode:
Itisclearfromthefunctionnameswhatthefunctionsdo
Donthavetoguessatvaluesofparameters
UWO

TheComputerScienceDepartment

42

Control Coupling: Another Example


void printReport (int which) {
switch (which) {
case 1: /*code for printing monthly financial report */
case 2: /*code for printing report on Web usage */

}
}
PersoncodingafunctionwhichcallsprintReporthastoremember
number,orgocheckprintReportcode
Easiertorememberfunctionnamethancodenumber
Toavoid:
Breakupfunctionsdoingtwodifferentthingsintoindividualones
withdescriptivenames
UWO

TheComputerScienceDepartment

43

Example of control coupling


public routineX(String command)
{
if (command.equals("drawCircle")
{
drawCircle();
}
else
{
drawRectangle();
}
}
Question: What OO concept should we be using
to avoid control coupling like the example above?
UWO

TheComputerScienceDepartment

44

Stamp coupling:
Occurswheneveroneofyourapplicationclassesis
declaredasthetypeofamethodargument
Sinceoneclassnowusestheother,changingthesystem
becomesharder
Reusingoneclassrequiresreusingtheother
Twowaystoreducestampcoupling,
usinganinterfaceastheargumenttype
passingsimplevariables

UWO

TheComputerScienceDepartment

45

Coupling Error Stamp Coupling: Using


OnlyAfunctionusingonlyasmallpartofaparameter
a Piece
Example:codeforfindinghowmuchincometaxtodeductfromemployeessalary:
int incomeTaxPayable(Person p) {
/* code which refers to only p.salary */
}
Functionheaderleadsustobelievethat:
incomeTaxPayableusesallofp
WehavetokeepallofthePersonfieldsinmindwhendebugging
incomeTaxPayable
Better:
int incomeTaxPayable(int salary) {
Question:Howcanwefixtheabovesituation?
/* code which refers salary */
}
CallwouldbeincomeTaxPayable (employee.salary)ratherthan
incomeTaxPayable(employee)
ShowsclearlythatincomeTaxPayableisconcernedonlywiththeemployeessalary
Ifthecallingfunctioncanextractallthatisneededforthecalledfunction,itshould

UWO

TheComputerScienceDepartment

46

Example of stamp coupling


public class Emailer
{
public void sendEmail(Employee e, String text)
{...}
...
}

Usingsimpledatatypestoavoidit:
public class Emailer
{
public void sendEmail(String name, String email, String text)
{...}
...
}

UWO

TheComputerScienceDepartment

47

Example of stamp coupling


Usinganinterfacetoavoidit:
public interface Addressee
{
public abstract String getName();
public abstract String getEmail();
}
public class Employee implements Addressee {}
public class Emailer
{
public void sendEmail(Addressee e, String text)
{...}
...
}

UWO

TheComputerScienceDepartment

48

Data coupling
Occurswheneverthetypesofmethodargumentsare
eitherprimitiveorelsesimplelibraryclasses
Themoreargumentsamethodhas,thehigherthe
coupling
Allmethodsthatusethemethodmustpassallthe
arguments
Youshouldreducecouplingbynotgivingmethods
unnecessaryarguments
Thereisatradeoffbetweendatacouplingandstamp
coupling
Increasingoneoftendecreasestheother
UWO

TheComputerScienceDepartment

49

Routine call coupling


Occurswhenoneroutine(ormethodinanobject
orientedsystem)callsanother
The routines are coupled because they depend on each
othersbehaviour
Routinecallcouplingisalwayspresentinanysystem.
Ifyourepetitivelyuseasequenceoftwoormore
methodstocomputesomething
thenyoucanreduceroutinecallcouplingbywriting
asingleroutinethatencapsulatesthesequence.

UWO

TheComputerScienceDepartment

50

Routine call coupling, what can we do?


Assumewehavemethods:aaa,bbb,ccc,andddd,whatcouldwe
dotohelpwiththeroutinecallcouplingbelow?
private int aaa( )
{
//more code
ccc();
ddd();
ccc();
//more code
}
private int bbb( )
{ ccc()
ddd();
ccc();
//more code
ccc();
ddd();
ccc();
//more code
}

UWO

private int eee()


{ ccc()
ddd();
ccc();
}
private int aaa( )
{
//more code
eee();
//more code
}
private int bbb( )
{ eee()
//more code
eee();
//more code
}

TheComputerScienceDepartment

51

Type use coupling


Occurswhenamoduleusesadatatypedefinedin
anothermodule
Itoccursanytimeaclassdeclaresaninstancevariable
oralocalvariableashavinganotherclassforitstype.
Theconsequenceoftypeusecouplingisthatifthetype
definitionchanges,thentheusersofthetypemayhave
tochange
Alwaysdeclarethetypeofavariabletobethemost
generalpossibleclassorinterfacethatcontainsthe
requiredoperations

UWO

TheComputerScienceDepartment

52

Inclusion or import coupling


Occurswhenonecomponentimportsapackage
(asinJava)
orwhenonecomponentincludesanother
(asinC++).
The including or importing component is now exposed to
everythingintheincludedorimportedcomponent.
Iftheincluded/importedcomponentchangessomethingor
addssomething.
This may raises a conflict with something in the
includer,forcingtheincludertochange.
Aniteminanimportedcomponentmighthavethesame
nameassomethingyouhavealreadydefined.
UWO

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

Code Without Coupling Errors


Characteristicsofcodewithoutcouplingerrors:
Functionshavelownumberofparameters
Eachparameterhasanintuitivenameandmeaning
Functionusesallandonlythedataintheparameters
Thisisdatacoupling:agoodthing
Wesometimessaythat:
Functionswithcouplingerrorshavehighcouplingbecausetheyare
verydependantononeanother
Functionswithoutcouplingerrorshavelowcouplingbecausethey
arerelativelyindependent
Wethereforewantlowcouplingbetweenfunctions

UWO

TheComputerScienceDepartment

56

Code Without Cohesion Errors


Characteristicsofcodewithoutcohesionerrors:
Functionsarerelativelysmall
Functionnameshaveclearintuitivemeaning
Functionsactuallydoallandonlywhattheirnamessuggest
Referredtoasfunctionalcohesion:agoodthing
Wesometimessaythat:
Functionswithcohesionerrorshavelowcohesion,theydonthang
togetherverywell
Functionswithoutcohesionerrorshavehighcohesion,theyhang
togetherwell
Wewantcodewith:
Lowcouplingbetweenfunctions
Highcohesionwithinfunction

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

Characteristics of Ideal Functions


Wecanidentifysomecharacteristicsthatfunctionsshouldideallyhave:
Functionsshouldnotbetoolong
Longfunctionstendtobehardertodebug,sincewecanteasilyfind
whereinthefunctionsomethingisdone
Howlongistoolong?
Dependsonthefunctions
2pages(120lines)isalmostcertainlytoolong
Morethanthisonlyjustifiediffunctionhassomesimplehighlevel
structure,e.g.abigswitchstatement
Functionsshouldhaveaclearunifyingconcept
Thisleadstoaclearfunctionnamewhich:
Describesallandeverythingthefunctiondoes
Doesnotconcealanyofthetaskofthefunction
Allowsustoknowexactlywhatfunctiontogotowhendebugging

UWO

TheComputerScienceDepartment

60

Characteristics of Ideal Function contd


Functionsshouldhaverelativelyfewparameters

Functionswithalargenumberofparametersareverypickyto
callcorrectly
Also,functionswithalargenumberofparametersareusually
tryingtodotoomanythings
Howmanyparametersistoomany?
Dependsonthefunction
8parametersisalmostcertainlytoomany
Parametersshouldhaveaclearpurposeinthefunction

Otherwise,hardtotellhowtocallthefunctionjustfromthe
headerandcomments
Parameterswithaclearpurposecanbegivenparameternames
whichdescribetheirexactrolesinthefunction

UWO

TheComputerScienceDepartment

61

Straying from the Ideal


Codecanusuallygetawayfromtheseidealsforvariousreasons
Usuallyasaresultofproblemsweencounterincoding
Example:functioncantdoeverythingwewantedittodowithoutan
extraparameter
Typicalsolution:
Slapontheextraparameter
Ifcallingfunctionneedstheparametertobeabletopassitontothis
one,thenslapitontheretoo
Anothersimplesolution:
Defineaglobalvariable
Functionsnowhardertodebugsinceglobalvariablelinkageishidden
Example:functionneedsmorecodethanweexpected
Typicalsimplesolution:justletthefunctiongrowandgrow
Example:werealizewehavetobreakupafunction
Typicalsimplesolution:breakitupinto2or3pieces,withoutaclear
purposetoanyonepiece
UWO

TheComputerScienceDepartment

62

Example of a Poorly Designed Function


Seeprogramfilesplt.contheClassnoteswebpage
PublicdomainLinusprogramwhichcan:
Splitafileintosmallerfiles(Whydoyouthinkthisprogramwas
written?Whomightuseit?)
Rejoinpieces
Piecesoffilemyfile.dat(e.g.)areputinfilesnamemyfile.001, myfile.002,
etc.
Informationforreconstructingoriginalfileputinfilenamedmyfile.000,
includingoriginallength
Considerfunctionjoin(lines175464)
Joinspiecesofafiletogetheragain(reconstructsfile)
Header:void join (struct easy *way);
Obscurestructandparameternames,butnotmanyparameters
However,289lines(about5pages)waytoolong
Codeshouldhavebeensplitupinsomeintelligentway
Wewillgetbacktothissoon
UWO

TheComputerScienceDepartment

63

Ultimate Result of Poor Design: Code Meltdown


Codecanmeltdownintojumbledmess,makingit:
Difficulttodebugandaddfeaturesto
Difficulttoeventracewhatishappening
Wecanavoidcodemeltdownsbyactingproactively
Buildhighlevelanddetaileddesigninwhich:
Tasksalreadybrokenupintoreasonablesizedsubtasks
Functionsareconceptuallysimple
Functionsareconceptuallyseparatefromothers
Whilecoding,ifwefindthatsomecodeismeltingdown:
Dontjustmakeaquickfix
Stepbackandredesign(refactor)thatpart
Maybeabletosalvagesomecodeinnewdesign
Keyconceptsinpreventingandcorrectingcodemeltdown:
Coupling
Cohesion
UWO

TheComputerScienceDepartment

64

Cohesion Errors
Wewilllookatseveralkindsoferrorsincohesion:
Functionwithnorealunifyingconcept(nofunctionalcohesion,
onlycoincidentalcohesion)WORST!
Functionperformsseveralrelatedbutdistinctactions(logical
cohesion)
Functionswhichperformaseriesofactionsrelatedonlybythetime
weneedtodothem(temporalcohesion)
Oftenarisefromtheneedtobreakupalargefunctionintoseveral
ormanysmallones

UWO

TheComputerScienceDepartment

65

Breaking up a Function: Example


Considerfunctionjoininfilespltagain
Howtobreakitup?
Algorithm:
Allocate(possiblylarge)buffer(lines196210)
Eliminateextensionoffilename(212224)
Extractinformationfromfilefname.000:originalfilename,length,etc.
Trytoopenthefile(228264)
Ifwecanopen,extractalltheinformation(265315)
Writetherejoinedfile
Openthefilewhichwillcontaintherejoineddata(316362)
Foreachfilecontainingapieceofthedata:
Copythatpieceintotheoutputfile,maintaininglength,etc.(364
407)
Closetheoutputfile(409410)
Verifythatlength,etc.agreeswithoriginal(415446)
Writeoutareportaboutwhathashappened(449462)
UWO

TheComputerScienceDepartment

66

Some Bad Ways of Breaking Up join

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

One Possible Good Way of Breaking Up join


joinfunctionpseudocode
Allocate buffer in buf (allocateBuffer)
Let basename = filename with extension (extractBaseName)
Extract information from .000 file (extractInfo)
If previous operation succeeded:
If output file specified, open output file
Otherwise, open original filename
Rejoin file from pieces and verify (rejoinVerifyFile)
Headerforcalledfunctions
char *allocateBuffer()
char *extractBaseName(char *filename)
void extractInfo (char *basename, FileInfo *fileInfo, int *success);
void rejoinVerifyFile(char *basename, FileInfo *fileInfo, char *buf, FILE
*outputFile);
UWO

TheComputerScienceDepartment

68

Breaking Up join contd


PseudocodeforrejoinVerifyFile:
Let fnumber = 1, success = 1
While fnumber <= numFiles and still success:
Construct inputFilename using basename and fnumber (constructFilename)
Try opening inputFile (tryOpen)
If open successful,
- Copy bytes from inputFile to outputFile, updating length, etc.
(copyBytes)
- Increment fnumber
Else, let success = 0
If success, verify that length, etc. is consistent with fileInfo (verifyLengthEtc)
Write report
Headersforcalledfunctions:
char *constructFilename (char *baseName, int fnumber);
FILE *tryOpen(char *filename, int *success);
void copyBytes(FILE *inFile, FILE *outFile, int *length, int *checksum);
void verifyLengthEtc(FileInfo *fileInfo, int length, int checksum);
UWO

TheComputerScienceDepartment

69

Breaking Up join contd


Ifwedidthingsassuggestedabove:
9functionsinsteadof1
Eachfunctionhasclearpurpose,parameters
Nofunctionwouldbeoverapage
WouldneedanextradefinitionfortheFileInfotype
However,thistypeencapsulatesalotofinformation
Veryuseful,promoteslowcoupling,highcohesion
USEDMAINLYFUNCTIONALCOHESION!
Yourmileagemayvary
Feelfreetodisputethechoicesmadeabove
Manyotherwaysofbreakingupwouldbeequallyvalid
Leavingitasitiswouldcertainlycausedebuggingproblems

UWO

TheComputerScienceDepartment

70

Design Principle 4: Keep the level of


abstraction as high as possible
Ensurethatyourdesignsallowyoutohideordefer
considerationofdetails,thusreducingcomplexity
Agoodabstractionissaidtoprovideinformationhiding
Abstractionsallowyoutounderstandtheessenceofa
subsystemwithouthavingtoknowunnecessarydetails

Lethbridge/Laganire2005

Chapter9:Architectinganddesigningsoftware

71

Abstraction and classes


Classes are data abstractions that contain procedural
abstractions
Abstraction is increased by defining all variables as
private.
The fewer public methods in a class, the better the
abstraction
Superclasses and interfaces increase the level of
abstraction
Attributesandassociationsarealsodataabstractions.
Methodsareproceduralabstractions
Betterabstractionsareachievedbygivingmethods
fewerparameters
Lethbridge/Laganire2005

Chapter9:Architectinganddesigningsoftware

72

Design Principle 5: Increase reusability


where possible
Designthevariousaspectsofyoursystemsothatthey
canbeusedagaininothercontexts
Generalizeyourdesignasmuchaspossible
Followtheprecedingthreedesignprinciples
Designyoursystemtocontainhooks
Simplifyyourdesignasmuchaspossible

Lethbridge/Laganire2005

Chapter9:Architectinganddesigningsoftware

73

Design Principle 6: Reuse existing designs


and code where possible
Designwithreuseiscomplementarytodesignfor
reusability
Activelyreusingdesignsorcodeallowsyoutotake
advantageoftheinvestmentyouorothershavemadein
reusablecomponents
Cloningshouldnotbeseenasaformofreuse

Lethbridge/Laganire2005

Chapter9:Architectinganddesigningsoftware

74

Design Principle 7: Design for flexibility


Activelyanticipatechangesthatadesignmayhaveto
undergointhefuture,andprepareforthem
Reducecouplingandincreasecohesion
Createabstractions
Donothardcodeanything
Leavealloptionsopen
Donotrestricttheoptionsofpeoplewhohaveto
modifythesystemlater
Usereusablecodeandmakecodereusable

Lethbridge/Laganire2005

Chapter9:Architectinganddesigningsoftware

75

Design Principle 8: Anticipate obsolescence


Planforchangesinthetechnologyorenvironmentso
thesoftwarewillcontinuetorunorcanbeeasily
changed
Avoidusingearlyreleasesoftechnology
Avoidusingsoftwarelibrariesthatarespecificto
particularenvironments
Avoidusingundocumentedfeaturesorlittleused
featuresofsoftwarelibraries
Avoidusingsoftwareorspecialhardwarefrom
companiesthatarelesslikelytoprovidelongterm
support
Usestandardlanguagesandtechnologiesthatare
supportedbymultiplevendors
Lethbridge/Laganire2005

Chapter9:Architectinganddesigningsoftware

76

Design Principle 9: Design for Portability


Havethesoftwarerunonasmanyplatformsaspossible
Avoidtheuseoffacilitiesthatarespecifictoone
particularenvironment
E.g.alibraryonlyavailableinMicrosoftWindows

Lethbridge/Laganire2005

Chapter9:Architectinganddesigningsoftware

77

Design Principle 10: Design for Testability


Takestepstomaketestingeasier
Designaprogramtoautomaticallytestthesoftware
DiscussedmoreinChapter10
Ensurethatallthefunctionalityofthecodecanby
drivenbyanexternalprogram,bypassingagraphical
userinterface
InJava,youcancreateamain()methodineachclassin
ordertoexercisetheothermethods

Lethbridge/Laganire2005

Chapter9:Architectinganddesigningsoftware

78

Design Principle 11: Design defensively


Nevertrusthowotherswilltrytouseacomponentyou
aredesigning
Handleallcaseswhereothercodemightattempttouse
yourcomponentinappropriately
Checkthatalloftheinputstoyourcomponentarevalid:
thepreconditions
Unfortunately,overzealousdefensivedesigncan
resultinunnecessarilyrepetitivechecking

Lethbridge/Laganire2005

Chapter9:Architectinganddesigningsoftware

79

Design by contract
Atechniquethatallowsyoutodesigndefensivelyinan
efficientandsystematicway
Keyidea
eachmethodhasanexplicitcontractwithitscallers
Thecontracthasasetofassertionsthatstate:
Whatpreconditionsthecalledmethodrequirestobe
truewhenitstartsexecuting
Whatpostconditionsthecalledmethodagreesto
ensurearetruewhenitfinishesexecuting
Whatinvariantsthecalledmethodagreeswillnot
changeasitexecutes
Lethbridge/Laganire2005

Chapter9:Architectinganddesigningsoftware

80

Vous aimerez peut-être aussi