SlideShare a Scribd company logo
Refactoring
Introduction
(Extract Method)
February 2016
Peter Kofler, ‘Code Cop’
@codecopkofler
www.code-cop.org
Copyright Peter Kofler, licensed under CC-BY.
Peter Kofler
• Ph.D. (Appl. Math.)
• Professional Software
Developer for 15 years
• “fanatic about code quality”
• Freelance Code Mentor
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
I help development teams with
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
●
Professionalism
●
Quality and
Productivity
●
Continuous
Improvement
Mentoring
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
●
Pair Programming
●
Programming
Workshops
●
Deliberate
Practice, e.g.
Coding Dojos
Developing Quality
Software Developers
Workshop Structure
●
Simple Design
●
Code Smells
●
Refactoring
●
Refactor manually
●
Refactoring tools
(i.e. PHPStorm)
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
Coding Dojo Mindset
●
Safe place outside
work
●
We are here to learn
●
Need to slow down
●
Focus on doing it right
●
Collaborative Game
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
Software Design
Why Software Design?
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
Software Design
Enables Change
Four Rules of Simple Design
(1) Passes the tests
(2) No duplication
(3) Reveals intention
(4) Fewer elements
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
"single letter variables who
the fuck do you think you are"
http://theprofoundprogrammer.com/post/26561881517/text-single-letter-variables-who-the-fuck-do
… that's a Code Smells
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
Code Smell
●
“a surface indication that usually
indicates a deeper problem in the
system.“
●
quick to spot
●
e.g. bad names
●
e.g. long method
●
e.g. duplication
●
does not always indicate a problem
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
List of Code Smells (Fowler)
The Bloaters
- Long Method
- Large Class
- Primitive Obsession
- Long Parameter List
- DataClumps
The Object-Orientation Abusers
- Switch Statements
- Temporary Field
- Refused Bequest
- Alternative Classes with Different
Interfaces
The Change Preventers
- Divergent Change
- Shotgun Surgery
- Parallel Inheritance Hierarchies
The Dispensables
- Lazy class
- Data class
- Duplicate Code
- Dead Code
- Speculative Generality
The Couplers
- Feature Envy
- Inappropriate Intimacy
- Message Chains
- Middle Man
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
Comment explaining
section of code
●
code grouped
into blocks
and there is
a comment
above each
few lines of
code
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
# delete previously converted BAS
File.delete PRG if File.exist? PRG
Dir['*.BAS'].each { |bas| File.delete bas }
# convert basic PRG to readable format
Dir['*.PRG'].each do |prg|
# handles only 8.3 names, rename
File.rename(prg, PRG)
puts "converting #{prg}" +
`#{CBM2ASC} #{PRG} #{BAS} b`
File.rename(BAS,
prg.sub(/.PRG$/i,'.BAS'))
end
# delete converted PRG
Dir['*.PRG'].each { |prg| File.delete prg }
Duplicate Code
●
same code found in 2 or more places
●
e.g. formatting, is user in session?
●
same expression found in 2 or more
places in the same function
●
constant value found in 2 or more places
●
e.g. items per page, default encoding
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
Method does too much
●
has more than 5 lines of code
●
If in doubt – it's too big.
●
does different things
●
e.g. DB and UI
●
has strange name or
●
has 'and' in its name
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
Code Smell Exercise
●
Group into pairs.
●
Get the printout of the Tennis code.
●
Read the code carefully.
●
Mark found code smells.
●
where? and which?
●
maybe more smells in one line
●
We found 25, how many can you find?
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
How do we fix it?
Refactoring
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
Definition
Refactoring is a technique
for restructuring
an existing body of code,
altering its internal structure
without changing
its external behaviour.
(Martin Fowler)
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
Small Transformations
●
behaviour preserving transformation
●
each transformation is small, less likely
to go wrong
●
system is fully working after each change
●
verified by working tests
●
sequence of transformations produce a
significant restructuring
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
Extract Method
● Create a new method, name by intention
● Copy extracted code from source method to new method
● Scan for local variables.
● Temporary variables local to method?
● Local-scope variables modified?
Return changes back to parent method.
● Pass local-scope variables as parameters.
● (Compile.)
● Replace extracted code with call to new method.
● (Compile and) test.
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
Introduce (Explaining) Variable
●
Declare a (final) temporary variable.
●
Set it to the result of part of the expression.
●
Replace the result part of the expression
with the value of the temp.
●
If the result part of the expression is repeated,
you can replace the repeats one at a time.
●
(Compile and) test.
●
Repeat for other parts of the expression.
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
Refactoring Exercise
●
Group into new pairs (with computer).
●
Go to the Tennis project.
●
Run ./vendor/bin/phpunit
●
Open TennisGame2.php in text editor.
●
Extract >= 2 methods (by hand).
●
Extract >= 2 local expressions (by hand).
●
Extract >= 2 constant (by hand).
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
Refactor Mercilessly
Seriously ;-)
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
●
mer·ci·less is defined as
having or showing no mercy,
cold-blooded, hard-boiled,
heartless, insensitive, hard,
pitiless, remorseless, ruthless,
slash-and-burn, soulless,
take-no-prisoners,
unfeeling, unsympathetic
●
e.g. „extract till you drop“
https://sites.google.com/site/unclebobconsultingllc/one-thing-extract-till-you-drop
Find more in the Refactoring
Book
Refactoring Questions
●
How long is a long method?
●
How do we refactor?
●
During refactoring, how
long does code not compile?
●
When to run the tests?
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
Refactoring with Tools
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
Automatic Refactorings
(PHPStorm)
● Rename
● Change Signature
● Move
● Extract Variable
● Extract Constant
● Extract Field
● Extract Method
● Extract Parameter
● Inline
● Safe Delete
● Copy/Clone
● Extract Interface
● Pull Members up
● Push Members down
JavaScript:
● Change Signature
● Extract Variable
● Extract Parameter
● (Format)
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
Demo(Refactoring in PHPStorm)
PHPStorm Exercise
●
Group into new pairs.
●
Open Gilded Rose project in PHPStorm.
●
On folder test, select Run Tests
●
Open gilded_rose.php.
●
Clean up in small steps.
●
Try to use only automatic refactorings.
●
Run tests often.
●
Commit to Git whenever tests pass.
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
What you could do
●
Make it more readable.
●
Remove duplication (extract duplicates).
●
Split into logically coherent blocks.
●
Simplify complex boolean conditions.
●
Bonus Round: Replace duplicated if-
statements with polymorphism (extract
Strategy pattern).
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
Closing Circle
●
What did you learn today?
●
What surprised you today?
●
What will you do
differently in the
future?
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
created by Peter Kofler
@codecopkofler
www.code-cop.org
with help from Aki Salmi
@rinkkasatiainen
https://about.me/rinkkasatiainen
both katas by Emily Bache
@emilybache
http://coding-is-like-cooking.info/2011/08/refactoring-kata-fun/
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
CC Images
●
puzzle https://www.flickr.com/photos/lizadaly/2944362379/
●
todos http://www.flickr.com/photos/kylesteeddesign/3724074594/
●
dojo http://www.flickr.com/photos/49715404@N00/3267627038/
●
wants you http://www.flickr.com/photos/shutter/105497713/
●
boys https://www.flickr.com/photos/andymorffew/16925347231/
●
smells http://www.flickr.com/photos/hhbw/4215183405/
●
exercise https://www.flickr.com/photos/sanchom/2963072255/
●
mercy http://www.flickr.com/photos/williac/99551756/
●
questions http://www.flickr.com/photos/seandreilinger/2326448445/
●
tools https://www.flickr.com/photos/tom-margie/5019211728/
PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY

More Related Content

What's hot (20)

PDF
Coding Dojo: Data Munging (2016)
Peter Kofler
 
PDF
JUnit Boot Camp (GeeCON 2016)
Peter Kofler
 
PDF
Designing Test Cases for the Gilded Rose Kata (2013)
Peter Kofler
 
PDF
Idiomatic R for Rosetta Code (2013)
Peter Kofler
 
PDF
Outside-in Test Driven Development - the London School of TDD
Peter Kofler
 
PDF
Refactoring the Tennis Kata v2 (2016)
Peter Kofler
 
PDF
The Brutal Refactoring Game (2013)
Peter Kofler
 
PDF
Using Automated Code Reviews to Achieve Continuous Quality (ASQF Agile Night ...
Peter Kofler
 
PDF
Brutal Coding Constraints (ITAKE 2017)
Peter Kofler
 
PDF
TDD as if You Meant It (2013)
Peter Kofler
 
PDF
Mob Programming (2016)
Peter Kofler
 
PDF
Designing Test Cases for the Gilded Rose Kata v3 (2016)
Peter Kofler
 
PDF
Software Craftsmanship Journeyman Tour (2013)
Peter Kofler
 
PDF
Coding Dojo: Asynchronous Clock-In (2016)
Peter Kofler
 
PDF
Designing Test Cases for the Gilded Rose Kata v2 (2015)
Peter Kofler
 
PDF
Coding Dojo Object Calisthenics (2016)
Peter Kofler
 
PDF
Writing Tests with the Unity Test Framework
Peter Kofler
 
PDF
Coding Dojo: Adding Tests to Legacy Code (2014)
Peter Kofler
 
PDF
Code Retreat Venice (2016)
Peter Kofler
 
PDF
Code Retreat Graz, Austria 2013
Peter Kofler
 
Coding Dojo: Data Munging (2016)
Peter Kofler
 
JUnit Boot Camp (GeeCON 2016)
Peter Kofler
 
Designing Test Cases for the Gilded Rose Kata (2013)
Peter Kofler
 
Idiomatic R for Rosetta Code (2013)
Peter Kofler
 
Outside-in Test Driven Development - the London School of TDD
Peter Kofler
 
Refactoring the Tennis Kata v2 (2016)
Peter Kofler
 
The Brutal Refactoring Game (2013)
Peter Kofler
 
Using Automated Code Reviews to Achieve Continuous Quality (ASQF Agile Night ...
Peter Kofler
 
Brutal Coding Constraints (ITAKE 2017)
Peter Kofler
 
TDD as if You Meant It (2013)
Peter Kofler
 
Mob Programming (2016)
Peter Kofler
 
Designing Test Cases for the Gilded Rose Kata v3 (2016)
Peter Kofler
 
Software Craftsmanship Journeyman Tour (2013)
Peter Kofler
 
Coding Dojo: Asynchronous Clock-In (2016)
Peter Kofler
 
Designing Test Cases for the Gilded Rose Kata v2 (2015)
Peter Kofler
 
Coding Dojo Object Calisthenics (2016)
Peter Kofler
 
Writing Tests with the Unity Test Framework
Peter Kofler
 
Coding Dojo: Adding Tests to Legacy Code (2014)
Peter Kofler
 
Code Retreat Venice (2016)
Peter Kofler
 
Code Retreat Graz, Austria 2013
Peter Kofler
 

Viewers also liked (17)

PDF
Digital Optimisation Infographic - Forrester Report
Omer Celep
 
PPTX
My favorite (mostly) free social media tools
Jay Dolan
 
PPTX
Lugar de encuentro y aprendizaje, una renovación de los parques infantiles
BertaAparicio14
 
PPT
Estrategias de divulgación y posicionamiento de marca
Carlos Alberto Villamil Sanchez
 
PDF
Portfolio_Dino
Dino Dermedgoglou
 
PDF
Build competitive edge through differentiated customer experience
Intense Technologies Limited
 
PDF
Tratao de Zimmermann
ElenaCanizares
 
PPTX
Oprah ( halima ahmed)
7aloom
 
PPTX
OPRAH WINFREY
shilu37
 
DOCX
Practica de windows
Norman Lucero
 
PPTX
Mandarin Phonetic
Devy Riani
 
PDF
Tax Problems with Big Box Stores
fsbrlaw
 
PPTX
Alien museo 2.odp
Marta Martín
 
PDF
Trabajo Cooperativo sobre Animales invertebrados
Alquimista Aula
 
PDF
Sap plant-maintenance-pm-business-blueprint-bbp2
gabrielsyst
 
PPT
La famille Simpson
smt786
 
PDF
Clean coding-practices
John Ferguson Smart Limited
 
Digital Optimisation Infographic - Forrester Report
Omer Celep
 
My favorite (mostly) free social media tools
Jay Dolan
 
Lugar de encuentro y aprendizaje, una renovación de los parques infantiles
BertaAparicio14
 
Estrategias de divulgación y posicionamiento de marca
Carlos Alberto Villamil Sanchez
 
Portfolio_Dino
Dino Dermedgoglou
 
Build competitive edge through differentiated customer experience
Intense Technologies Limited
 
Tratao de Zimmermann
ElenaCanizares
 
Oprah ( halima ahmed)
7aloom
 
OPRAH WINFREY
shilu37
 
Practica de windows
Norman Lucero
 
Mandarin Phonetic
Devy Riani
 
Tax Problems with Big Box Stores
fsbrlaw
 
Alien museo 2.odp
Marta Martín
 
Trabajo Cooperativo sobre Animales invertebrados
Alquimista Aula
 
Sap plant-maintenance-pm-business-blueprint-bbp2
gabrielsyst
 
La famille Simpson
smt786
 
Clean coding-practices
John Ferguson Smart Limited
 
Ad

Similar to Extract Method Refactoring Workshop (2016) (20)

PDF
Refactoring
Herez Moise Kattan
 
PDF
Refactoring, Therapeutic Attitude to Programming.
Amin Shahnazari
 
PPT
Code Review
Ravi Raj
 
PPTX
Refactoring, 2nd Edition
jexp
 
PPTX
Agile korea 2013 유석문
Sangcheol Hwang
 
PPTX
Code smell overview
Pham Manh Lan
 
PDF
Refactoring 2TheMax (con ReSharper)
DotNetMarche
 
PDF
Code refactoring workshop (in Javascript)
Ilias Bartolini
 
PPT
Developing a Culture of Quality Code (Midwest PHP 2020)
Scott Keck-Warren
 
PDF
Does your code spark joy? Refactoring techniques to make your life easier.
Juciellen Cabrera
 
PPTX
Code smells and Other Malodorous Software Odors
Clint Edmonson
 
PPT
Code Refactoring
Charlie Berg
 
PDF
Refactoring Long Methods
Marc Rendl Ignacio
 
PPTX
Refactoring workshop
Itzik Saban
 
PPT
Revisiting refactoring
Nick Harrison
 
PPT
Revisiting Refactoring
Nick Harrison
 
PDF
Voxxed days 2015-hakansaglam-codereview
Hakan Saglam
 
PDF
Code reviews
Raúl Araya Tauler
 
PPTX
Ruby code smells
Rodrigo Urubatan
 
PPTX
Code Reviews
phildenoncourt
 
Refactoring
Herez Moise Kattan
 
Refactoring, Therapeutic Attitude to Programming.
Amin Shahnazari
 
Code Review
Ravi Raj
 
Refactoring, 2nd Edition
jexp
 
Agile korea 2013 유석문
Sangcheol Hwang
 
Code smell overview
Pham Manh Lan
 
Refactoring 2TheMax (con ReSharper)
DotNetMarche
 
Code refactoring workshop (in Javascript)
Ilias Bartolini
 
Developing a Culture of Quality Code (Midwest PHP 2020)
Scott Keck-Warren
 
Does your code spark joy? Refactoring techniques to make your life easier.
Juciellen Cabrera
 
Code smells and Other Malodorous Software Odors
Clint Edmonson
 
Code Refactoring
Charlie Berg
 
Refactoring Long Methods
Marc Rendl Ignacio
 
Refactoring workshop
Itzik Saban
 
Revisiting refactoring
Nick Harrison
 
Revisiting Refactoring
Nick Harrison
 
Voxxed days 2015-hakansaglam-codereview
Hakan Saglam
 
Code reviews
Raúl Araya Tauler
 
Ruby code smells
Rodrigo Urubatan
 
Code Reviews
phildenoncourt
 
Ad

More from Peter Kofler (9)

PDF
Pragmatic Introduction to Python Unit Testing (PyDays 2018)
Peter Kofler
 
PDF
GDCR15 in Las Palmas, Gran Canaria
Peter Kofler
 
PDF
Pair Programming (2015)
Peter Kofler
 
PDF
Pragmatic Introduction to PHP Unit Testing (2015)
Peter Kofler
 
PDF
Coding Dojo: Fun with Tic-Tac-Toe (2014)
Peter Kofler
 
PDF
Coding Dojo for Testers/Testing Dojo: Designing Test Cases with FitNesse (2014)
Peter Kofler
 
PDF
Code Refactoring - Live Coding Demo (JavaDay 2014)
Peter Kofler
 
PDF
Coding Dojo: Bank OCR (2014)
Peter Kofler
 
PDF
Prime Factors Code Kata - Practicing TDD (2014)
Peter Kofler
 
Pragmatic Introduction to Python Unit Testing (PyDays 2018)
Peter Kofler
 
GDCR15 in Las Palmas, Gran Canaria
Peter Kofler
 
Pair Programming (2015)
Peter Kofler
 
Pragmatic Introduction to PHP Unit Testing (2015)
Peter Kofler
 
Coding Dojo: Fun with Tic-Tac-Toe (2014)
Peter Kofler
 
Coding Dojo for Testers/Testing Dojo: Designing Test Cases with FitNesse (2014)
Peter Kofler
 
Code Refactoring - Live Coding Demo (JavaDay 2014)
Peter Kofler
 
Coding Dojo: Bank OCR (2014)
Peter Kofler
 
Prime Factors Code Kata - Practicing TDD (2014)
Peter Kofler
 

Recently uploaded (20)

PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
July Patch Tuesday
Ivanti
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
July Patch Tuesday
Ivanti
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 

Extract Method Refactoring Workshop (2016)

  • 1. Refactoring Introduction (Extract Method) February 2016 Peter Kofler, ‘Code Cop’ @codecopkofler www.code-cop.org Copyright Peter Kofler, licensed under CC-BY.
  • 2. Peter Kofler • Ph.D. (Appl. Math.) • Professional Software Developer for 15 years • “fanatic about code quality” • Freelance Code Mentor PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
  • 3. I help development teams with PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY ● Professionalism ● Quality and Productivity ● Continuous Improvement
  • 4. Mentoring PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY ● Pair Programming ● Programming Workshops ● Deliberate Practice, e.g. Coding Dojos
  • 6. Workshop Structure ● Simple Design ● Code Smells ● Refactoring ● Refactor manually ● Refactoring tools (i.e. PHPStorm) PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
  • 7. Coding Dojo Mindset ● Safe place outside work ● We are here to learn ● Need to slow down ● Focus on doing it right ● Collaborative Game PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
  • 9. Why Software Design? PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
  • 11. Four Rules of Simple Design (1) Passes the tests (2) No duplication (3) Reveals intention (4) Fewer elements PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
  • 12. "single letter variables who the fuck do you think you are" http://theprofoundprogrammer.com/post/26561881517/text-single-letter-variables-who-the-fuck-do
  • 13. … that's a Code Smells PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
  • 14. Code Smell ● “a surface indication that usually indicates a deeper problem in the system.“ ● quick to spot ● e.g. bad names ● e.g. long method ● e.g. duplication ● does not always indicate a problem PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
  • 15. List of Code Smells (Fowler) The Bloaters - Long Method - Large Class - Primitive Obsession - Long Parameter List - DataClumps The Object-Orientation Abusers - Switch Statements - Temporary Field - Refused Bequest - Alternative Classes with Different Interfaces The Change Preventers - Divergent Change - Shotgun Surgery - Parallel Inheritance Hierarchies The Dispensables - Lazy class - Data class - Duplicate Code - Dead Code - Speculative Generality The Couplers - Feature Envy - Inappropriate Intimacy - Message Chains - Middle Man PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
  • 16. Comment explaining section of code ● code grouped into blocks and there is a comment above each few lines of code PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY # delete previously converted BAS File.delete PRG if File.exist? PRG Dir['*.BAS'].each { |bas| File.delete bas } # convert basic PRG to readable format Dir['*.PRG'].each do |prg| # handles only 8.3 names, rename File.rename(prg, PRG) puts "converting #{prg}" + `#{CBM2ASC} #{PRG} #{BAS} b` File.rename(BAS, prg.sub(/.PRG$/i,'.BAS')) end # delete converted PRG Dir['*.PRG'].each { |prg| File.delete prg }
  • 17. Duplicate Code ● same code found in 2 or more places ● e.g. formatting, is user in session? ● same expression found in 2 or more places in the same function ● constant value found in 2 or more places ● e.g. items per page, default encoding PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
  • 18. Method does too much ● has more than 5 lines of code ● If in doubt – it's too big. ● does different things ● e.g. DB and UI ● has strange name or ● has 'and' in its name PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
  • 19. Code Smell Exercise ● Group into pairs. ● Get the printout of the Tennis code. ● Read the code carefully. ● Mark found code smells. ● where? and which? ● maybe more smells in one line ● We found 25, how many can you find? PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
  • 20. How do we fix it?
  • 21. Refactoring PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
  • 22. Definition Refactoring is a technique for restructuring an existing body of code, altering its internal structure without changing its external behaviour. (Martin Fowler) PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
  • 23. Small Transformations ● behaviour preserving transformation ● each transformation is small, less likely to go wrong ● system is fully working after each change ● verified by working tests ● sequence of transformations produce a significant restructuring PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
  • 24. Extract Method ● Create a new method, name by intention ● Copy extracted code from source method to new method ● Scan for local variables. ● Temporary variables local to method? ● Local-scope variables modified? Return changes back to parent method. ● Pass local-scope variables as parameters. ● (Compile.) ● Replace extracted code with call to new method. ● (Compile and) test. PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
  • 25. Introduce (Explaining) Variable ● Declare a (final) temporary variable. ● Set it to the result of part of the expression. ● Replace the result part of the expression with the value of the temp. ● If the result part of the expression is repeated, you can replace the repeats one at a time. ● (Compile and) test. ● Repeat for other parts of the expression. PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
  • 26. Refactoring Exercise ● Group into new pairs (with computer). ● Go to the Tennis project. ● Run ./vendor/bin/phpunit ● Open TennisGame2.php in text editor. ● Extract >= 2 methods (by hand). ● Extract >= 2 local expressions (by hand). ● Extract >= 2 constant (by hand). PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
  • 28. Seriously ;-) PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY ● mer·ci·less is defined as having or showing no mercy, cold-blooded, hard-boiled, heartless, insensitive, hard, pitiless, remorseless, ruthless, slash-and-burn, soulless, take-no-prisoners, unfeeling, unsympathetic ● e.g. „extract till you drop“ https://sites.google.com/site/unclebobconsultingllc/one-thing-extract-till-you-drop
  • 29. Find more in the Refactoring Book
  • 30. Refactoring Questions ● How long is a long method? ● How do we refactor? ● During refactoring, how long does code not compile? ● When to run the tests? PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
  • 31. Refactoring with Tools PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
  • 32. Automatic Refactorings (PHPStorm) ● Rename ● Change Signature ● Move ● Extract Variable ● Extract Constant ● Extract Field ● Extract Method ● Extract Parameter ● Inline ● Safe Delete ● Copy/Clone ● Extract Interface ● Pull Members up ● Push Members down JavaScript: ● Change Signature ● Extract Variable ● Extract Parameter ● (Format) PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
  • 34. PHPStorm Exercise ● Group into new pairs. ● Open Gilded Rose project in PHPStorm. ● On folder test, select Run Tests ● Open gilded_rose.php. ● Clean up in small steps. ● Try to use only automatic refactorings. ● Run tests often. ● Commit to Git whenever tests pass. PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
  • 35. What you could do ● Make it more readable. ● Remove duplication (extract duplicates). ● Split into logically coherent blocks. ● Simplify complex boolean conditions. ● Bonus Round: Replace duplicated if- statements with polymorphism (extract Strategy pattern). PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
  • 36. Closing Circle ● What did you learn today? ● What surprised you today? ● What will you do differently in the future? PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
  • 37. created by Peter Kofler @codecopkofler www.code-cop.org with help from Aki Salmi @rinkkasatiainen https://about.me/rinkkasatiainen both katas by Emily Bache @emilybache http://coding-is-like-cooking.info/2011/08/refactoring-kata-fun/ PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY
  • 38. CC Images ● puzzle https://www.flickr.com/photos/lizadaly/2944362379/ ● todos http://www.flickr.com/photos/kylesteeddesign/3724074594/ ● dojo http://www.flickr.com/photos/49715404@N00/3267627038/ ● wants you http://www.flickr.com/photos/shutter/105497713/ ● boys https://www.flickr.com/photos/andymorffew/16925347231/ ● smells http://www.flickr.com/photos/hhbw/4215183405/ ● exercise https://www.flickr.com/photos/sanchom/2963072255/ ● mercy http://www.flickr.com/photos/williac/99551756/ ● questions http://www.flickr.com/photos/seandreilinger/2326448445/ ● tools https://www.flickr.com/photos/tom-margie/5019211728/ PETER KOFLER, CODE-COP.ORG FANATIC ABOUT CODE QUALITY