Bade Smells in Code

2,755 views

Published on

Intro to Code Smells (refer to Refactorin

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,755
On SlideShare
0
From Embeds
0
Number of Embeds
6
Actions
Shares
0
Downloads
18
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Bade Smells in Code

  1. 1. Bad Smells in CodeWill Shen2013/03/14
  2. 2. ReferenceMartin Fowler, “Refactoring - Improving theDesign of Existing Code”, Addison Wesley,1999.2
  3. 3. OutlineDefining RefactoringBad Smells in CodeReading Schedule3
  4. 4. 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
  5. 5. 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
  6. 6. 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
  7. 7. 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
  8. 8. DRY Principle8DO NOTTOUCHREPEATYOURSELF
  9. 9. 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
  10. 10. 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
  11. 11. Red/Green/Refactor11
  12. 12. Bad Smells in Code12
  13. 13. Bad Smells in CodeDuplicated CodeLong MethodLarge ClassLong Parameter ListDivergent ChangeShotgun SurgeryFeature EnvyData ClumpsPrimitive ObsessionSwitch StatementsParallel InheritanceHierarchiesLazy ClassSpeculativeGeneralityTemporary FieldMessage ChainsMiddle ManInappropriateIntimacyAlternative Classeswith DifferentInterfacesIncomplete LibraryClassData Class13
  14. 14. 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
  15. 15. 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
  16. 16. 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
  17. 17. 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
  18. 18. 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
  19. 19. 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
  20. 20. Feature EnvyA method seems more interested inanother classThe method clearly wants to beelsewhere  Move MethodOnly part of the method  ExtractMethod +Move Method20
  21. 21. 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
  22. 22. 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
  23. 23. 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
  24. 24. 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
  25. 25. 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
  26. 26. 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
  27. 27. 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
  28. 28. Message ChainsAGetB()GetC()…DoSomething()Hide Delegate at various points in thechain28
  29. 29. 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
  30. 30. 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
  31. 31. 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
  32. 32. 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
  33. 33. 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

×