SlideShare a Scribd company logo
1 of 46
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

What's hot

Clean code - DSC DYPCOE
Clean code - DSC DYPCOEClean code - DSC DYPCOE
Clean code - DSC DYPCOEPatil Shreyas
 
Refactoring and code smells
Refactoring and code smellsRefactoring and code smells
Refactoring and code smellsPaul Nguyen
 
Refactoring for Domain Driven Design
Refactoring for Domain Driven DesignRefactoring for Domain Driven Design
Refactoring for Domain Driven DesignDavid Berliner
 
Bad Code Smells
Bad Code SmellsBad Code Smells
Bad Code Smellskim.mens
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design PatternsAnton Keks
 
Clean architecture
Clean architectureClean architecture
Clean architecture.NET Crowd
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code SmellsMario Sangiorgio
 
Interface segregation principle
Interface segregation principleInterface segregation principle
Interface segregation principlemuhammadali0014
 
The Clean Architecture
The Clean ArchitectureThe Clean Architecture
The Clean ArchitectureDmytro Turskyi
 
Software Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdfSoftware Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdfVictor Rentea
 
SOLID Principle & Design Pattern.pdf
SOLID Principle & Design Pattern.pdfSOLID Principle & Design Pattern.pdf
SOLID Principle & Design Pattern.pdfrony setyawansyah
 
Hexagonal architecture - message-oriented software design
Hexagonal architecture  - message-oriented software designHexagonal architecture  - message-oriented software design
Hexagonal architecture - message-oriented software designMatthias Noback
 

What's hot (20)

Clean code - DSC DYPCOE
Clean code - DSC DYPCOEClean code - DSC DYPCOE
Clean code - DSC DYPCOE
 
Refactoring and code smells
Refactoring and code smellsRefactoring and code smells
Refactoring and code smells
 
Refactoring
RefactoringRefactoring
Refactoring
 
Refactoring for Domain Driven Design
Refactoring for Domain Driven DesignRefactoring for Domain Driven Design
Refactoring for Domain Driven Design
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
 
Refactoring
RefactoringRefactoring
Refactoring
 
Bad Code Smells
Bad Code SmellsBad Code Smells
Bad Code Smells
 
For Beginners - C#
For Beginners - C#For Beginners - C#
For Beginners - C#
 
Clean code
Clean codeClean code
Clean code
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
 
Clean architecture
Clean architectureClean architecture
Clean architecture
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
 
Interface segregation principle
Interface segregation principleInterface segregation principle
Interface segregation principle
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
The Clean Architecture
The Clean ArchitectureThe Clean Architecture
The Clean Architecture
 
Intro to Git and GitHub
Intro to Git and GitHubIntro to Git and GitHub
Intro to Git and GitHub
 
Software Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdfSoftware Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdf
 
SOLID Principle & Design Pattern.pdf
SOLID Principle & Design Pattern.pdfSOLID Principle & Design Pattern.pdf
SOLID Principle & Design Pattern.pdf
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
Hexagonal architecture - message-oriented software design
Hexagonal architecture  - message-oriented software designHexagonal architecture  - message-oriented software design
Hexagonal architecture - message-oriented software design
 

Viewers also liked

Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design PatternSanae BEKKAR
 
Refactoring - An Introduction
Refactoring - An IntroductionRefactoring - An Introduction
Refactoring - An IntroductionGiorgio Vespucci
 
The Decorator Pattern
The Decorator PatternThe Decorator Pattern
The Decorator PatternAkshat Vig
 
Design Patterns這樣學就會了:入門班 Day1 教材
Design Patterns這樣學就會了:入門班 Day1 教材Design Patterns這樣學就會了:入門班 Day1 教材
Design Patterns這樣學就會了:入門班 Day1 教材teddysoft
 
Design Patterns Illustrated
Design Patterns IllustratedDesign Patterns Illustrated
Design Patterns IllustratedHerman Peeren
 
Design Patterns - 01 Introduction and Decorator Pattern
Design Patterns - 01 Introduction and Decorator PatternDesign Patterns - 01 Introduction and Decorator Pattern
Design Patterns - 01 Introduction and Decorator Patterneprafulla
 
Design Patterns
Design PatternsDesign Patterns
Design Patternssoms_1
 

Viewers also liked (9)

Code Refactoring
Code RefactoringCode Refactoring
Code Refactoring
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design Pattern
 
Refactoring - An Introduction
Refactoring - An IntroductionRefactoring - An Introduction
Refactoring - An Introduction
 
The Decorator Pattern
The Decorator PatternThe Decorator Pattern
The Decorator Pattern
 
Design Patterns這樣學就會了:入門班 Day1 教材
Design Patterns這樣學就會了:入門班 Day1 教材Design Patterns這樣學就會了:入門班 Day1 教材
Design Patterns這樣學就會了:入門班 Day1 教材
 
Design Patterns Illustrated
Design Patterns IllustratedDesign Patterns Illustrated
Design Patterns Illustrated
 
Design Patterns - 01 Introduction and Decorator Pattern
Design Patterns - 01 Introduction and Decorator PatternDesign Patterns - 01 Introduction and Decorator Pattern
Design Patterns - 01 Introduction and Decorator Pattern
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 

Similar to Refactoring 101

Refactoring Legacy Code
Refactoring Legacy CodeRefactoring Legacy Code
Refactoring Legacy CodeAdam Culp
 
Prashant technical practices-tdd for xebia event
Prashant   technical practices-tdd for xebia eventPrashant   technical practices-tdd for xebia event
Prashant technical practices-tdd for xebia eventXebia India
 
Workshop: Refactoring Legacy PHP: The Complete Guide
Workshop: Refactoring Legacy PHP: The Complete Guide Workshop: Refactoring Legacy PHP: The Complete Guide
Workshop: Refactoring Legacy PHP: The Complete Guide Junade Ali
 
Converting Your Legacy Data to S1000D
Converting Your Legacy Data to S1000DConverting Your Legacy Data to S1000D
Converting Your Legacy Data to S1000Ddclsocialmedia
 
Peephole optimization techniques in compiler design
Peephole optimization techniques in compiler designPeephole optimization techniques in compiler design
Peephole optimization techniques in compiler designAnul Chaudhary
 
The Power Of Refactoring (php|tek 09)
The Power Of Refactoring (php|tek 09)The Power Of Refactoring (php|tek 09)
The Power Of Refactoring (php|tek 09)Stefan Koopmanschap
 
Refactoring: Improving the design of existing code
Refactoring: Improving the design of existing codeRefactoring: Improving the design of existing code
Refactoring: Improving the design of existing codeKnoldus Inc.
 
They why behind php frameworks
They why behind php frameworksThey why behind php frameworks
They why behind php frameworksKirk Madera
 
Refactoring Techniques
Refactoring TechniquesRefactoring Techniques
Refactoring TechniquesMayada Ghanem
 
Zend expressive workshop
Zend expressive workshopZend expressive workshop
Zend expressive workshopAdam Culp
 
2014 11 20 Drupal 7 -> 8 test migratie
2014 11 20 Drupal 7 -> 8 test migratie2014 11 20 Drupal 7 -> 8 test migratie
2014 11 20 Drupal 7 -> 8 test migratiehcderaad
 
Refactoring PHP
Refactoring PHPRefactoring PHP
Refactoring PHPAdam Culp
 
Standard Coding, OOP Techniques and Code Reuse
Standard Coding, OOP Techniques and Code ReuseStandard Coding, OOP Techniques and Code Reuse
Standard Coding, OOP Techniques and Code ReuseRayhan Chowdhury
 
An Introduction to Scrum: presented at PyTexas 2012
An Introduction to Scrum: presented at PyTexas 2012An Introduction to Scrum: presented at PyTexas 2012
An Introduction to Scrum: presented at PyTexas 2012Tomo Popovic
 
Kylin Engineering Principles
Kylin Engineering PrinciplesKylin Engineering Principles
Kylin Engineering PrinciplesXu Jiang
 
Keeping code clean
Keeping code cleanKeeping code clean
Keeping code cleanBrett Child
 
Angular Ivy- An Overview
Angular Ivy- An OverviewAngular Ivy- An Overview
Angular Ivy- An OverviewJalpesh Vadgama
 
Behat Workshop at WeLovePHP
Behat Workshop at WeLovePHPBehat Workshop at WeLovePHP
Behat Workshop at WeLovePHPMarcos Quesada
 
04 Functional Programming in Python
04 Functional Programming in Python04 Functional Programming in Python
04 Functional Programming in PythonEbad ullah Qureshi
 

Similar to Refactoring 101 (20)

Refactoring Legacy Code
Refactoring Legacy CodeRefactoring Legacy Code
Refactoring Legacy Code
 
Prashant technical practices-tdd for xebia event
Prashant   technical practices-tdd for xebia eventPrashant   technical practices-tdd for xebia event
Prashant technical practices-tdd for xebia event
 
Workshop: Refactoring Legacy PHP: The Complete Guide
Workshop: Refactoring Legacy PHP: The Complete Guide Workshop: Refactoring Legacy PHP: The Complete Guide
Workshop: Refactoring Legacy PHP: The Complete Guide
 
Converting Your Legacy Data to S1000D
Converting Your Legacy Data to S1000DConverting Your Legacy Data to S1000D
Converting Your Legacy Data to S1000D
 
Peephole optimization techniques in compiler design
Peephole optimization techniques in compiler designPeephole optimization techniques in compiler design
Peephole optimization techniques in compiler design
 
The Power Of Refactoring (php|tek 09)
The Power Of Refactoring (php|tek 09)The Power Of Refactoring (php|tek 09)
The Power Of Refactoring (php|tek 09)
 
Refactoring: Improving the design of existing code
Refactoring: Improving the design of existing codeRefactoring: Improving the design of existing code
Refactoring: Improving the design of existing code
 
They why behind php frameworks
They why behind php frameworksThey why behind php frameworks
They why behind php frameworks
 
Refactoring Techniques
Refactoring TechniquesRefactoring Techniques
Refactoring Techniques
 
Zend expressive workshop
Zend expressive workshopZend expressive workshop
Zend expressive workshop
 
2014 11 20 Drupal 7 -> 8 test migratie
2014 11 20 Drupal 7 -> 8 test migratie2014 11 20 Drupal 7 -> 8 test migratie
2014 11 20 Drupal 7 -> 8 test migratie
 
Refactoring PHP
Refactoring PHPRefactoring PHP
Refactoring PHP
 
Standard Coding, OOP Techniques and Code Reuse
Standard Coding, OOP Techniques and Code ReuseStandard Coding, OOP Techniques and Code Reuse
Standard Coding, OOP Techniques and Code Reuse
 
An Introduction to Scrum: presented at PyTexas 2012
An Introduction to Scrum: presented at PyTexas 2012An Introduction to Scrum: presented at PyTexas 2012
An Introduction to Scrum: presented at PyTexas 2012
 
Kylin Engineering Principles
Kylin Engineering PrinciplesKylin Engineering Principles
Kylin Engineering Principles
 
Keeping code clean
Keeping code cleanKeeping code clean
Keeping code clean
 
Angular Ivy- An Overview
Angular Ivy- An OverviewAngular Ivy- An Overview
Angular Ivy- An Overview
 
Behat Workshop at WeLovePHP
Behat Workshop at WeLovePHPBehat Workshop at WeLovePHP
Behat Workshop at WeLovePHP
 
04 Functional Programming in Python
04 Functional Programming in Python04 Functional Programming in Python
04 Functional Programming in Python
 
Optimizing performance
Optimizing performanceOptimizing performance
Optimizing performance
 

More from Adam Culp

Putting legacy to REST with middleware
Putting legacy to REST with middlewarePutting legacy to REST with middleware
Putting legacy to REST with middlewareAdam Culp
 
Release your refactoring superpower
Release your refactoring superpowerRelease your refactoring superpower
Release your refactoring superpowerAdam Culp
 
Managing Technical Debt
Managing Technical DebtManaging Technical Debt
Managing Technical DebtAdam Culp
 
Developing PHP Applications Faster
Developing PHP Applications FasterDeveloping PHP Applications Faster
Developing PHP Applications FasterAdam Culp
 
Containing Quality
Containing QualityContaining Quality
Containing QualityAdam Culp
 
Debugging elephpants
Debugging elephpantsDebugging elephpants
Debugging elephpantsAdam Culp
 
Expressive Microservice Framework Blastoff
Expressive Microservice Framework BlastoffExpressive Microservice Framework Blastoff
Expressive Microservice Framework BlastoffAdam Culp
 
Foundations of Zend Framework
Foundations of Zend FrameworkFoundations of Zend Framework
Foundations of Zend FrameworkAdam Culp
 
Accidental professional
Accidental professionalAccidental professional
Accidental professionalAdam Culp
 
Build great products
Build great productsBuild great products
Build great productsAdam Culp
 
Does Your Code Measure Up?
Does Your Code Measure Up?Does Your Code Measure Up?
Does Your Code Measure Up?Adam Culp
 
Practical PHP Deployment with Jenkins
Practical PHP Deployment with JenkinsPractical PHP Deployment with Jenkins
Practical PHP Deployment with JenkinsAdam Culp
 
Virtualizing Development
Virtualizing DevelopmentVirtualizing Development
Virtualizing DevelopmentAdam Culp
 
Deprecated: Foundations of Zend Framework 2
Deprecated: Foundations of Zend Framework 2Deprecated: Foundations of Zend Framework 2
Deprecated: Foundations of Zend Framework 2Adam Culp
 
Clean application development tutorial
Clean application development tutorialClean application development tutorial
Clean application development tutorialAdam Culp
 
Essential git for developers
Essential git for developersEssential git for developers
Essential git for developersAdam Culp
 
Vagrant for Virtualized Development
Vagrant for Virtualized DevelopmentVagrant for Virtualized Development
Vagrant for Virtualized DevelopmentAdam Culp
 
Clean application development (talk)
Clean application development (talk)Clean application development (talk)
Clean application development (talk)Adam Culp
 

More from Adam Culp (20)

Hypermedia
HypermediaHypermedia
Hypermedia
 
Putting legacy to REST with middleware
Putting legacy to REST with middlewarePutting legacy to REST with middleware
Putting legacy to REST with middleware
 
php-1701-a
php-1701-aphp-1701-a
php-1701-a
 
Release your refactoring superpower
Release your refactoring superpowerRelease your refactoring superpower
Release your refactoring superpower
 
Managing Technical Debt
Managing Technical DebtManaging Technical Debt
Managing Technical Debt
 
Developing PHP Applications Faster
Developing PHP Applications FasterDeveloping PHP Applications Faster
Developing PHP Applications Faster
 
Containing Quality
Containing QualityContaining Quality
Containing Quality
 
Debugging elephpants
Debugging elephpantsDebugging elephpants
Debugging elephpants
 
Expressive Microservice Framework Blastoff
Expressive Microservice Framework BlastoffExpressive Microservice Framework Blastoff
Expressive Microservice Framework Blastoff
 
Foundations of Zend Framework
Foundations of Zend FrameworkFoundations of Zend Framework
Foundations of Zend Framework
 
Accidental professional
Accidental professionalAccidental professional
Accidental professional
 
Build great products
Build great productsBuild great products
Build great products
 
Does Your Code Measure Up?
Does Your Code Measure Up?Does Your Code Measure Up?
Does Your Code Measure Up?
 
Practical PHP Deployment with Jenkins
Practical PHP Deployment with JenkinsPractical PHP Deployment with Jenkins
Practical PHP Deployment with Jenkins
 
Virtualizing Development
Virtualizing DevelopmentVirtualizing Development
Virtualizing Development
 
Deprecated: Foundations of Zend Framework 2
Deprecated: Foundations of Zend Framework 2Deprecated: Foundations of Zend Framework 2
Deprecated: Foundations of Zend Framework 2
 
Clean application development tutorial
Clean application development tutorialClean application development tutorial
Clean application development tutorial
 
Essential git for developers
Essential git for developersEssential git for developers
Essential git for developers
 
Vagrant for Virtualized Development
Vagrant for Virtualized DevelopmentVagrant for Virtualized Development
Vagrant for Virtualized Development
 
Clean application development (talk)
Clean application development (talk)Clean application development (talk)
Clean application development (talk)
 

Recently uploaded

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 

Recently uploaded (20)

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 

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