SlideShare ist ein Scribd-Unternehmen logo
1 von 68
Power of Patterns:
Refactoring to (or away from)
Patterns
Mike Clement
@mdclement
mike@softwareontheside.com
http://blog.softwareontheside.com
http://agilecodegames.com
Design Patterns Defined
• Alexander’s
Architecture Design
Patterns
• Published in 1977
“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
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
WHY SHOULD I CARE ABOUT
PATTERNS?
Different
implementations, but all
recognized as “a guitar”
Kitchen
• Preparing/Cooking food
• Stove
• Refrigerator
• Sink
• Counter space
• Storage/Cabinets/Drawers
• Dishwasher
Power of a Pattern Language
• Say more with less
• Better communication
• Stay “in the design” longer
• A shared vocabulary
From Architecture to Software
• 1987 – Kent Beck and Ward Cunningham
presented at OOPSLA
• 1994 – GoF book published
GOF Pattern Template
• Pattern Name
• Classification
• Intent
• Also Known As
• Motivation
• Applicability
• Structure
• Participants
• Collaborations
• Consequences
• Implementation
• Sample Code
• Known Uses
• Related Patterns
We need some code that…
When weather/stock/employee
data is updated, all the clients are
notified of the change.
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
Patterns are not created…
They are
discovered!
LET’S DISCOVER A PATTERN!
Object oriented principles sneak in
Duck Simulator
Adding “fly()”
But RubberDuck now flies…
Override fly?
One possible solution
But what happens when we have this?
Interfaces?
Encapsulate what varies
Important OOP Principle!
Behaviors separated
The New Duck
Important OOP Principle!
Program to an interface, not an implementation
Delegate the behavior
The Strategy Pattern
Patterns are not created…
They are
discovered!
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.
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
XP Simple Design
• Passes all tests
• Clear, expressive, consistent
• No duplication
• Minimal
SO WHAT ABOUT REFACTORING?
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
• 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
“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
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)
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)
ENCAPSULATE CREATION WITH
FACTORY
Code!
CONDITIONAL TO STRATEGY
Code!
XP Simple Design
• Passes all tests
• Clear, expressive, consistent
• No duplication
• Minimal?
Beyond
• Application
• Domain-Specific
• Business Process
• Organizational
• User Interface Design
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.
Learning more…
The “Original” Refactoring book.
All your classic refactorings!
Great content and catalog of
composite refactorings to help
with patterns.
Share the Vocabulary
1) In design meetings
2) In documentation
3) In naming conventions
4) To groups of interested developers
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!
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

Weitere ähnliche Inhalte

Ähnlich wie Power of Patterns: Refactoring to (or away from) Patterns

Design Pattern Zoology
Design Pattern ZoologyDesign Pattern Zoology
Design Pattern ZoologyJosh Adell
 
Coder sans peur du changement avec la meme pas mal hexagonal architecture
Coder sans peur du changement avec la meme pas mal hexagonal architectureCoder sans peur du changement avec la meme pas mal hexagonal architecture
Coder sans peur du changement avec la meme pas mal hexagonal architectureThomas Pierrain
 
Applying Design Patterns in Practice
Applying Design Patterns in PracticeApplying Design Patterns in Practice
Applying Design Patterns in PracticeGanesh Samarthyam
 
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018Mike Harris
 
How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....Mike Harris
 
Few minutes To better Code - Refactoring
Few minutes To better Code - RefactoringFew minutes To better Code - Refactoring
Few minutes To better Code - RefactoringDiaa Al-Salehi
 
Design pattern
Design patternDesign pattern
Design patternOmar Isaid
 
Deployment is the new build
Deployment is the new buildDeployment is the new build
Deployment is the new buildAndrew Phillips
 
[DevDay 2016] Design Pattern at a glance - Speaker: Tuan Do – Scrum Master a...
 [DevDay 2016] Design Pattern at a glance - Speaker: Tuan Do – Scrum Master a... [DevDay 2016] Design Pattern at a glance - Speaker: Tuan Do – Scrum Master a...
[DevDay 2016] Design Pattern at a glance - Speaker: Tuan Do – Scrum Master a...DevDay.org
 
Applying Design Principles in Practice
Applying Design Principles in PracticeApplying Design Principles in Practice
Applying Design Principles in PracticeGanesh Samarthyam
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentationBhavin Gandhi
 
Domain Driven Design Demonstrated
Domain Driven Design Demonstrated Domain Driven Design Demonstrated
Domain Driven Design Demonstrated Alan Christensen
 
Things Every Professional Programmer Should Know
Things Every Professional Programmer Should KnowThings Every Professional Programmer Should Know
Things Every Professional Programmer Should KnowDaniel Sawano
 
Fixing Broken Windows: Dealing with Legacy Systems, Poor Quality and Gaps
Fixing Broken Windows: Dealing with Legacy Systems, Poor Quality and GapsFixing Broken Windows: Dealing with Legacy Systems, Poor Quality and Gaps
Fixing Broken Windows: Dealing with Legacy Systems, Poor Quality and GapsDmitry Vinnik
 
Art of refactoring - Code Smells and Microservices Antipatterns
Art of refactoring - Code Smells and Microservices AntipatternsArt of refactoring - Code Smells and Microservices Antipatterns
Art of refactoring - Code Smells and Microservices AntipatternsEl Mahdi Benzekri
 

Ähnlich wie Power of Patterns: Refactoring to (or away from) Patterns (20)

Design Pattern Zoology
Design Pattern ZoologyDesign Pattern Zoology
Design Pattern Zoology
 
Coder sans peur du changement avec la meme pas mal hexagonal architecture
Coder sans peur du changement avec la meme pas mal hexagonal architectureCoder sans peur du changement avec la meme pas mal hexagonal architecture
Coder sans peur du changement avec la meme pas mal hexagonal architecture
 
Applying Design Patterns in Practice
Applying Design Patterns in PracticeApplying Design Patterns in Practice
Applying Design Patterns in Practice
 
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
 
How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....
 
Few minutes To better Code - Refactoring
Few minutes To better Code - RefactoringFew minutes To better Code - Refactoring
Few minutes To better Code - Refactoring
 
Design pattern
Design patternDesign pattern
Design pattern
 
Deployment is the new build
Deployment is the new buildDeployment is the new build
Deployment is the new build
 
[DevDay 2016] Design Pattern at a glance - Speaker: Tuan Do – Scrum Master a...
 [DevDay 2016] Design Pattern at a glance - Speaker: Tuan Do – Scrum Master a... [DevDay 2016] Design Pattern at a glance - Speaker: Tuan Do – Scrum Master a...
[DevDay 2016] Design Pattern at a glance - Speaker: Tuan Do – Scrum Master a...
 
Applying Design Principles in Practice
Applying Design Principles in PracticeApplying Design Principles in Practice
Applying Design Principles in Practice
 
mehdi-refactoring.pptx
mehdi-refactoring.pptxmehdi-refactoring.pptx
mehdi-refactoring.pptx
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
 
Code Smells
Code SmellsCode Smells
Code Smells
 
Domain Driven Design Demonstrated
Domain Driven Design Demonstrated Domain Driven Design Demonstrated
Domain Driven Design Demonstrated
 
Things Every Professional Programmer Should Know
Things Every Professional Programmer Should KnowThings Every Professional Programmer Should Know
Things Every Professional Programmer Should Know
 
Fixing Broken Windows: Dealing with Legacy Systems, Poor Quality and Gaps
Fixing Broken Windows: Dealing with Legacy Systems, Poor Quality and GapsFixing Broken Windows: Dealing with Legacy Systems, Poor Quality and Gaps
Fixing Broken Windows: Dealing with Legacy Systems, Poor Quality and Gaps
 
Modernizing PowerShell Scripts
Modernizing PowerShell ScriptsModernizing PowerShell Scripts
Modernizing PowerShell Scripts
 
Design Principles
Design PrinciplesDesign Principles
Design Principles
 
Art of refactoring - Code Smells and Microservices Antipatterns
Art of refactoring - Code Smells and Microservices AntipatternsArt of refactoring - Code Smells and Microservices Antipatterns
Art of refactoring - Code Smells and Microservices Antipatterns
 
Anti-patterns
Anti-patternsAnti-patterns
Anti-patterns
 

Mehr von Mike Clement

Collaboration Principles from Mob Programming
Collaboration Principles from Mob ProgrammingCollaboration Principles from Mob Programming
Collaboration Principles from Mob ProgrammingMike Clement
 
Focus on Flow: Lean Principles in Action
Focus on Flow: Lean Principles in ActionFocus on Flow: Lean Principles in Action
Focus on Flow: Lean Principles in ActionMike Clement
 
Taming scary production code that nobody wants to touch
Taming scary production code that nobody wants to touchTaming scary production code that nobody wants to touch
Taming scary production code that nobody wants to touchMike Clement
 
Develop your sense of code smell
Develop your sense of code smellDevelop your sense of code smell
Develop your sense of code smellMike Clement
 
Maps over Backlogs: User Story Mapping to Share the Big Picture
Maps over Backlogs: User Story Mapping to Share the Big PictureMaps over Backlogs: User Story Mapping to Share the Big Picture
Maps over Backlogs: User Story Mapping to Share the Big PictureMike Clement
 
Escaping the Pitfalls of Software Product Development
Escaping the Pitfalls of Software Product DevelopmentEscaping the Pitfalls of Software Product Development
Escaping the Pitfalls of Software Product DevelopmentMike Clement
 
Mob Programming for Continuous Learning
Mob Programming for Continuous LearningMob Programming for Continuous Learning
Mob Programming for Continuous LearningMike Clement
 
Code Katas Spring 2012
Code Katas Spring 2012Code Katas Spring 2012
Code Katas Spring 2012Mike Clement
 
Linq (from the inside)
Linq (from the inside)Linq (from the inside)
Linq (from the inside)Mike Clement
 
Bowling Game Kata in C# Adapted
Bowling Game Kata in C# AdaptedBowling Game Kata in C# Adapted
Bowling Game Kata in C# AdaptedMike Clement
 
Code Katas: Practicing Your Craft
Code Katas: Practicing Your CraftCode Katas: Practicing Your Craft
Code Katas: Practicing Your CraftMike Clement
 
Software Craftsmanship
Software CraftsmanshipSoftware Craftsmanship
Software CraftsmanshipMike Clement
 

Mehr von Mike Clement (12)

Collaboration Principles from Mob Programming
Collaboration Principles from Mob ProgrammingCollaboration Principles from Mob Programming
Collaboration Principles from Mob Programming
 
Focus on Flow: Lean Principles in Action
Focus on Flow: Lean Principles in ActionFocus on Flow: Lean Principles in Action
Focus on Flow: Lean Principles in Action
 
Taming scary production code that nobody wants to touch
Taming scary production code that nobody wants to touchTaming scary production code that nobody wants to touch
Taming scary production code that nobody wants to touch
 
Develop your sense of code smell
Develop your sense of code smellDevelop your sense of code smell
Develop your sense of code smell
 
Maps over Backlogs: User Story Mapping to Share the Big Picture
Maps over Backlogs: User Story Mapping to Share the Big PictureMaps over Backlogs: User Story Mapping to Share the Big Picture
Maps over Backlogs: User Story Mapping to Share the Big Picture
 
Escaping the Pitfalls of Software Product Development
Escaping the Pitfalls of Software Product DevelopmentEscaping the Pitfalls of Software Product Development
Escaping the Pitfalls of Software Product Development
 
Mob Programming for Continuous Learning
Mob Programming for Continuous LearningMob Programming for Continuous Learning
Mob Programming for Continuous Learning
 
Code Katas Spring 2012
Code Katas Spring 2012Code Katas Spring 2012
Code Katas Spring 2012
 
Linq (from the inside)
Linq (from the inside)Linq (from the inside)
Linq (from the inside)
 
Bowling Game Kata in C# Adapted
Bowling Game Kata in C# AdaptedBowling Game Kata in C# Adapted
Bowling Game Kata in C# Adapted
 
Code Katas: Practicing Your Craft
Code Katas: Practicing Your CraftCode Katas: Practicing Your Craft
Code Katas: Practicing Your Craft
 
Software Craftsmanship
Software CraftsmanshipSoftware Craftsmanship
Software Craftsmanship
 

Kürzlich hochgeladen

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 

Kürzlich hochgeladen (20)

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
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
  • 2. Design Patterns Defined • Alexander’s Architecture Design Patterns • Published in 1977
  • 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
  • 5. WHY SHOULD I CARE ABOUT PATTERNS?
  • 7. Kitchen • Preparing/Cooking food • Stove • Refrigerator • Sink • Counter space • Storage/Cabinets/Drawers • Dishwasher
  • 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
  • 13.
  • 14. Patterns are not created… They are discovered!
  • 15. LET’S DISCOVER A PATTERN! Object oriented principles sneak in
  • 18. But RubberDuck now flies…
  • 19. Override fly? One possible solution But what happens when we have this?
  • 23. The New Duck Important OOP Principle! Program to an interface, not an implementation
  • 26. Patterns are not created… They are discovered!
  • 27.
  • 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
  • 37.
  • 38. SO WHAT ABOUT REFACTORING?
  • 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
  • 40. • 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
  • 41.
  • 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)
  • 46.
  • 48.
  • 49.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57. XP Simple Design • Passes all tests • Clear, expressive, consistent • No duplication • Minimal?
  • 58.
  • 59.
  • 60.
  • 61. Beyond • Application • Domain-Specific • Business Process • Organizational • User Interface Design
  • 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

  1. "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”
  2. 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
  3. 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
  4. 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.
  5. 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.
  6. Instead of this, I could simply say… let’s use the…
  7. 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?
  8. Those that build pattern catalogs aren’t “creators” but are discoverers. They “see” the pattern and catalog it.
  9. 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…
  10. “Classic” use of inheritance… different types of somethingCurrently we just have to display the ducks so this is okay. But…
  11. What if we add “fly()”? Here we add it to the base class and all the subclasses fly fine but…
  12. 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.
  13. Using the Java “able” interface convention.No inappropriate behaviors but now behavior code is duplicated.We traded one maintenance problem for another!
  14. Instead of having the behavior embedded in the classes, we’re going to encapsulate them elsewhere. This way they are centralized (not duplicated) and
  15. Here we are now programming the Behavior INTERFACES not the concrete implementations
  16. Those that build pattern catalogs aren’t “creators” but are discoverers. They “see” the pattern and catalog it.
  17. 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.
  18. 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.
  19. Cargo Cult
  20. Golden Hammer – favorite solution… even if it’s patterns themselves!
  21. Flexibility?Flexible in which direction????
  22. “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
  23. Changes in the course of the Mississippi over time. How fast are your requirements, needs changing?
  24. Start here. Do the simplest thing that works.
  25. 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
  26. Work for Ancestry.com
  27. Refactoring to Patterns p.30 Table 3.1
  28. Refactoring to Patterns p. 38 Table 4.1
  29. We want to add CoinOperated Overlord as well.
  30. 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
  31. 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.
  32. Start here. Do the simplest thing that works.
  33. What happened to minimal?Complex? If you know the pattern, simpler, but otherwise more complex. Balance!Knowledge of the patterns makes all the difference.
  34. 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
  35. 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
  36. Leave of with a couple of Anti-patterns courtesy of Despair.com