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

1,598 views
1,450 views

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
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,598
On SlideShare
0
From Embeds
0
Number of Embeds
286
Actions
Shares
0
Downloads
24
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide
  • "Each solution is stated in such a way that it gives the essential field of relationships needed to solve the problem, but in a very general and abstract way - so that you can solve the problem for yourself, in your own way, by adapting it to your preferences, and the local conditions at the place where you are making it.“Includes patterns for “problems” such asHomes“Couple’s Realm”“Farmhouse Kitchen”“Bulk Storage”Offices Space“Communal Eating”“A Place to Wait”Communities“Ring Roads”“Web of Shopping”“Sacred Sites”“Night Life”“Household Mix”
  • What are some of the properties of a kitchen?When you say “kitchen” you get all those other descriptors for free. Instead of detailing everything, you can focus on exceptions and specifics to the pattern.Ex. Kitchen WITHOUT a dishwasher or GRANITE countertops
  • From Head First Design Patterns p28A shared vocabularycommunicating qualities, characteristics and constraintsSay more with lessStay “in the design” longer – avoids getting prematurely into implementation detailsteam moves more quickly with less room for misunderstandingGets new hires up to speed – easily allows new hires (college or industry)to get up to speed with defined patterns
  • 1987 is when Kent Beck and Ward Cunningham first introduced the concept to software. Took another few years before the GoF book was published and then from there it’s exploded.
  • Sample CodeUse of sample code is a little bit controversial because of the previous statements. GoF writers decided that the usefulness of having something concrete outweighed the need for “purity” in their pattern catalog. Even class diagrams can be too prescriptive which we’ll see later.ConsequencesBoth positive and negative. Sometimes a pattern’s effects are not entirely positive.
  • Instead of this, I could simply say… let’s use the…
  • Often as part of a pattern definition we’ll have a class diagram to help describe how the pattern *could* be implemented. Remember Alexander said a pattern means that we can “use this solution a million times over, without ever doing it the same way twice”Raises the question, Is a class diagram too much for pattern definition?.NET alternatives to this class structure?
  • Those that build pattern catalogs aren’t “creators” but are discoverers. They “see” the pattern and catalog it.
  • Two of the OO Basics that usually go hand in hand are Inheritance and Polymorphism. If you don’t remember, the other two are Abstraction and Encapsulation. (these can change depending on who is defining… but regardless…)What is a “classic” use of inheritance and polymorphism? What’s the first think you coded up in intro to programming that used inheritance?Shapes, animalsWe’re going to use ducks…
  • “Classic” use of inheritance… different types of somethingCurrently we just have to display the ducks so this is okay. But…
  • What if we add “fly()”? Here we add it to the base class and all the subclasses fly fine but…
  • What seemed like a great use of inheritance for reuse hasn’t worked out so well for maintenanceRemember, that writing code “fast” now isn’t usually the main goal. We need to write code that can be easily maintained.By maintained I mean any future modification, including debugging and modifications BEFORE release of the product.
  • Using the Java “able” interface convention.No inappropriate behaviors but now behavior code is duplicated.We traded one maintenance problem for another!
  • Instead of having the behavior embedded in the classes, we’re going to encapsulate them elsewhere. This way they are centralized (not duplicated) and
  • Here we are now programming the Behavior INTERFACES not the concrete implementations
  • Those that build pattern catalogs aren’t “creators” but are discoverers. They “see” the pattern and catalog it.
  • Ineffective and/or counterproductive practices.Why Anti-patterns?By formally describing repeated mistakes, one can recognize the forces that lead to their repetition and learn how others have refactored themselves out of these broken patterns.
  • Big ball of mud: A system with no recognizable structureGold plating: Continuing to work on a task or project well past the point at which extra effort is adding valueInterface bloat: Making an interface so powerful that it is extremely difficult to implementGod object: Concentrating too many functions in a single part of the design (class)Coding by exception: Adding new code to handle each special case as it is recognizedCopy and paste programming: Copying (and modifying) existing code rather than creating generic solutionsGolden hammer: Assuming that a favorite solution is universally applicableCargo cult programming: Using patterns and methods without understanding whyAnalysis paralysis: Devoting disproportionate effort to the analysis phase of a projectDesign by committee: The result of having many contributors to a design, but no unifying visionVendor lock-in: Making a system excessively dependent on an externally supplied componentGroupthink: During groupthink, members of the group avoid promoting viewpoints outside the comfort zone of consensus thinkingMushroom management: Keeping employees uninformed and misinformed (kept in the dark and fed manure), let to stew, and finally canned.
  • Cargo Cult
  • Golden Hammer – favorite solution… even if it’s patterns themselves!
  • Flexibility?Flexible in which direction????
  • “When you make your code more flexible or sophisticated than it needs to be, you over-engineer it.  Some programmers do this because they believe they know their system’s future requirements.  They reason that it’s best to make a design more flexible or sophisticated today, so it can accommodate the needs of tomorrow.  That sounds reasonable - if you happen to be psychic.” Refactoring to Patterns p. 1
  • Changes in the course of the Mississippi over time. How fast are your requirements, needs changing?
  • Start here. Do the simplest thing that works.
  • Some things just go togetherSpaghetti and Meatballshttp://www.simplyrecipes.com/wp-content/uploads/2008/04/spaghetti-meatballs.jpg?ea6e46Peas and Carrots – Forrest Gumphttp://i145.photobucket.com/albums/r206/camille030189/peaandcarrotlg.pngHorse and Carriage – Frank Sinatrahttp://www.lowcountrycarriage.com/images/carriage-ride-wedding.jpgPeanut Butter and Chocolatehttp://blog.tropo.com/files/2010/09/pbc.jpg
  • Work for Ancestry.com
  • Refactoring to Patterns p.30 Table 3.1
  • Refactoring to Patterns p. 38 Table 4.1
  • We want to add CoinOperated Overlord as well.
  • By now you’ve likely answered it for yourself!Refactoring to Patterns p 10Make it easier to add new codeImprove the design of existing codeGain a better understanding of the codeMake coding less annoying
  • Changes in the course of the Mississippi over time. Rarely will you really know if the pattern applies up front. Don’t do a lot of work to figure it out up front, refactor to the pattern as it emerges.
  • Start here. Do the simplest thing that works.
  • What happened to minimal?Complex? If you know the pattern, simpler, but otherwise more complex. Balance!Knowledge of the patterns makes all the difference.
  • Application – System level, multi-tierDomain – concurrent or real-time systems, maybe even domains like accountingBusiness Processes – interaction between businesses, within businesses, communicate decisions You expect order confirmation emailOrganizational – human organizations (how teams are structured, interact with other teams)AJAX or UI in generalWidgets – what do you expect them to do?Visual effects – highlighting changesLinda Rising was an early champion for patterns in software and applied them to organizational changeFearless Change examples: Bring Food, Brown Bags, Evangelist, Dedicated Champion, Champion Skeptic, Just Say Thanks
  • Use it or it’s not usefulCan use the brownbag sessions in the future to present different design patterns/pattern languages or catalogsBook Reading Discussion Group – Head First Design Patterns
  • Leave of with a couple of Anti-patterns courtesy of Despair.com
  • 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.comhttp://agilecodegames.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
    5. 5. WHY SHOULD I CARE ABOUTPATTERNS?
    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
    29. 29. SO WHAT ABOUT REFACTORING?
    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)
    35. 35. ENCAPSULATE CREATION WITHFACTORYCode!
    36. 36. CONDITIONAL TO STRATEGYCode!
    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• mike@softwareontheside.com• http://blog.softwareontheside.com• http://agilecodegames.com• https://github.com/mdclement• Utah Software Craftsmanship Group– http://utahsc.org– @utahsc

    ×