Bade Smells in Code

on

  • 1,968 views

Intro to Code Smells (refer to Refactorin

Intro to Code Smells (refer to Refactorin

Statistics

Views

Total Views
1,968
Views on SlideShare
1,968
Embed Views
0

Actions

Likes
1
Downloads
10
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Bade Smells in Code Bade Smells in Code Presentation Transcript

  • Bad Smells in CodeWill Shen2013/03/14
  • ReferenceMartin Fowler, “Refactoring - Improving theDesign of Existing Code”, Addison Wesley,1999.2
  • OutlineDefining RefactoringBad Smells in CodeReading Schedule3
  • Defining RefactoringRefactoring (noun)• a change made to the internal structure ofsoftware to make it easier to understand andcheaper to modify without changing itsobservable behavior.Refactor (verb)• to restructure software by applying a series ofrefactorings without changing its observablebehavior4
  • Why Should You Refactor?To improve the design of softwareTo make software easier to understand• Somebody else will eventually have to read yourcodeTo help you find bugsTo help you program faster5
  • When to do Refactoring1. Refactor when you add function• Helps you to understand the code you are modifying• Sometimes the existing design does not allow you to easilyadd the feature2. Refactor when you need to fix a bug• the code was not clear enough for you to see the bug inthe first place3. Refactor as you do a code review• Code reviews help spread knowledge through thedevelopment team6
  • The Rule of three - Three strikes and you refactor1. The first time you do something, you just doit.2. The second time you do something similar,you wince at the duplication, but you do theduplicate thing anyway.3. The third time you do something similar, yourefactor.7
  • DRY Principle8DO NOTTOUCHREPEATYOURSELF
  • Refactoring and DesignRefactoring changes the role of upfrontdesign•  Code the first approach you discover get it working refactor it into shapeA reasonable solution > looking for theperfect solutionRefactoring can lead to simpler designswithout sacrificing flexibility9
  • Refactoring and Unit TestsRefactoring is strongly dependent onhaving a good suite of unit tests• To verify that the behavior is indeed preservedWithout unit tests  the fear thatsomething may break.10
  • Red/Green/Refactor11
  • Bad Smells in Code12
  • Bad Smells in CodeDuplicated CodeLong MethodLarge ClassLong Parameter ListDivergent ChangeShotgun SurgeryFeature EnvyData ClumpsPrimitive ObsessionSwitch StatementsParallel InheritanceHierarchiesLazy ClassSpeculativeGeneralityTemporary FieldMessage ChainsMiddle ManInappropriateIntimacyAlternative Classeswith DifferentInterfacesIncomplete LibraryClassData Class13
  • Duplicated CodeCode that is thesame, or performsthe same functionare showing up inmultiple placeswithin a programHaving the sameexpression in twomethods of the sameclass  ExtractMethodHaving the sameexpression in twosibling subclasses Extract Method + PullUp FieldHaving duplicatedcode in two unrelatedclasses  ExtractClass14
  • Long MethodA lack of properencapsulationIt does too muchitself, and doesntdelegate that work tothe properauthoritiesPrevent code reuseTo shorten a method Extract MethodPassing a lot ofparameters Replace Temp withQuerySliming down thelong list ofparameters Introduce ParameterObject, PreserveWhole Object15
  • Large ClassA class has taken ontoo muchresponsibilities.• Complexity - hard tounderstand.• Bloat - take longer tounderstand.A class doing toomuch  too manyinstance variablesduplicated code!Extract Class +Extract Subclass16
  • Long Parameter ListThe method is doingtoo much - why doesit need all of thatinformation?Understandability -lots of parameterswill make codeharder tounderstand.difficult to usechanging them needsmore dataReplace Parameterwith Method whenyou can get the datain one parameter making a request ofan object17
  • Divergent ChangeOne class is commonly changed in differentways for different reasonsTo clean this up you identify everything thatchanges for a particular cause and use ExtractClass to put them all together18
  • Shotgun SurgeryMake a kind ofchange  have tomake a lot of littlechanges to a lot ofdifferent classesChanges are hard tofindEasy to miss animportant change.Move Method andMove Field to put allthe changes in asingle classIf no current classlooks like a goodcandidate then createone – Extract ClassInline Class to bringa whole bunch ofbehavior together19
  • Feature EnvyA method seems more interested inanother classThe method clearly wants to beelsewhere  Move MethodOnly part of the method  ExtractMethod +Move Method20
  • Data ClumpsSee the same three or four data items togetherin lots of places:• Fields in a couple of classes• Parameters in many method signaturesUse Extract Class to turn the clumps into anobjectFor method parameters use IntroduceParameter Object or Preserve Whole Object toslim them down21
  • Primitive ObsessionUsing primitive datatypes and method calls togenerate desiredoutcomes, and could bewritten in a moredescriptive andsustainable way.People new to objects aresometimes reluctant touse small objects forsmall tasksReplace Data Value withObject on individual datavaluesReplace Type Code withClass if the value does noteffect the behaviorHave conditional thatdepend on the type code Replace Type Code withSubclass or Replace TypeCode with State/Strategy22
  • Switch StatementsSee a switch statement  polymorphismExtract Method + Move MethodOnly have a few case that effect a singlemethod then polymorphism is overkill Replace Parameter with Explicit MethodsOne of the conditional cases is null Introduce Null Object23
  • Parallel Inheritance HierarchiesMake a subclass of one class  you have tomake a subclass of another (this is a specialcase of shotgun surgery)To make sure that instances of one hierarchyrefer to instance of anotherMove Method + Move Field  the hierarchy onthe referring class disappears24
  • Lazy ClassA class that is notcarrying its weightshould be eliminated• Each class you createcosts money and time tomaintain and understandSubclasses that arenot doing enough Collapse HierarchyNearly uselesscomponents  InlineClass25
  • Speculative GeneralityCreating today what wespeculate will be neededin the future• the only users of a class ormethod are test casesAbstract classes that arenot doing enough Collapse HierarchyUnnecessary delegation Inline ClassMethods with unusedparameters should Remove ParameterMethods named with oddabstract names Rename Method26
  • Temporary FieldSee an object inwhich an instancevariable is set only incertaincircumstancesdifficult tounderstand becausewe usually expect anobject to use all of itsvariablesUse Extract Class tocreate a home fororphan variablesEliminate conditionalcode by usingIntroduce Null Objectto create analternativecomponent for whenthe variables are notvalid27
  • Message ChainsAGetB()GetC()…DoSomething()Hide Delegate at various points in thechain28
  • Middle ManEncapsulation  often comes with delegation sometimes delegation can go to farHalf the methods are delegated to another class Remove Middle Man and talk to the object that reallyknows what is going onA few methods are not doing much  Inline MethodIf there is additional behavior  Replace Delegationwith Inheritance to turn the middle man into a subclassof the real object29
  • Inappropriate IntimacySometimes classesbecome far toointimate and spendtoo much time ineach others privatepartsUse Move Method andMove Field to separatethe pieces to reduce theintimacyIf the classes do havecommon interests• Extract Class to put thecommonality in a safe place• Hide Delegate to let anotherclass act as a go-betweenChange BidirectionalAssociation toUnidirectional30
  • Alternative Classes with Different Interfacesuse Rename Method on any methods that dothe same thing but have different signaturesfor what they doKeep using Move Method to move behavior toother classes until the protocols are the sameIf you have to redundantly move code toaccomplish this, you may be able to useExtract Superclass31
  • Incomplete Library ClassThe library isinsufficient foryour needsIf there are just acouple of methodsthat you wish thelibrary class had Introduce ForeignMethodIf there is more extrabehavior you need Introduce LocalExtension32
  • Data ClassClasses that have fields,getting and settingmethods, and nothingelseDumb data holdersManipulated in far toomuch detail by otherclassespublic fields Encapsulate FieldA collection of fields Encapsulate CollectionRemove Setting Methodon any field that shouldnot be changedMove Method to movebehavior into the dataclassIf you cant move a wholemethod, use ExtractMethod to create amethod that can bemoved33