SlideShare a Scribd company logo
Refactoring 101
By:
Adam Culp
Twitter: @adamculp
https://joind.in/14927
2
Refactoring 101
●
About me
– PHP 5.3 Certified
– Consultant at Zend Technologies
– Organizer SoFloPHP (South Florida)
– Organized SunshinePHP (Miami)
– Long distance (ultra) runner
– Judo Black Belt Instructor
3
Refactoring 101
●
Fan of iteration
– Pretty much everything requires iteration to do well:
●
Long distance running
●
Judo
●
Development
●
Evading project managers
●
Refactoring!
4
Refactoring 101
● About talk
– Based on “Refactoring; Improving The Design of Existing Code” book, by
Martin Fowler.
– https://github.com/adamculp/refactoring101 – for PHP code samples
6
Refactoring 101
● What is “refactoring”?
– “...process of changing a computer program's source code without
modifying its external functional behavior...” en.wikipedia.org/wiki/Refactoring
– Should not add functionality
– Simplify code
– Improve code readability
7
Refactoring 101
● Two hats
– Adding Functionality Hat
– Refactoring Hat
– We add functionality, then refactor, then add more functionality ...
8
Refactoring 101
● Then optimize
– Do not optimize while refactoring
– Separate step
– Refactoring is NOT optimizing
9
Refactoring 101
● Why refactor?
– Prevent decay
– Preserve or fix design
– Reduce duplication
– Improve maintainability
– Helps us code faster
– Locate bugs
– Code smells
10
Refactoring 101
●
Code “smells”
– What are “smells”?
●
Indications of spoiled code nearby
●
Not conclusive
●
The “smell” is not bad
11
Refactoring 101
● Code “smells”
– “Smells” hinting a refactor may be needed:
●
Duplicate Code (rule of 3)
●
Long Methods
●
Large Class
●
Long Parameter (argument) List
● Divergent Change – cascade change to accommodate another
●
Shotgun Surgery – change ripples as bugs
●
Feature Envy – method uses parts from other class
●
Switch Statements – sacrifice polymorphism
12
Refactoring 101
● Code “smells”
– Cont'd:
●
Lazy Class – class not doing much
●
Speculative Generality – something built for possible future
●
Temporary Field/Variable
●
Message Chains – object asking object asking object
● Middle Man – directors in place but serve no real purpose
●
Inappropriate Intimacy – classes share private parts
●
Data Class – getters and setters, but nothing else
●
Comments – where comments cover bad code
14
Refactoring 101
● Tools to highlight smells
– PHPqatools.org
●
PHPUnit
●
PHPLoc
●
PHP_Codesniffer
●
PHP_Depend
● PHP Copy/Paste Detector
●
PHP Mess Detector
●
PHP Dead Code Detector
15
Refactoring 101
● Realtime profiling
– Zend Z-Ray
16
Refactoring 101
● Rewrite vs Refactor
– Rewrite = perceived easy road
– Refactor = best teacher
– Business arguments
● Budget
●
Time
●
Retain business logic
17
Refactoring 101
● When to rewrite
– Want a new app
● Not just better coded current app
– Business logic change
– Target market change
– Framework integration or change
18
Refactoring 101
● When to refactor?
– No “special” time
– Short bursts
– Refactor to gain something
– Prior to adding functionality
– When fixing a bug
– During code review
19
Refactoring 101
● What do I tell my manager? (justification)
– Tech savvy manager = not be hard to explain the benefits.
– Quality centric manager = stress quality aspects.
●
Introduce as a review process.
●
Many resources on Google.
– Schedule driven manager = Don't tell (controversial?).
●
Find a way to work it in.
●
Overall it saves time, but some will never “see” it.
20
Refactoring 101
● First steps
– Use source control (Git, SVN, etc.)
●
Records steps, provides rollback
● Auditable
– GET IT WORKING
●
Do NOT refactor broken
– Create consistent data
– Create tests
21
Refactoring 101
● Tests and refactoring
– Basic refactor steps
●
Ensure tests pass
●
Plan refactor
●
Implement
●
Ensure tests still pass
– Updating tests if needed
– Add more tests to cover newly discovered items
●
Repeat!
22
Refactoring 101
Let's look at the code!
● Example
– Lets look at a code example.
– Tips and descriptions during steps.
– Our Task:
● Video Rental Company has asked for an HTML representation of their
customer statement to be created.
23
Refactoring 101
24
Refactoring 101
25
Refactoring 101
26
Refactoring 101
27
Refactoring 101
28
Refactoring 101
29
Refactoring 101
●
Code summary: What did we see?
– Method statement()→
●
Too long
●
Not reusable for HTML version
●
Switch sacrificing polymorphism
●
Determining class/type
●
Calculating rental price, frequent renter points, grant total
30
Refactoring 101
●
Additional notes
– Cannot change how movies are classified.
– Customers always changes, not easy in current state.
●
Movie classification
●
Frequent renter points
●
Rental days per type
●
Price calculation
31
Refactoring 101
●
Objective:
– Clean up statement().
●
Shorten
– Extract code to encapsulate functionality
– Extract business logic to keep DRY
32
Refactoring 101
● TEST ! ! !
33
Refactoring 101
● Extract method
– Moves a functionality to it's own method.
●
Encapsulate calculation of each rental.
●
Shorten statement() method.
34
Refactoring 101
● Extract method cont'd.
– We now have a new method amountFor().
35
Refactoring 101
● Rename variables
– Renaming $each to $rental
– Improves readability.
– Relate intent.
36
Refactoring 101
● Renaming variables, cont'd.
– Renamed $each to $rental, and also changed $thisAmount to become
$result for clarity.
37
Refactoring 101
● Rename method
– Rename amountFor() to getCharge().
– Self documenting.
38
Refactoring 101
● Move method
– Move getCharge() from Customer to Rental.
●
Relies on Rental data.
– Already have Rental object, no need to pass $rental.
39
Refactoring 101
● Move method cont'd
– Now calls getDaysRented() directly.
– Returns charge of Rental, as it should.
●
Building rental charge in customer was misplaced.
40
Refactoring 101
● Replace temp with query
– Remove temporary variable and call Rental->getCharge() direct.
●
Less future maintenance.
●
Makes code clearer.
41
Refactoring 101
● Extract method
– $frequentRenterPoints calculation extracted to
getFrequentRenterPoints(), and move it in the Rental class.
42
Refactoring 101
● Replace temp with query
– Encapsulate logic and generation of grand total.
– Promotes DRY.
– Remove $totalAmount temporary variable.
43
Refactoring 101
●
Replace temp with query
– Encapsulate logic and generation of frequent renter points.
– Promotes DRY.
– Remove $frequentRentalPoints temporary variable.
44
Refactoring 101
● Create HTML statement
– Create HTML version.
– Rename original as text version.
45
Refactoring 101
● Execution
– Can call either Text or HTML versions.
46
Refactoring 101
● Recap
– Most refactoring reduces code
●
More self-documenting
●
More flexibility
● More testable
– 3 loops (getFrequentRenterPoints, getTotalCharge, and statement)
●
Isolates calculations
●
Enabled multiple statements (text/html)
– Optimizing and refactoring = different
●
Refactor, then optimize
– Future = separation of concerns
59
Refactoring 101
●
Conclusion
– Do not refactor a broken application
– Always have tests in place prior to refactor
●
Unit tests or
●
Functional tests or
●
Manual tests
– Leave code cleaner than you got it
– Try NOT to rewrite
– Learn to “smell” problems
– Love iteration!
● Thank you!
– Code: https://github.com/adamculp/refactoring101
– Please rate at: https://joind.in/14927
Adam Culp
http://www.geekyboy.com
http://RunGeekRadio.com
Twitter @adamculp

More Related Content

ODP
Refactoring Techniques
PPTX
Code refactoring
PDF
Refactoring
PPTX
Refactoring and code smells
PDF
Code Refactoring
PPTX
Tech talks#6: Code Refactoring
PPT
Refactoring Tips by Martin Fowler
PDF
Refactoring
Refactoring Techniques
Code refactoring
Refactoring
Refactoring and code smells
Code Refactoring
Tech talks#6: Code Refactoring
Refactoring Tips by Martin Fowler
Refactoring

What's hot (20)

PPTX
Code smells and remedies
PDF
Refactoring
PPTX
Code smell overview
PDF
Code Smells and Its type (With Example)
PPTX
PPTX
Software maintenance
PPTX
The Art of Debugging.pptx
ODP
Refactoring: Improving the design of existing code
PPTX
Software Craftsmanship - Code Smells - Change Preventers
PDF
OOP Assignment 03.pdf
PPTX
software maintenance
PDF
Software requirements
PDF
An Introduction to Redux
PDF
Working Effectively with Legacy Code
PPTX
Cost of software quality ( software quality assurance )
PPTX
Code Smell, Software Engineering
PPTX
Software Evolution
PDF
Remote Method Invocation in JAVA
PPT
Lecture6
Code smells and remedies
Refactoring
Code smell overview
Code Smells and Its type (With Example)
Software maintenance
The Art of Debugging.pptx
Refactoring: Improving the design of existing code
Software Craftsmanship - Code Smells - Change Preventers
OOP Assignment 03.pdf
software maintenance
Software requirements
An Introduction to Redux
Working Effectively with Legacy Code
Cost of software quality ( software quality assurance )
Code Smell, Software Engineering
Software Evolution
Remote Method Invocation in JAVA
Lecture6
Ad

Viewers also liked (9)

PPT
Code Refactoring
PDF
Design patterns
PDF
Introduction to Design Pattern
PDF
Refactoring - An Introduction
PDF
The Decorator Pattern
PDF
Design Patterns這樣學就會了:入門班 Day1 教材
PDF
Design Patterns Illustrated
PPTX
Design Patterns - 01 Introduction and Decorator Pattern
PPT
Design Patterns
Code Refactoring
Design patterns
Introduction to Design Pattern
Refactoring - An Introduction
The Decorator Pattern
Design Patterns這樣學就會了:入門班 Day1 教材
Design Patterns Illustrated
Design Patterns - 01 Introduction and Decorator Pattern
Design Patterns
Ad

Similar to Refactoring 101 (20)

PDF
Refactoring Legacy Code
PPTX
Prashant technical practices-tdd for xebia event
PDF
Workshop: Refactoring Legacy PHP: The Complete Guide
PPTX
Converting Your Legacy Data to S1000D
PPTX
Peephole optimization techniques in compiler design
PDF
The Power Of Refactoring (php|tek 09)
PPTX
They why behind php frameworks
PDF
Zend expressive workshop
ODP
2014 11 20 Drupal 7 -> 8 test migratie
PDF
Refactoring PHP
PDF
Standard Coding, OOP Techniques and Code Reuse
PDF
An Introduction to Scrum: presented at PyTexas 2012
PPTX
Kylin Engineering Principles
PDF
Keeping code clean
PPTX
Angular Ivy- An Overview
ODP
Behat Workshop at WeLovePHP
PPT
2. Life Cycle Models for Software Engineeting
PDF
04 Functional Programming in Python
PPTX
Optimizing performance
PDF
Clean application development (talk)
Refactoring Legacy Code
Prashant technical practices-tdd for xebia event
Workshop: Refactoring Legacy PHP: The Complete Guide
Converting Your Legacy Data to S1000D
Peephole optimization techniques in compiler design
The Power Of Refactoring (php|tek 09)
They why behind php frameworks
Zend expressive workshop
2014 11 20 Drupal 7 -> 8 test migratie
Refactoring PHP
Standard Coding, OOP Techniques and Code Reuse
An Introduction to Scrum: presented at PyTexas 2012
Kylin Engineering Principles
Keeping code clean
Angular Ivy- An Overview
Behat Workshop at WeLovePHP
2. Life Cycle Models for Software Engineeting
04 Functional Programming in Python
Optimizing performance
Clean application development (talk)

More from Adam Culp (20)

PDF
Hypermedia
PDF
Putting legacy to REST with middleware
PDF
php-1701-a
PDF
Release your refactoring superpower
PDF
Managing Technical Debt
PDF
Developing PHP Applications Faster
PDF
Containing Quality
PDF
Debugging elephpants
PDF
Expressive Microservice Framework Blastoff
PDF
Foundations of Zend Framework
PDF
Accidental professional
PDF
Build great products
PDF
Does Your Code Measure Up?
PDF
Practical PHP Deployment with Jenkins
PDF
Virtualizing Development
PDF
Deprecated: Foundations of Zend Framework 2
PDF
Clean application development tutorial
PDF
Essential git for developers
PDF
Vagrant for Virtualized Development
PDF
Using an API
Hypermedia
Putting legacy to REST with middleware
php-1701-a
Release your refactoring superpower
Managing Technical Debt
Developing PHP Applications Faster
Containing Quality
Debugging elephpants
Expressive Microservice Framework Blastoff
Foundations of Zend Framework
Accidental professional
Build great products
Does Your Code Measure Up?
Practical PHP Deployment with Jenkins
Virtualizing Development
Deprecated: Foundations of Zend Framework 2
Clean application development tutorial
Essential git for developers
Vagrant for Virtualized Development
Using an API

Recently uploaded (20)

PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
A Presentation on Artificial Intelligence
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Modernizing your data center with Dell and AMD
PDF
Electronic commerce courselecture one. Pdf
PDF
Machine learning based COVID-19 study performance prediction
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPT
Teaching material agriculture food technology
PDF
Encapsulation theory and applications.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Review of recent advances in non-invasive hemoglobin estimation
Per capita expenditure prediction using model stacking based on satellite ima...
A Presentation on Artificial Intelligence
Empathic Computing: Creating Shared Understanding
Digital-Transformation-Roadmap-for-Companies.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
Modernizing your data center with Dell and AMD
Electronic commerce courselecture one. Pdf
Machine learning based COVID-19 study performance prediction
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Teaching material agriculture food technology
Encapsulation theory and applications.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
NewMind AI Weekly Chronicles - August'25 Week I
NewMind AI Monthly Chronicles - July 2025
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Chapter 3 Spatial Domain Image Processing.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf

Refactoring 101

  • 1. Refactoring 101 By: Adam Culp Twitter: @adamculp https://joind.in/14927
  • 2. 2 Refactoring 101 ● About me – PHP 5.3 Certified – Consultant at Zend Technologies – Organizer SoFloPHP (South Florida) – Organized SunshinePHP (Miami) – Long distance (ultra) runner – Judo Black Belt Instructor
  • 3. 3 Refactoring 101 ● Fan of iteration – Pretty much everything requires iteration to do well: ● Long distance running ● Judo ● Development ● Evading project managers ● Refactoring!
  • 4. 4 Refactoring 101 ● About talk – Based on “Refactoring; Improving The Design of Existing Code” book, by Martin Fowler. – https://github.com/adamculp/refactoring101 – for PHP code samples
  • 5. 6 Refactoring 101 ● What is “refactoring”? – “...process of changing a computer program's source code without modifying its external functional behavior...” en.wikipedia.org/wiki/Refactoring – Should not add functionality – Simplify code – Improve code readability
  • 6. 7 Refactoring 101 ● Two hats – Adding Functionality Hat – Refactoring Hat – We add functionality, then refactor, then add more functionality ...
  • 7. 8 Refactoring 101 ● Then optimize – Do not optimize while refactoring – Separate step – Refactoring is NOT optimizing
  • 8. 9 Refactoring 101 ● Why refactor? – Prevent decay – Preserve or fix design – Reduce duplication – Improve maintainability – Helps us code faster – Locate bugs – Code smells
  • 9. 10 Refactoring 101 ● Code “smells” – What are “smells”? ● Indications of spoiled code nearby ● Not conclusive ● The “smell” is not bad
  • 10. 11 Refactoring 101 ● Code “smells” – “Smells” hinting a refactor may be needed: ● Duplicate Code (rule of 3) ● Long Methods ● Large Class ● Long Parameter (argument) List ● Divergent Change – cascade change to accommodate another ● Shotgun Surgery – change ripples as bugs ● Feature Envy – method uses parts from other class ● Switch Statements – sacrifice polymorphism
  • 11. 12 Refactoring 101 ● Code “smells” – Cont'd: ● Lazy Class – class not doing much ● Speculative Generality – something built for possible future ● Temporary Field/Variable ● Message Chains – object asking object asking object ● Middle Man – directors in place but serve no real purpose ● Inappropriate Intimacy – classes share private parts ● Data Class – getters and setters, but nothing else ● Comments – where comments cover bad code
  • 12. 14 Refactoring 101 ● Tools to highlight smells – PHPqatools.org ● PHPUnit ● PHPLoc ● PHP_Codesniffer ● PHP_Depend ● PHP Copy/Paste Detector ● PHP Mess Detector ● PHP Dead Code Detector
  • 13. 15 Refactoring 101 ● Realtime profiling – Zend Z-Ray
  • 14. 16 Refactoring 101 ● Rewrite vs Refactor – Rewrite = perceived easy road – Refactor = best teacher – Business arguments ● Budget ● Time ● Retain business logic
  • 15. 17 Refactoring 101 ● When to rewrite – Want a new app ● Not just better coded current app – Business logic change – Target market change – Framework integration or change
  • 16. 18 Refactoring 101 ● When to refactor? – No “special” time – Short bursts – Refactor to gain something – Prior to adding functionality – When fixing a bug – During code review
  • 17. 19 Refactoring 101 ● What do I tell my manager? (justification) – Tech savvy manager = not be hard to explain the benefits. – Quality centric manager = stress quality aspects. ● Introduce as a review process. ● Many resources on Google. – Schedule driven manager = Don't tell (controversial?). ● Find a way to work it in. ● Overall it saves time, but some will never “see” it.
  • 18. 20 Refactoring 101 ● First steps – Use source control (Git, SVN, etc.) ● Records steps, provides rollback ● Auditable – GET IT WORKING ● Do NOT refactor broken – Create consistent data – Create tests
  • 19. 21 Refactoring 101 ● Tests and refactoring – Basic refactor steps ● Ensure tests pass ● Plan refactor ● Implement ● Ensure tests still pass – Updating tests if needed – Add more tests to cover newly discovered items ● Repeat!
  • 20. 22 Refactoring 101 Let's look at the code! ● Example – Lets look at a code example. – Tips and descriptions during steps. – Our Task: ● Video Rental Company has asked for an HTML representation of their customer statement to be created.
  • 27. 29 Refactoring 101 ● Code summary: What did we see? – Method statement()→ ● Too long ● Not reusable for HTML version ● Switch sacrificing polymorphism ● Determining class/type ● Calculating rental price, frequent renter points, grant total
  • 28. 30 Refactoring 101 ● Additional notes – Cannot change how movies are classified. – Customers always changes, not easy in current state. ● Movie classification ● Frequent renter points ● Rental days per type ● Price calculation
  • 29. 31 Refactoring 101 ● Objective: – Clean up statement(). ● Shorten – Extract code to encapsulate functionality – Extract business logic to keep DRY
  • 31. 33 Refactoring 101 ● Extract method – Moves a functionality to it's own method. ● Encapsulate calculation of each rental. ● Shorten statement() method.
  • 32. 34 Refactoring 101 ● Extract method cont'd. – We now have a new method amountFor().
  • 33. 35 Refactoring 101 ● Rename variables – Renaming $each to $rental – Improves readability. – Relate intent.
  • 34. 36 Refactoring 101 ● Renaming variables, cont'd. – Renamed $each to $rental, and also changed $thisAmount to become $result for clarity.
  • 35. 37 Refactoring 101 ● Rename method – Rename amountFor() to getCharge(). – Self documenting.
  • 36. 38 Refactoring 101 ● Move method – Move getCharge() from Customer to Rental. ● Relies on Rental data. – Already have Rental object, no need to pass $rental.
  • 37. 39 Refactoring 101 ● Move method cont'd – Now calls getDaysRented() directly. – Returns charge of Rental, as it should. ● Building rental charge in customer was misplaced.
  • 38. 40 Refactoring 101 ● Replace temp with query – Remove temporary variable and call Rental->getCharge() direct. ● Less future maintenance. ● Makes code clearer.
  • 39. 41 Refactoring 101 ● Extract method – $frequentRenterPoints calculation extracted to getFrequentRenterPoints(), and move it in the Rental class.
  • 40. 42 Refactoring 101 ● Replace temp with query – Encapsulate logic and generation of grand total. – Promotes DRY. – Remove $totalAmount temporary variable.
  • 41. 43 Refactoring 101 ● Replace temp with query – Encapsulate logic and generation of frequent renter points. – Promotes DRY. – Remove $frequentRentalPoints temporary variable.
  • 42. 44 Refactoring 101 ● Create HTML statement – Create HTML version. – Rename original as text version.
  • 43. 45 Refactoring 101 ● Execution – Can call either Text or HTML versions.
  • 44. 46 Refactoring 101 ● Recap – Most refactoring reduces code ● More self-documenting ● More flexibility ● More testable – 3 loops (getFrequentRenterPoints, getTotalCharge, and statement) ● Isolates calculations ● Enabled multiple statements (text/html) – Optimizing and refactoring = different ● Refactor, then optimize – Future = separation of concerns
  • 45. 59 Refactoring 101 ● Conclusion – Do not refactor a broken application – Always have tests in place prior to refactor ● Unit tests or ● Functional tests or ● Manual tests – Leave code cleaner than you got it – Try NOT to rewrite – Learn to “smell” problems – Love iteration!
  • 46. ● Thank you! – Code: https://github.com/adamculp/refactoring101 – Please rate at: https://joind.in/14927 Adam Culp http://www.geekyboy.com http://RunGeekRadio.com Twitter @adamculp