60
Introduction to Software Technology Software Quality Klaus Ostermann Some slides on refactoring adapted from CS246 course at U Waterloo Einführung in die Softwaretechnik 1

Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

IntroductiontoSoftwareTechnologySoftwareQuality

KlausOstermann

SomeslidesonrefactoringadaptedfromCS246courseatUWaterloo

EinführungindieSoftwaretechnik1

Page 2: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

SoftwareQuality

EinführungindieSoftwaretechnik2

}  Howcanwemaintainorimprovethequalityofsoftware?

}  Whatissoftwarequality,anyway?}  Correctimplementationofrequirementsspecification}  Designquality,modularity

}  Extensibility,Maintainability,Understandability,Readability,Reusability…

}  Robustnesstochange}  LowCoupling,HighCohesion

}  Reliability,FaultTolerance,Testability,Performance,…

Page 3: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

SoftwareQuality

EinführungindieSoftwaretechnik3

}  Howcanwemeasuresoftwarequality?

}  Whataboutsoftwaremetrics?Whatisasoftwaremetric?

“Youcan’tcontrolwhatyoucan'tmeasure”TomDeMarco,1986

Measurementistheempirical,objectiveassignmentofnumbers,accordingtoarulederivedfromamodelor

theory,toattributesofobjectsoreventswiththeintentofdescribingthem.

Kaner&Cem,“SoftwareEngineerMetrics:Whatdotheymeasureandhowdoweknow?”

Page 4: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

ExamplesofSoftwareMetrics

EinführungindieSoftwaretechnik4

}  LinesofCode(LoC)}  Bugsperlineofcode}  Commentdensity}  Cyclomaticcomplexity

}  measuresthenumberoflinearlyindependentpathsthroughaprogram'ssourcecode

}  Halsteadcomplexitymeasures}  Derivesoftwarecomplexityfromnumbersof(distinct)operandsand

operators}  Programexecutiontime}  TestCoverage}  Numberofclassesandinterfaces}  Abstractness=ratioofabstractclassestototalnumberofclasses}  …

Page 5: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

Metricsarerarelyused

EinführungindieSoftwaretechnik5

}  Fewcompaniesestablishmeasurementprograms,evenfewersucceedwiththem

}  ThosethatusemetricsoftendosoonlytoconformtocriteriaestablishedincertainqualitystandardssuchasCMM}  seeN.E.Fenton,"SoftwareMetrics:Successes,Failures&New

Directions”,1999

}  Onecouldinterpretthisasevidenceoftheimmaturityandunprofessionalismofthefield}  Aren’ttheengineerssosuccessfulbecausetheycanmeasure

quality?}  Butthisisagainthemisleading“softwareasengineeringproduct”

analogythatwasalreadyrefutedinthefirstlectureofthiscourse

Page 6: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

Metricsarerarelyuseduseful!

EinführungindieSoftwaretechnik6

}  Formallydefinedmetricsareobjective,butwhatdothesemeasurementsmean?}  Whatcanweconcludeaboutqualityifthecyclomaticcomplexityofourcodeis12?

}  Answer:Nothing.

}  Problem:Oftenunclearwhetherthemetriccorrelatestoanyusefulqualityfactor}  Similartotheattemptofmeasuringtheintelligenceofapersonintermsoftheweightorcircumferenceofthebrain

}  Ifafuturepotentialemployertellsyouabouttheirextensivesoftwaremetricssuite,run!J

Page 7: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

TomDeMarco23yearslater…

EinführungindieSoftwaretechnik7

“Thebook’smostquotedlineisitsfirstsentence:“Youcan’tcontrolwhatyoucan’tmeasure.”Thislinecontainsarealtruth,butI’vebecomeincreasinglyuncomfortablewithmyuseofit.Implicitinthequoteisthatcontrolisanimportantaspect,maybethemostimportant,ofanysoftwareproject.Butitisn’t.Manyprojectshaveproceededwithoutmuchcontrolbutmanagedtoproducewonderfulproducts.”TomDeMarco,“SoftwareEngineering:AnIdeaWhoseTimeHasComeandGone”,2009.

Page 8: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

SoftwareQuality

EinführungindieSoftwaretechnik8

}  Ifmetricsdon’twork,howdoweassessthequalityofsoftware?

}  Answer:Byacase-by-caseanalysisofeachindividualsoftwareproject}  Reasonaboutdesignquality,extensibility,…}  Reasonbycomparingtodesignsthathaveprovenuseful

}  Designpatternsetc.

}  Reasonbylookingfor“codesmells”andanti-patterns}  Byextensivetestsuites}  Byusinganalysistools:Staticanalysis,dynamicanalysis,formalverification

Page 9: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

CodeSmells

EinführungindieSoftwaretechnik9

}  Codesmell:Anysymptominthecodeofaprogramthatpossiblyindicatesadeeperproblem}  TermpopularizedbyKentBeckinhis“Refactoring”book

}  Commoncodesmells}  Duplicatedcode}  Longmethod,Largeclass}  Featureenvy,inappropriateintimacy}  Contrivedcomplexity

Page 10: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

Anti-Pattern

EinführungindieSoftwaretechnik10

}  Ananti-patternisapatternthatmaybecommonlyusedbutisineffectiveand/orcounterproductiveinpractice.

}  Adescriptionofanti-patternsisuseful}  Onecanrecognizetheforcesthatleadtotheirrepetitionandlearnhowothershaverefactoredthemselvesoutofthesebrokenpatterns.

}  Examples:}  Actionatadistance:Unexpectedinteractionbetweenotherwiseseparatedpartsofasystem

}  Sequentialcoupling:Aclassthatrequiresitsmethodstobecalledinaparticularorder

}  Circulardependency:Unnecessarydirectorindirectmutualdependenciesbetweensoftwaremodules

Page 11: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

Anti-Pattern

EinführungindieSoftwaretechnik11

}  MoreExamples:}  AbstractionInversion:Re-implementlow-levelfunctionsusinghigh-levelfunctions

}  Interfacebloat:Makinganinterfacesopowerfulthatitistoohardtoimplement

}  Busyspinorbusywaiting:ConsumingCPUwhilewaitingforsomethingtohappen

}  Seehttp://c2.com/cgi/wiki?AntiPatternsCatalogforanextensiveoverviewovercommonantipatterns

Page 12: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

Whattodoaboutanti-patternsandcodesmells?

EinführungindieSoftwaretechnik12

}  Refactoringsformalizetheideatosystematicallyremoveanti-patternsandcodesmells}  Oftenformalizedtoadegreethatitcanbeautomatedintheformof

anIDEtool}  Standardreference:à}  Refactoringscanoftenbeunderstoodtoimprovethemodularityofthecode

}  Refactoringsdonotchangethebehaviorofcode,e.g.,addafeature

}  Let’slookatsomesmellsandassociatedrefactoringsinmoredetail!

Page 13: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

Badsmellsandassociatedrefactorings

EinführungindieSoftwaretechnik13

}  Duplicatedcode–“The#1badsmell”}  Wehavealreadydiscussedhowtoabstractoverdifferentformsofduplicatedcodeinthelectureonreuse

}  Sameexpressionintwomethodsinthesameclass?}  Makeitaprivateauxiliaryroutineandparameterizeit

(Extract method refactoring)

}  Samecodeintworelatedclasses?}  Pushcommonalitiesintoclosestmutualancestorandparameterize}  UsetemplatemethodDPforvariationinsubtasks

(Form template method refactoring)

Page 14: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

Badsmellsandassociatedrefactorings

14

} Duplicatedcode}  Samecodeintwounrelatedclasses?

}  Oughttheyberelated?¨  Introduceabstractparent(Extract class, Pull up method)

}  Doesthecodereallybelongtojustoneclass?¨ Maketheotherclassintoaclient(Extract method)

}  Canyouseparateoutthecommonalitiesintoasubpartorotherfunctionobject?¨ Makethemethodintoasubobjectofbothclasses.¨  StrategyDPallowsforpolymorphicvariationofmethods-as-objects

(Replace method with method object) = apply strategy pattern

Page 15: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

ExtractClassRefactoring

EinführungindieSoftwaretechnik15

You have one class doing work that should be done by two. Create a new class and move the relevant fields and methods from the

old class into the new class.

Page 16: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

Pull-UpMethodRefactoring

EinführungindieSoftwaretechnik16

You have methods with identical results on subclasses. Move them to the superclass

Page 17: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

ExtractMethod Refactoring

EinführungindieSoftwaretechnik17

void printOwing() { printBanner(); //print details System.out.println ("name: " + _name); System.out.println ("amount " + getOutstanding()); }

void printOwing() { printBanner(); printDetails(getOutstanding()); } void printDetails (double outstanding) { System.out.println ("name: " + _name); System.out.println ("amount " + outstanding); }

You have a code fragment that can be grouped together. Turn the fragment into a method whose name explains the purpose of the method.

Page 18: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

18

Badsmellsincode

}  Long method }  Oftenasignof:

}  Tryingtodotoomanythings}  Poorlythoughtoutabstractionsandboundaries

}  Besttothinkcarefullyaboutthemajortasksandhowtheyinter-relate.Beaggressive!}  Breakupintosmallerprivatemethodswithintheclass

(Extract method) }  Delegatesubtaskstosubobjectsthat“knowbest”(i.e.,templatemethodDP)(Extract class/method, Replace data value with object)

Page 19: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

ReplaceDataValuewithObjectRefactoring

EinführungindieSoftwaretechnik19

You have a data item that needs additional data or behavior. Turn the data item into an object.

Page 20: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

20

Badsmellsincode

}  Long method }  Fowler’sheuristic:

} Whenyouseeacomment,makeamethod.}  Often,acommentindicates:

¨  Thenextmajorstep¨  Somethingnon-obviouswhosedetailsdetractfromtheclarityoftheroutineasawhole.

}  Ineithercase,thisisagoodspotto“breakitup”.

Page 21: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

21

Badsmellsincode}  Large class

}  i.e.,toomanydifferentsubpartsandmethods}  Twostepsolution:

1.  Gatherupthelittlepiecesintoaggregatesubparts.(Extract class, replace data value with object)

2.  Delegatemethodstothenewsubparts.(Extract method)

}  Likely,you’llnoticesomeunnecessarysubpartsthathavebeenhidingintheforest!

}  Resisttheurgetomicromanagethesubparts!

Page 22: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

22

Badsmellsincode

}  Large class }  Counterexample:

}  Libraryclassesoftenhavelarge,fatinterfaces(manymethods,manyparameters,lotsofoverloading)¨  Ifthemanymethodsexistforthepurposeofflexibility,that’s

OKinalibraryclass.

Page 23: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

23

Badsmellsincode

}  Long parameter list }  Longparameterlistsmakemethodsdifficultfor

clientstounderstand}  Thisisoftenasymptomof

}  Tryingtodotoomuch}  …toofarfromhome}  …withtoomanydisparatesubparts

"ifyourprocedurehasmorethanabouthalfadozenparameters,youprobablyforgotafew.“–AlanPerlis

Page 24: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

24

Badsmellsincode

}  Long parameter list }  Intheolddays,structuredprogrammingtaught

theuseofparameterizationasacureforglobalvariables.}  Withmodules/OOP,objectshavemini-islandsof

statethatcanbereasonablytreatedas“global”tothemethods(yetarestillhiddenfromtherestoftheprogram).

}  i.e.,Youdon’tneedtopassasubpartofyourselfasaparametertooneofyourownmethods.

Page 25: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

25

Badsmellsincode}  Long parameter list

}  Solution:}  Tryingtodotoomuch?

¨  Breakupintosub-tasks(Extract method)

}  …toofarfromhome?¨  Localizepassingofparameters;don’tjustpassdownseverallayers

ofcalls(Preserve whole object, introduce parameter object)

}  …withtoomanydisparatesubparts?¨  Gatherupparametersintoaggregatesubparts¨  Yourmethodinterfaceswillbemucheasiertounderstand!

(Preserve whole object, introduce parameter object)

Page 26: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

PreserveWholeObjectRefactoring

EinführungindieSoftwaretechnik26

int low = daysTempRange().getLow(); int high = daysTempRange().getHigh(); withinPlan = plan.withinRange(low, high);

withinPlan = plan.withinRange(daysTempRange());

You are getting several values from an object and passing these values as parameters in a method call.

Send the whole object instead.

Page 27: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

IntroduceParameterObjectRefactoring

EinführungindieSoftwaretechnik27

You have a group of parameters that naturally go together. Replace them with an object.

Page 28: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

28

Badsmellsincode

}  Divergent change }  Occurswhenoneclassiscommonlychangedindifferentwaysfor

differentreasons}  Likely,thisclassistryingtodotoomuchandcontainstoomany

unrelatedsubparts}  Overtime,someclassesdevelopa“Godcomplex”

}  Theyacquiresdetails/ownershipofsubpartsthatrightlybelongelsewhere

}  Thisisasignofpoorcohesion}  Unrelatedelementsinthesamecontainer

}  Solution:}  Breakitup,reshuffle,reconsiderrelationshipsandresponsibilities

(Extract class)

Page 29: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

29

Badsmellsincode}  Shotgun surgery

}  …theoppositeofdivergentchange}  Eachtimeyouwanttomakeasingle,seeminglycoherent

change,youhavetochangelotsofclassesinlittleways

}  Alsoaclassicsignofpoorcohesion}  Relatedelementsarenotinthesamecontainer!

}  Solution:}  Looktodosomegathering,eitherinaneworexistingclass.

(Move method/field)

Page 30: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

MoveMethodRefactoring

EinführungindieSoftwaretechnik30

A method is, or will be, using or used by more features of another class than the class on which it is defined.

Create a new method with a similar body in the class it uses most. Either turn the old method into a simple delegation, or remove it altogether

Page 31: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

MoveFieldRefactoring

EinführungindieSoftwaretechnik31

A field is, or will be, used by another class more than the class on which it is defined. Create a new field in the target class, and change all its users.

Page 32: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

32

Badsmellsincode}  Feature envy

}  Amethodseemsmoreinterestedinanotherclassthantheoneit’sdefinedine.g.,amethodA.m()callslotsofget/setmethodsofclassB

}  Solution:}  Movem()(orpartofit)intoB!

(Move method/field, extract method) }  Exceptions:

}  Visitor/iterator/strategyDPwherethewholepointistodecouplethedatafromthealgorithm¨  FeatureenvyismoreofanissuewhenbothAandBhaveinterestingdata

Page 33: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

33

Badsmellsincode}  Data clumps

}  Youseeasetofvariablesthatseemto“hangout”togethere.g.,passedasparameters,changed/accessedatthesametime

}  Usually,thismeansthatthere’sacoherentsubobjectjustwaitingtoberecognizedandencapsulated

void Scene::setTitle (string titleText, int titleX, int titleY, Colour titleColour){…}

void Scene::getTitle (string& titleText,

int& titleX, int& titleY, Colour& titleColour){…}

Page 34: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

34

Badsmellsincode}  Data clumps

}  Intheexample,aTitleclassiswaitingtobeborn}  Ifaclientknowshowtochangeatitle’sx,y,text,andcolour,

thenitknowsenoughtobeableto“rollitsown”Titleobjects.}  However,thisdoesmeanthattheclientnowhastotalktoanother

class.

}  Thiswillgreatlyshortenandsimplifyyourparameterlists(whichaidsunderstanding)andmakesyourclassconceptuallysimplertoo.

}  Movingthedatamaycreatefeature envyinitially}  Mayhavetoiterateonthedesignuntilitfeelsright.(Preserve whole object, extract class, introduce parameter

object)

Page 35: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

35

Badsmellsincode}  Primitive obsession

}  Allsubpartsofanobjectareinstancesofprimitivetypes(int, string, bool, double, etc.)e.g.,dates,currency,SIN,tel.#,ISBN,specialstringvalues

}  Often,thesesmallobjectshaveinterestingandnon-trivialconstraintsthatcanbemodellede.g.,fixednumberofdigits/chars,checkdigits,specialvalues

}  Solution:}  Createsome“smallclasses”thatcanencapsulatecoherent

subsetsoftheprimitivedataandvalidateandenforcetheconstraints.

(Replace data value with object, extract class, introduce parameter object)

Page 36: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

36

Badsmellsincode}  Switch statements

}  Wesawthisbefore;here’sFowler’sexample:

Double getSpeed () { switch (_type) {

case EUROPEAN: return getBaseSpeed(); case AFRICAN: return getBaseSpeed() – getLoadFactor() * _numCoconuts; case NORWEGIAN_BLUE: return (_isNailed) ? 0 : getBaseSpeed(_voltage);

} }

Page 37: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

37

Badsmellsincode}  Switch statements

}  Thisisanexampleofalackofunderstandingpolymorphismandalackofencapsulation.

}  Solution:}  RedesignasapolymorphicmethodofPythonBird (Replace conditional with polymorphism, replace type code with

subclasses)

Page 38: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

Replace conditional with polymorphism, replace type code with subclasses

EinführungindieSoftwaretechnik38

Replace conditional with polymorphism

replace type code with subclasses

Page 39: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

39

Badsmellsincode}  Lazy class

}  Classesthatdoesn’tdomuchthat’sdifferentfromotherclasses.}  Ifthereareseveralsiblingclassesthatdon’texhibitpolymorphic

behaviouraldifferences,thenconsiderjustcollapsingthembackintotheparentandaddsomeparameters

}  Often,lazy classesarelegaciesofambitiousdesignorarefactoringthatguttedtheclassofinterestingbehaviour

(Collapse hierarchy, inline class)

Page 40: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

Collapse hierarchy, inline class

EinführungindieSoftwaretechnik40

A class isn't doing very much. Move all its features into another class and delete it.

A superclass and subclass are not very different. Merge them together.

Page 41: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

41

Badsmellsincode}  Speculative generality

}  “Wemightneedthisoneday…”}  Fairenough,butdidyoureallyneeditafterall?}  Extraclassesandfeaturesaddtocomplexity.

}  “ExtremeProgramming”philosophy:}  “Assimpleaspossiblebutnosimpler.”}  “Ruleofthree”.

}  Keepinmindthatrefactoringisanongoingprocess.}  Ifyoureallydoneeditlater,youcanadditbackin.(Collapse hierarchy, inline class, remove parameter)

Page 42: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

42

Badsmellsincode}  Message chains

}  Aclientasksoneobjectforanotherobject,whichtheclientthenasksforyetanotherobject,whichtheclientthenasksforyetanotheranotherobject,

}  Navigatingthiswaymeanstheclientiscoupledtothestructureofthenavigation.

}  Anychangetotheintermediaterelationshipscausestheclienttohavetochange(cf.LawofDemeter)

}  Solution:Hide delegate

Page 43: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

Hide delegate refactoring

EinführungindieSoftwaretechnik43

A client is calling a delegate class of an object. Create methods on the server to hide the delegate.

Page 44: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

44

Badsmellsincode}  Middle man

}  “Allhardproblemsinsoftwareengineeringcanbesolvedbyanextralevelofindirection.”}  OODPsprettywellallboildowntothis,albeitinquitecleverand

elegantways.

}  Ifyounoticethatmanyofaclass’smethodsjustturnaroundandbegservicesofdelegatesubobjects,thebasicabstractionisprobablypoorlythoughtout.

}  Anobjectshouldbemorethanthesumofitspartsintermsofbehaviours!

(Remove middle man, replace delegation with inheritance)

Page 45: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

RemoveMiddleManRefactoring

EinführungindieSoftwaretechnik45

A class is doing too much simple delegation. Get the client to call the delegate directly

Page 46: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

ReplaceDelegationwithInheritance

EinführungindieSoftwaretechnik46

You're using delegation and are often writing many simple delegations for the entire interface.

Make the delegating class a subclass of the delegate

Page 47: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

47

Badsmellsincode}  Inappropriate intimacy

}  Sharingofsecretsbetweenclasses,esp.outsideoftheholyboundsofinheritancee.g.,publicvariables,indiscriminatedefinitionsofget/setmethods,C++

friendship,protecteddatainclasses}  Leadstodatacoupling,intimateknowledgeofinternalstructures

andimplementationdecisions.}  Makesclientsbrittle,hardtoevolve,easytobreak.

}  Solution:}  Appropriateuseofget/setmethods}  Rethinkbasicabstraction.}  Mergeclassesifyoudiscover“truelove”(Move/extract method/field, change bidirectional association to

unidirectional, hide delegate)

Page 48: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

48

Badsmellsincode

}  Alternative classes with different interfaces }  Classes/methodsseemtoimplementthesame

orsimilarabstractionyetareotherwiseunrelated.

}  Solution:}  Movetheclasses“closer”together.

¨  Findacommoninterface,perhapsanABC.¨  Findacommonsubpartandremoveit.

(Extract[super]class,movemethod/field,renamemethod)

Page 49: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

ExtractSuperclassRefactoring

EinführungindieSoftwaretechnik49

You have two classes with similar features. Create a superclass and move the common features to the superclass.

Page 50: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

50

Badsmellsincode

}  Data class }  Classconsistsof(simple)datafieldsandsimpleaccessor/mutator

methodsonly.}  Solution:

}  Havealookatusagepatternsintheclients}  Trytoabstractsomecommonalitiesofusageintomethodsofthedata

classandmovesomefunctionalityover}  “Dataclassesarelikechildren.TheyareOKasastartingpoint,but

toparticipateasagrownupobject,theyneedtotakeonsomeresponsibility.”

(Extract/move method)

Page 51: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

51

Badsmellsincode}  Comments

}  XPphilosophydiscouragescomments,ingeneral:}  Instead,makemethodsshortanduselongidentifiers

}  Inthecontextofrefactoring,Fowlerclaimsthatlongcommentsareoftenasignofopaque,complicated,inscrutablecode.}  Theyaren’tagainstcommentssomuchasinfavourofself-

evidentcodingpractices.}  Ratherthanexplainingopaquecode,restructureit!(Extract method/class, [many others applicable] …)

}  Commentsarebestusedtodocumentrationalei.e.,explainwhyyoupickedoneapproachoveranother.

Page 52: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

52

Summary}  Fowleretal.‘sRefactoringisawell-writtenbookthatsummarizesalotof

“bestpractices”ofOOD/OOPwithniceexamples.}  ManybooksonOODheuristicsarevagueandlackconcreteadvice.}  Mostoftheadviceinthisbookisaimedatlow-levelOOprogramming.

}  i.e.,loops,variables,methodcalls,andclassdefinitions.}  Nextobviousstepupinabstraction/scaleistoOODPs.

}  i.e.,collaboratingclasses

}  Thisisanexcellentbookfortheintermediate-levelOOprogrammer.}  ExperiencedOOprogrammerswillhavediscoveredalotofthetechniques

alreadyontheirown.

}  Manysourcesaboutrefactoringontheweb:}  http://refactoring.com/

Page 53: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

Testing

SomeslidesbyT.BallandJ.Aldrich

EinführungindieSoftwaretechnik53

Page 54: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

Whytest?

EinführungindieSoftwaretechnik54

Page 55: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

Testing:Challenges

EinführungindieSoftwaretechnik55

}  Testingiscostly}  Testeffectivenessandsoftwarequalityhardtomeasure}  Incomplete,informalandchangingspecifications}  Downstreamcostofbugsisenormous}  Lackofspecandimplementationtestingtools}  Integrationtestingacrossproductgroups}  Patchingnightmare}  Versionsexploding

Page 56: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

Example:TestingMSWord

EinführungindieSoftwaretechnik56

}  inputs}  keyboard}  mouse/pen}  .doc,.htm,.xml,…

}  outputs(WYSIWYG)}  Printers}  displays}  doc,.htm,.xml,…

}  variables}  fonts}  templates}  languages}  dictionaries}  styles

}  Interoperability}  Access}  Excel}  COM}  VB}  sharepoint

}  Otherfeatures}  34toolbars}  100sofcommands}  ?dialogs

}  Constraints}  hugeuserbase

Page 57: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

FromMicrosoftOfficeEULA…

EinführungindieSoftwaretechnik57

Page 58: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

FromGPL

EinführungindieSoftwaretechnik58

Page 59: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

Thegoalsoftesting

EinführungindieSoftwaretechnik59

}  Not-quite-rightanswers}  Makesureitdoesn’tcrash}  Regressiontesting–nonewbugs}  Makesureyoumeetthespec}  Makesureyoudon’thaveharmfulsideeffects

}  Actualgoals}  Revealfaults}  Establishconfidence}  Clarifyorrepresentthespecification

Page 60: Introduction to Software Technology Software Quality · Bad smells in code } Large class } i.e., too many different subparts and methods } Two step solution: 1. Gather up the little

THElimitationoftesting

EinführungindieSoftwaretechnik60

Testingcanonlyshowthepresenceoferrors,nottheirabsence

-E.W.Dijkstra

…tobecontinuedinthenextlecture!