Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Power of Patterns: Refactoring to (or away from) Patterns


Published on

What is a design pattern? Why should you care? What it the power of design patterns? How do design patterns tie into object oriented programming? If I'm using objects in my code, isn't that object oriented programming? (The answer is not necessarily!) When should I use them?

Design Patterns are great but the temptation is to use Design Patterns as a golden hammer. This can lead to unnecessarily complicated, over-engineered code in an effort to be flexible and ready for the future. That sounds reasonable - if you happen to be a psychic. More commonly, you will refactor to a pattern when the code (that you’ve written simply and minimally) demands it.

We'll talk about why you should know common design patterns, why they are powerful, how they relate to object oriented principles, different composite refactorings that will move you to (and sometimes away) from patterns and the smells that help you know when to apply them.

Published in: Technology
  • I went from getting $3 surveys to $500 surveys every day!! learn more... ♥♥♥
    Are you sure you want to  Yes  No
    Your message goes here
  • Secrets to making $$$ with paid surveys... ◆◆◆
    Are you sure you want to  Yes  No
    Your message goes here

Power of Patterns: Refactoring to (or away from) Patterns

  1. 1. Power of Patterns:Refactoring to (or away from)PatternsMike Clement@mdclementmike@softwareontheside.comhttp://blog.softwareontheside.com
  2. 2. Design Patterns Defined• Alexander’sArchitecture DesignPatterns• Published in 1977
  3. 3. “Each pattern describes a problemwhich occurs over and over againin our environment, and thendescribes the core of the solutionto the problem, in such a way thatyou can use this solution a milliontimes over, without ever doing itthe same way twice.”-Christopher Alexander
  4. 4. A Pattern is a solution to aproblem in a context• Context – recurring situation• Problem – goal and constraints• Solution – general design to resolve theproblemIf it only happened once,it’s not a pattern
  6. 6. Differentimplementations, but allrecognized as “a guitar”
  7. 7. Kitchen• Preparing/Cooking food• Stove• Refrigerator• Sink• Counter space• Storage/Cabinets/Drawers• Dishwasher
  8. 8. Power of a Pattern Language• Say more with less• Better communication• Stay “in the design” longer• A shared vocabulary
  9. 9. From Architecture to Software• 1987 – Kent Beck and Ward Cunninghampresented at OOPSLA• 1994 – GoF book published
  10. 10. GOF Pattern Template• Pattern Name• Classification• Intent• Also Known As• Motivation• Applicability• Structure• Participants• Collaborations• Consequences• Implementation• Sample Code• Known Uses• Related Patterns
  11. 11. We need some code that…When weather/stock/employeedata is updated, all the clients arenotified of the change.
  12. 12. Observer Pattern• Intent: Define a one-to-many dependencybetween objects so that when one objectchanges state, all its dependents are notifiedand updated automatically• Also Known As: Publish-Subscribe
  13. 13. Patterns are not created…They arediscovered!
  14. 14. LET’S DISCOVER A PATTERN!Object oriented principles sneak in
  15. 15. Duck Simulator
  16. 16. Adding “fly()”
  17. 17. But RubberDuck now flies…
  18. 18. Override fly?One possible solutionBut what happens when we have this?
  19. 19. Interfaces?
  20. 20. Encapsulate what variesImportant OOP Principle!
  21. 21. Behaviors separated
  22. 22. The New DuckImportant OOP Principle!Program to an interface, not an implementation
  23. 23. Delegate the behavior
  24. 24. The Strategy Pattern
  25. 25. Patterns are not created…They arediscovered!
  26. 26. Anti-Patterns• Why the bad solution is unattractive• Why in the long term it’s bad• Suggests other patterns for a good solutionTells you how to go from a problemto a BAD solution.
  27. 27. Catalog…• Big Ball of Mud• Gold Plating• Interface Bloat• God Object• Coding by Exception• Copy and Paste• Golden Hammer• Cargo Cult• Analysis Paralysis• Design by Committee• Vendor Lock-in• Groupthink• MushroomManagement
  28. 28. XP Simple Design• Passes all tests• Clear, expressive, consistent• No duplication• Minimal
  30. 30. Code Smells• Duplicated Code• Long Method• Large Class• Long Parameter List• Divergent Change• Shotgun Surgery• Feature Envy• Data Clumps• Primitive Obsession• Switch Statements• Parallel Inheritance Hierarchies• Lazy Class• Speculative Generality• Temporary Field• Message Chains• Middle Man• Inappropriate Intimacy• Alternative Classes with DifferentInterfaces• Incomplete Library Class• Data Class• Refused Bequest• Comments• Conditional Complexity• Indecent Exposure• Solution Sprawl• Combinatorial Explosion• Oddball SolutionFrom Refactoring and Refactoring to Patterns
  31. 31. • Extract Method• Inline Method• Move Method• Extract Class• Encapsulate Field• Rename Method• Add Parameter• Remove Parameter• Encapsulate Downcast• Pull Up Method• Push Down Method• Extract Superclass• Extract Subclass• Extract Interface
  32. 32. “There is a naturalrelation betweenpatterns andrefactoring. Patternsare where you want tobe; refactorings areways to get there fromsomewhere else.”Refactoring p. 107
  33. 33. Pattern To Towards AwayAdapter Extract Adapter (258),Unify Interfaces with Adapter(247) Unify Interfaces withAdapter(247)Builder Encapsulate Composite with Builder(96)Collecting Parameter Move Accumulation to Collecting Parameter(313)Command Replace Conditional Dispatcher with Command(191) Replace Conditional Dispatcherwith Command(191)Composed Method Compose Method (123)Composite Replace One/Many Distinctions with Composite(224), ExtractComposite(214), Replace Implicit Tree with Composite(178)Encapsulate Composite withBuilder(96)Creation Method Replace Constructors with Creation Methods (57)Decorator Move Embellishment to Decorator(144) Move Embellishment toDecorator(144)Factory Move Creation Knowledge to Factory (68),Encapsulate Classeswith Factory (80)Factory Method Introduce Polymorphic Creation with Factory Method (88)Interpreter Replace Implicit Language with Interpreter(269)Iterator Move Accumulation to Visitor(320)Null Object Introduce Null Object (301)Observer Replace Hard-Coded Notifications with Observer(236) Replace Hard-CodedNotifications withObserver(236)Singleton Limit Instantiation with Singleton(296) Inline Singleton(114)State Replace State-Altering Conditionals with State(166) Replace State-AlteringConditionals with State(166)Strategy Replace Conditional Logic with Strategy (129) Replace Conditional Logic withStrategy (129)Template Method Form Template Method (205)Visitor Move Accumulation to Visitor (320) Move Accumulation toVisitor (320)
  34. 34. Smell RefactoringDuplicated Code (39) Form Template Method(205)Introduce Polymorphic Creation with Factory Method(88)Chain Constructors(340)Replace One/Many Distinctions with Composite (224)Extract Composite(214)Unify Interfaces with Adapter (247)Introduce Null Object(301)Long Method(40) Compose Method (123)Move Accumulation to Collecting Parameter (313)Replace Conditional Dispatcher with Command (191)Move Accumulation to Visitor (320)Replace Conditional Logic with Strategy(129)Conditional Complexity(41) Replace Conditional Logic with Strategy(129)Move Embellishment to Decorator (144)Replace State-Altering Conditionals with State (166)Introduce Null Object(301)Primitive Obsession (41) Replace Type Code with Class (286)Replace State-Altering Conditionals with State ( 166)Replace Conditional Logic with Strategy(129)Replace Implicit Tree with Composite (178)Replace Implicit Language with Interpreter (269)Move Embellishment to Decorator (144)Encapsulate Composite with Builder (96)Indecent Exposure (42) Encapsulate Classes with Factory (80)Solution Sprawl (43) Move Creation Knowledge to Factory(68)Alternative Classes withDifferent Interfaces (43)Unify Interfaces with Adapter (247)Lazy Class (43) Inline Singleton (114)Large Class(44) Replace Conditional Dispatcher with Command (191)Replace State-Altering Conditionals with State (166)Replace Implicit Language with Interpreter (269)Switch Statements(44) Replace Conditional Dispatcher with Command (191) Move Accumulation to Visitor (320)Combinatorial Explosion (45) Replace Implicit Language with Interpreter (269)Oddball Solution (45) Unify Interfaces with Adapter (247)
  37. 37. XP Simple Design• Passes all tests• Clear, expressive, consistent• No duplication• Minimal?
  38. 38. Beyond• Application• Domain-Specific• Business Process• Organizational• User Interface Design
  39. 39. Learning more…I really like this one… some peoplefind it annoying. Puts DesignPatterns in the context of OOP.Great reference. Definitiveresource. Put me to sleep thefirst couple times I tried to readit though.
  40. 40. Learning more…The “Original” Refactoring book.All your classic refactorings!Great content and catalog ofcomposite refactorings to helpwith patterns.
  41. 41. Share the Vocabulary1) In design meetings2) In documentation3) In naming conventions4) To groups of interested developers
  42. 42. Action Items!• Play with Patterns• Share the Vocabulary– Study HFDP with your team• Build a common language• Participate in a local Software Craftsmanshipgroup near you!
  43. 43. My Contact Info• @mdclement••••• Utah Software Craftsmanship Group–– @utahsc