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.
Boost Fertility New Invention Ups Success Rates.pdf
Power of Patterns: Refactoring to (or away from) Patterns
1. Power of Patterns:
Refactoring to (or away from)
Patterns
Mike Clement
@mdclement
mike@softwareontheside.com
http://blog.softwareontheside.com
http://agilecodegames.com
3. “Each pattern describes a problem
which occurs over and over again
in our environment, and then
describes the core of the solution
to the problem, in such a way that
you can use this solution a million
times over, without ever doing it
the same way twice.”
-Christopher Alexander
4. A Pattern is a solution to a
problem in a context
• Context – recurring situation
• Problem – goal and constraints
• Solution – general design to resolve the
problem
If it only happened once,
it’s not a pattern
8. Power of a Pattern Language
• Say more with less
• Better communication
• Stay “in the design” longer
• A shared vocabulary
9. From Architecture to Software
• 1987 – Kent Beck and Ward Cunningham
presented at OOPSLA
• 1994 – GoF book published
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. We need some code that…
When weather/stock/employee
data is updated, all the clients are
notified of the change.
12. Observer Pattern
• Intent: Define a one-to-many dependency
between objects so that when one object
changes state, all its dependents are notified
and updated automatically
• Also Known As: Publish-Subscribe
28. Anti-Patterns
• Why the bad solution is unattractive
• Why in the long term it’s bad
• Suggests other patterns for a good solution
Tells you how to go from a problem
to a BAD solution.
29. 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
• Mushroom
Management
30.
31.
32.
33.
34.
35.
36. XP Simple Design
• Passes all tests
• Clear, expressive, consistent
• No duplication
• Minimal
39. 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 Different
Interfaces
• Incomplete Library Class
• Data Class
• Refused Bequest
• Comments
• Conditional Complexity
• Indecent Exposure
• Solution Sprawl
• Combinatorial Explosion
• Oddball Solution
From Refactoring and Refactoring to Patterns
42. “There is a natural
relation between
patterns and
refactoring. Patterns
are where you want to
be; refactorings are
ways to get there from
somewhere else.”
Refactoring p. 107
43.
44. Pattern To Towards Away
Adapter Extract Adapter (258),Unify Interfaces with Adapter(247) Unify Interfaces with
Adapter(247)
Builder Encapsulate Composite with Builder(96)
Collecting Parameter Move Accumulation to Collecting Parameter(313)
Command Replace Conditional Dispatcher with Command(191) Replace Conditional Dispatcher
with Command(191)
Composed Method Compose Method (123)
Composite Replace One/Many Distinctions with Composite(224), Extract
Composite(214), Replace Implicit Tree with Composite(178)
Encapsulate Composite with
Builder(96)
Creation Method Replace Constructors with Creation Methods (57)
Decorator Move Embellishment to Decorator(144) Move Embellishment to
Decorator(144)
Factory Move Creation Knowledge to Factory (68),Encapsulate Classes
with 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-Coded
Notifications with
Observer(236)
Singleton Limit Instantiation with Singleton(296) Inline Singleton(114)
State Replace State-Altering Conditionals with State(166) Replace State-Altering
Conditionals with State(166)
Strategy Replace Conditional Logic with Strategy (129) Replace Conditional Logic with
Strategy (129)
Template Method Form Template Method (205)
Visitor Move Accumulation to Visitor (320) Move Accumulation to
Visitor (320)
45. Smell Refactoring
Duplicated 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 with
Different 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)
62. Learning more…
I really like this one… some people
find it annoying. Puts Design
Patterns in the context of OOP.
Great reference. Definitive
resource. Put me to sleep the
first couple times I tried to read
it though.
63. Learning more…
The “Original” Refactoring book.
All your classic refactorings!
Great content and catalog of
composite refactorings to help
with patterns.
64. Share the Vocabulary
1) In design meetings
2) In documentation
3) In naming conventions
4) To groups of interested developers
65. Action Items!
• Play with Patterns
• Share the Vocabulary
– Study HFDP with your team
• Build a common language
• Participate in a local Software Craftsmanship
group near you!
66.
67.
68. 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
Hinweis der Redaktion
"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