SlideShare ist ein Scribd-Unternehmen logo
1 von 31
Refactoring



             Presentation for:
      South Florida PHP Users Group
                     By:
               Adam Culp
              Twitter: @adamculp
           http://www.geekyboy.com
Refactoring

   Based on popular “Refactoring” Improving The
    Design of Existing Code book, by Martin
    Fowler.
   We will start in the code with an example.
   Tips and descriptions will be handled during the
    example.
   In the example we are tasked with creating an
    HTML representation of the customer
    statement for a movie rental.
Refactoring

   Movie class
       With a new project we take
        a look at the current
        application a customer has
        requested to be changed.
       We start with the Movie
        class.
Refactoring

   Rental class
       Next we look at the Rental
        class.
Refactoring

   Customer class p1
       With a new project we take
        a look at the current app
        that is about to be
        changed.
       Next we look at part 1 of
        the Customer class.
Refactoring

   Customer class p2
       With a new project we take
        a look at the current app
        that is about to be
        changed.
       Next we look at part 2 of
        the Customer class.
Refactoring

   Not terrible for a small quick and dirty application, but
    if part of a larger application we have problems.
   Customer class doing far too much, and statement
    method is too long.
   Impossible to reuse the statement for an HTML
    representation.
   The customer also wants to be able to change how
    they classify movies.
   As experienced developers we know that customers
    will always come back six months from now and want
    it changed in some way.
Refactoring

   Rewrite vs Refactor
       Budget constraint
       Time constraint
       Rewrite is an excuse to NOT dig in someone's code
       Refactor is the best teacher
Refactoring

   First step
       Build tests based on current “working” application,
        so we can verify if we break something.
       Pre-load database with data or create fixtures
        needed for tests, to ensure we have a constant to
        compare test results.
       If we are not starting with a working application you
        must first get the application working prior to
        refactoring. Do not try to refactor a broken
        application or you risk breaking it further, and end
        up with a total rewrite.
Refactoring
   Step 1
       Extract Method to move switch statement to its own method.
Refactoring
   Step 2
       Variable names should make sense. (each > rental, thisAmount > result)
Refactoring
   Step 3
       Extract Method amountFor() to Rental class. It uses information from
        Rental, but no information from Customer. We rename it to more
        meaningful getCharge().
Refactoring
   Step 4
       Call getCharge() directly from statement() instead of using amountFor() as
        a middle man method.
Refactoring
   Step 5
       Replace Temp with Query - Cleanup of call to getCharge(). Eliminate
        temp variables by calling method direct. Less maintenance.
Refactoring
   Step 6
       Extract Method and move frequentRenterPoints to its own method in
        Rental class where it logically belongs.
Refactoring
   Step 7
       We do Replace Temp with Query for totalAmount. Temp variables can be
        a problem and really only serve a purpose within their own routine and
        encourage long, complex routines.
Refactoring
   Step 8
       Also do Replace Temp with Query on frequentRentalPoints to eliminate
        more temp variables.
Refactoring
   Step 9
       We are now able to create the HTML version of the statement, and we
        rename the original to represent a Text version.
Refactoring

   Recap
       Most refactoring reduces code, while we increased it for
        this example.
       We also duplicated a loop to make it happen 4 times
        instead    of     once.     (getFrequentRenterPoints,
        getTotalCharge, getTotalFrequentRenterPoints)
       Optimizing and refactoring are different actions.
        Refactor first, then optimize later if needed.
       More refactoring could further clean up Text and HTML
        statements to DRY it up. (split out header/footer, etc.)
       Still need more refactoring to allow classification
        changes by the customer.
Refactoring
   Step 10
       Move Method on getCharge() because it uses data in Movie, so should be
        in the same class as the data.
Refactoring
   Step 11
       Replace Conditional with Polymorphism on getCharge() because it uses
        data in Movie, so should be in the same class as the data.
Refactoring

   Two hats
       Adding Function Hat
       Refactoring Hat
First we add functionality, they we refactor it, then
add more functionality, ...
Refactoring

   Why Refactor?
       Without refactoring code decays
       As code is changed it loses structure, making it
        harder to see design
                  Regular refactoring preserves design
       Poorly designed = more code due to duplication
                  Reduced code = easier to maintain
                  Reduced code = easier to understand
       Helps find bugs
       Helps us program faster
Refactoring

   When to Refactor?
       Should not set aside time to refactor, it is just
        something we do in short bursts
       Refactor because you want to do something, and
        refactoring helps you do it
                  Often a quick refactor can help developing new
                    functionalities move faster
       Rule of Three → see next slide
Refactoring

   Rule of Three
       When you add function
                  Helps to learn code you need to modify
                  Changes code that prevents the addition
       When you need to fix a bug
                  Make code more understandable
                  Usually highlights the bug
       During code review
                  Code looks good to developer, but maybe not to
                    the team.
                  More concrete results
Refactoring

   What do I tell my manager?
       For a tech saavy manager it may not be hard to
        explain the benefits
       Quality centric manager stress quality aspects
                   Perhaps introduce it as a review process
                   There are many resources on Google about
                     value of reviews, inspections, or software
                     development process
       Schedule driven … Don't tell (controversial?)
                   Find a way to work it into scheduling.
                   Overall it saves time, but some will never “see” it
Refactoring

   Code “smells” as indicators
       Bad code “smells” and is a great way of indicating it
        is time for a refactor.
                   Duplicate Code
                   Long Method
                   Large Class
                   Long Parameter (argument) List
                   Divergent Change - if change is needed in
                     multiple areas to accommodate a change
                   Shotgun Surgery – change causes ripple of other
                     needed changes
                   Feature Envy – a method seems to use another
                     class instead of the one it is in
Refactoring

   Code “smells” as indicators
       More “smells”
                  Data Clumps – if data items tend to accompany
                    one another
                  Primitive Obsession
                  Switch statements
                  Parallel Inheritance Hierarchies – caused when
                    you need to create a subclass of one object
                    because you created a subclass of another
                  Lazy Class – classes that do not do much and do
                    not pay for their extra weight
                  Speculative Generality – constructs built for the
                    sake of possibility later
Refactoring

   Code “smells” as indicators
       More “smells”
                  Temporary Field
                  Message Chains – object asking for object that
                     asks for another object...
                  Middle Man – directors in place but serving no
                     real purpose
                  Inappropriate Intimacy – classes should not deal
                     too much with each others private parts
                  Data Class – getters and setters, but nothing else
                  Comments – where comments are used as
                     deodorant to cover a bad smell
Refactoring

   Tests and Refactoring
       You cannot properly refactor without tests in place.
       Writing tests is the first step of refactoring, and
        should happen as you write the code in the first
        place. (or before, as with TDD)
Refactoring

   Thank you


                   Adam Culp
            http://www.geekyboy.com
           http://github.com/adamculp
                Twitter @adamculp

Weitere ähnliche Inhalte

Was ist angesagt?

Micro Frontends Architecture - Jitendra kumawat (Guavus)
Micro Frontends Architecture - Jitendra kumawat (Guavus)Micro Frontends Architecture - Jitendra kumawat (Guavus)
Micro Frontends Architecture - Jitendra kumawat (Guavus)Tech Triveni
 
Mikrofrontend a Module Federation
Mikrofrontend a Module FederationMikrofrontend a Module Federation
Mikrofrontend a Module FederationThe Software House
 
FEVR - Micro Frontend
FEVR - Micro FrontendFEVR - Micro Frontend
FEVR - Micro FrontendMiki Lombardi
 
Microservices and docker
Microservices and dockerMicroservices and docker
Microservices and dockerAlex Ivy
 
An introduction to DevOps
An introduction to DevOpsAn introduction to DevOps
An introduction to DevOpsAlexander Meijers
 
SWE-401 - 1. Introduction to Software Engineering
SWE-401 - 1. Introduction to Software EngineeringSWE-401 - 1. Introduction to Software Engineering
SWE-401 - 1. Introduction to Software Engineeringghayour abbas
 
State of Micro Frontend
State of Micro FrontendState of Micro Frontend
State of Micro FrontendYugo Sakamoto
 
Micro frontends
Micro frontendsMicro frontends
Micro frontendsAssaf Gannon
 
Introduction To Micro Frontends
Introduction To Micro Frontends Introduction To Micro Frontends
Introduction To Micro Frontends Meitar Karas
 
Software architecture
Software architectureSoftware architecture
Software architecturenazn
 
MVVM in iOS presentation
MVVM in iOS presentationMVVM in iOS presentation
MVVM in iOS presentationG ABHISEK
 
Dev ops != Dev+Ops
Dev ops != Dev+OpsDev ops != Dev+Ops
Dev ops != Dev+OpsShalu Ahuja
 
Globant development week / Micro frontend
Globant development week / Micro frontendGlobant development week / Micro frontend
Globant development week / Micro frontendGlobant
 
What is DevOps? | DevOps Introduction | DevOps Tools | DevOps Tutorial For Be...
What is DevOps? | DevOps Introduction | DevOps Tools | DevOps Tutorial For Be...What is DevOps? | DevOps Introduction | DevOps Tools | DevOps Tutorial For Be...
What is DevOps? | DevOps Introduction | DevOps Tools | DevOps Tutorial For Be...Simplilearn
 
Micro Front-End & Microservices - Plansoft
Micro Front-End & Microservices - PlansoftMicro Front-End & Microservices - Plansoft
Micro Front-End & Microservices - PlansoftMiki Lombardi
 

Was ist angesagt? (20)

Micro Frontends Architecture - Jitendra kumawat (Guavus)
Micro Frontends Architecture - Jitendra kumawat (Guavus)Micro Frontends Architecture - Jitendra kumawat (Guavus)
Micro Frontends Architecture - Jitendra kumawat (Guavus)
 
Micro Frontends
Micro FrontendsMicro Frontends
Micro Frontends
 
Mikrofrontend a Module Federation
Mikrofrontend a Module FederationMikrofrontend a Module Federation
Mikrofrontend a Module Federation
 
FEVR - Micro Frontend
FEVR - Micro FrontendFEVR - Micro Frontend
FEVR - Micro Frontend
 
Microservices and docker
Microservices and dockerMicroservices and docker
Microservices and docker
 
An introduction to DevOps
An introduction to DevOpsAn introduction to DevOps
An introduction to DevOps
 
DevOps
DevOps DevOps
DevOps
 
SWE-401 - 1. Introduction to Software Engineering
SWE-401 - 1. Introduction to Software EngineeringSWE-401 - 1. Introduction to Software Engineering
SWE-401 - 1. Introduction to Software Engineering
 
State of Micro Frontend
State of Micro FrontendState of Micro Frontend
State of Micro Frontend
 
Micro frontends
Micro frontendsMicro frontends
Micro frontends
 
Introduction To Micro Frontends
Introduction To Micro Frontends Introduction To Micro Frontends
Introduction To Micro Frontends
 
Microservicios
MicroserviciosMicroservicios
Microservicios
 
Software architecture
Software architectureSoftware architecture
Software architecture
 
MVVM in iOS presentation
MVVM in iOS presentationMVVM in iOS presentation
MVVM in iOS presentation
 
Dev ops != Dev+Ops
Dev ops != Dev+OpsDev ops != Dev+Ops
Dev ops != Dev+Ops
 
Micro-frontend
Micro-frontendMicro-frontend
Micro-frontend
 
Globant development week / Micro frontend
Globant development week / Micro frontendGlobant development week / Micro frontend
Globant development week / Micro frontend
 
What is DevOps? | DevOps Introduction | DevOps Tools | DevOps Tutorial For Be...
What is DevOps? | DevOps Introduction | DevOps Tools | DevOps Tutorial For Be...What is DevOps? | DevOps Introduction | DevOps Tools | DevOps Tutorial For Be...
What is DevOps? | DevOps Introduction | DevOps Tools | DevOps Tutorial For Be...
 
Devops
DevopsDevops
Devops
 
Micro Front-End & Microservices - Plansoft
Micro Front-End & Microservices - PlansoftMicro Front-End & Microservices - Plansoft
Micro Front-End & Microservices - Plansoft
 

Ă„hnlich wie Refactoring PHP

Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerIgor Crvenov
 
Workshop - The Little Pattern That Could.pdf
Workshop - The Little Pattern That Could.pdfWorkshop - The Little Pattern That Could.pdf
Workshop - The Little Pattern That Could.pdfTobiasGoeschel
 
Reduce Reuse Refactor
Reduce Reuse RefactorReduce Reuse Refactor
Reduce Reuse RefactorAlena Holligan
 
Refactoring, A First Example
Refactoring, A First ExampleRefactoring, A First Example
Refactoring, A First ExampleVorleak Chy
 
Refactoring, 2nd Edition
Refactoring, 2nd EditionRefactoring, 2nd Edition
Refactoring, 2nd Editionjexp
 
Refactoring 2 The Max
Refactoring 2 The MaxRefactoring 2 The Max
Refactoring 2 The MaxAlfredo Morresi
 
Design Patterns
Design PatternsDesign Patterns
Design Patternsimedo.de
 
Introduction to Refactoring
Introduction to RefactoringIntroduction to Refactoring
Introduction to RefactoringVorleak Chy
 
Principles in Refactoring
Principles in RefactoringPrinciples in Refactoring
Principles in RefactoringChamnap Chhorn
 
Agile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddAgile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddSrinivasa GV
 
How can JAVA Performance tuning speed up applications.pdf
How can JAVA Performance tuning speed up applications.pdfHow can JAVA Performance tuning speed up applications.pdf
How can JAVA Performance tuning speed up applications.pdfMindfire LLC
 
Principlesinrefactoring 090906230021-phpapp01
Principlesinrefactoring 090906230021-phpapp01Principlesinrefactoring 090906230021-phpapp01
Principlesinrefactoring 090906230021-phpapp01Sopheak Sem
 
Put to the Test
Put to the TestPut to the Test
Put to the TestKevlin Henney
 
Lecture: Refactoring
Lecture: RefactoringLecture: Refactoring
Lecture: RefactoringMarcus Denker
 
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
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2Hammad Rajjoub
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2Hammad Rajjoub
 
Ian Cooper webinar for DDD Iran: Kent beck style tdd seven years after
Ian Cooper webinar for DDD Iran: Kent beck style tdd   seven years afterIan Cooper webinar for DDD Iran: Kent beck style tdd   seven years after
Ian Cooper webinar for DDD Iran: Kent beck style tdd seven years afterIranian Domain-Driven Design Community
 

Ă„hnlich wie Refactoring PHP (20)

Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin Fowler
 
Workshop - The Little Pattern That Could.pdf
Workshop - The Little Pattern That Could.pdfWorkshop - The Little Pattern That Could.pdf
Workshop - The Little Pattern That Could.pdf
 
Reduce Reuse Refactor
Reduce Reuse RefactorReduce Reuse Refactor
Reduce Reuse Refactor
 
Refactoring, A First Example
Refactoring, A First ExampleRefactoring, A First Example
Refactoring, A First Example
 
Refactoring
RefactoringRefactoring
Refactoring
 
Refactoring, 2nd Edition
Refactoring, 2nd EditionRefactoring, 2nd Edition
Refactoring, 2nd Edition
 
Refactoring 2 The Max
Refactoring 2 The MaxRefactoring 2 The Max
Refactoring 2 The Max
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Introduction to Refactoring
Introduction to RefactoringIntroduction to Refactoring
Introduction to Refactoring
 
Principles in Refactoring
Principles in RefactoringPrinciples in Refactoring
Principles in Refactoring
 
Refactoring
RefactoringRefactoring
Refactoring
 
Agile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddAgile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tdd
 
How can JAVA Performance tuning speed up applications.pdf
How can JAVA Performance tuning speed up applications.pdfHow can JAVA Performance tuning speed up applications.pdf
How can JAVA Performance tuning speed up applications.pdf
 
Principlesinrefactoring 090906230021-phpapp01
Principlesinrefactoring 090906230021-phpapp01Principlesinrefactoring 090906230021-phpapp01
Principlesinrefactoring 090906230021-phpapp01
 
Put to the Test
Put to the TestPut to the Test
Put to the Test
 
Lecture: Refactoring
Lecture: RefactoringLecture: Refactoring
Lecture: Refactoring
 
Few minutes To better Code - Refactoring
Few minutes To better Code - RefactoringFew minutes To better Code - Refactoring
Few minutes To better Code - Refactoring
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2
 
Ian Cooper webinar for DDD Iran: Kent beck style tdd seven years after
Ian Cooper webinar for DDD Iran: Kent beck style tdd   seven years afterIan Cooper webinar for DDD Iran: Kent beck style tdd   seven years after
Ian Cooper webinar for DDD Iran: Kent beck style tdd seven years after
 

Mehr von Adam Culp

Hypermedia
HypermediaHypermedia
HypermediaAdam 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
 
php-1701-a
php-1701-aphp-1701-a
php-1701-aAdam 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
 
Zend expressive workshop
Zend expressive workshopZend expressive workshop
Zend expressive workshopAdam 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
 
Refactoring Legacy Code
Refactoring Legacy CodeRefactoring Legacy Code
Refactoring Legacy CodeAdam 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
 
Refactoring 101
Refactoring 101Refactoring 101
Refactoring 101Adam Culp
 

Mehr von 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
 
Zend expressive workshop
Zend expressive workshopZend expressive workshop
Zend expressive workshop
 
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
 
Refactoring Legacy Code
Refactoring Legacy CodeRefactoring Legacy Code
Refactoring Legacy Code
 
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
 
Refactoring 101
Refactoring 101Refactoring 101
Refactoring 101
 

KĂĽrzlich hochgeladen

Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
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
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
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
 
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
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
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
 
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
 
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
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
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
 
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
 
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
 
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
 

KĂĽrzlich hochgeladen (20)

Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
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
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
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
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
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
 
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
 
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...
 
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
 

Refactoring PHP

  • 1. Refactoring Presentation for: South Florida PHP Users Group By: Adam Culp Twitter: @adamculp http://www.geekyboy.com
  • 2. Refactoring  Based on popular “Refactoring” Improving The Design of Existing Code book, by Martin Fowler.  We will start in the code with an example.  Tips and descriptions will be handled during the example.  In the example we are tasked with creating an HTML representation of the customer statement for a movie rental.
  • 3. Refactoring  Movie class  With a new project we take a look at the current application a customer has requested to be changed.  We start with the Movie class.
  • 4. Refactoring  Rental class  Next we look at the Rental class.
  • 5. Refactoring  Customer class p1  With a new project we take a look at the current app that is about to be changed.  Next we look at part 1 of the Customer class.
  • 6. Refactoring  Customer class p2  With a new project we take a look at the current app that is about to be changed.  Next we look at part 2 of the Customer class.
  • 7. Refactoring  Not terrible for a small quick and dirty application, but if part of a larger application we have problems.  Customer class doing far too much, and statement method is too long.  Impossible to reuse the statement for an HTML representation.  The customer also wants to be able to change how they classify movies.  As experienced developers we know that customers will always come back six months from now and want it changed in some way.
  • 8. Refactoring  Rewrite vs Refactor  Budget constraint  Time constraint  Rewrite is an excuse to NOT dig in someone's code  Refactor is the best teacher
  • 9. Refactoring  First step  Build tests based on current “working” application, so we can verify if we break something.  Pre-load database with data or create fixtures needed for tests, to ensure we have a constant to compare test results.  If we are not starting with a working application you must first get the application working prior to refactoring. Do not try to refactor a broken application or you risk breaking it further, and end up with a total rewrite.
  • 10. Refactoring  Step 1  Extract Method to move switch statement to its own method.
  • 11. Refactoring  Step 2  Variable names should make sense. (each > rental, thisAmount > result)
  • 12. Refactoring  Step 3  Extract Method amountFor() to Rental class. It uses information from Rental, but no information from Customer. We rename it to more meaningful getCharge().
  • 13. Refactoring  Step 4  Call getCharge() directly from statement() instead of using amountFor() as a middle man method.
  • 14. Refactoring  Step 5  Replace Temp with Query - Cleanup of call to getCharge(). Eliminate temp variables by calling method direct. Less maintenance.
  • 15. Refactoring  Step 6  Extract Method and move frequentRenterPoints to its own method in Rental class where it logically belongs.
  • 16. Refactoring  Step 7  We do Replace Temp with Query for totalAmount. Temp variables can be a problem and really only serve a purpose within their own routine and encourage long, complex routines.
  • 17. Refactoring  Step 8  Also do Replace Temp with Query on frequentRentalPoints to eliminate more temp variables.
  • 18. Refactoring  Step 9  We are now able to create the HTML version of the statement, and we rename the original to represent a Text version.
  • 19. Refactoring  Recap  Most refactoring reduces code, while we increased it for this example.  We also duplicated a loop to make it happen 4 times instead of once. (getFrequentRenterPoints, getTotalCharge, getTotalFrequentRenterPoints)  Optimizing and refactoring are different actions. Refactor first, then optimize later if needed.  More refactoring could further clean up Text and HTML statements to DRY it up. (split out header/footer, etc.)  Still need more refactoring to allow classification changes by the customer.
  • 20. Refactoring  Step 10  Move Method on getCharge() because it uses data in Movie, so should be in the same class as the data.
  • 21. Refactoring  Step 11  Replace Conditional with Polymorphism on getCharge() because it uses data in Movie, so should be in the same class as the data.
  • 22. Refactoring  Two hats  Adding Function Hat  Refactoring Hat First we add functionality, they we refactor it, then add more functionality, ...
  • 23. Refactoring  Why Refactor?  Without refactoring code decays  As code is changed it loses structure, making it harder to see design  Regular refactoring preserves design  Poorly designed = more code due to duplication  Reduced code = easier to maintain  Reduced code = easier to understand  Helps find bugs  Helps us program faster
  • 24. Refactoring  When to Refactor?  Should not set aside time to refactor, it is just something we do in short bursts  Refactor because you want to do something, and refactoring helps you do it  Often a quick refactor can help developing new functionalities move faster  Rule of Three → see next slide
  • 25. Refactoring  Rule of Three  When you add function  Helps to learn code you need to modify  Changes code that prevents the addition  When you need to fix a bug  Make code more understandable  Usually highlights the bug  During code review  Code looks good to developer, but maybe not to the team.  More concrete results
  • 26. Refactoring  What do I tell my manager?  For a tech saavy manager it may not be hard to explain the benefits  Quality centric manager stress quality aspects  Perhaps introduce it as a review process  There are many resources on Google about value of reviews, inspections, or software development process  Schedule driven … Don't tell (controversial?)  Find a way to work it into scheduling.  Overall it saves time, but some will never “see” it
  • 27. Refactoring  Code “smells” as indicators  Bad code “smells” and is a great way of indicating it is time for a refactor.  Duplicate Code  Long Method  Large Class  Long Parameter (argument) List  Divergent Change - if change is needed in multiple areas to accommodate a change  Shotgun Surgery – change causes ripple of other needed changes  Feature Envy – a method seems to use another class instead of the one it is in
  • 28. Refactoring  Code “smells” as indicators  More “smells”  Data Clumps – if data items tend to accompany one another  Primitive Obsession  Switch statements  Parallel Inheritance Hierarchies – caused when you need to create a subclass of one object because you created a subclass of another  Lazy Class – classes that do not do much and do not pay for their extra weight  Speculative Generality – constructs built for the sake of possibility later
  • 29. Refactoring  Code “smells” as indicators  More “smells”  Temporary Field  Message Chains – object asking for object that asks for another object...  Middle Man – directors in place but serving no real purpose  Inappropriate Intimacy – classes should not deal too much with each others private parts  Data Class – getters and setters, but nothing else  Comments – where comments are used as deodorant to cover a bad smell
  • 30. Refactoring  Tests and Refactoring  You cannot properly refactor without tests in place.  Writing tests is the first step of refactoring, and should happen as you write the code in the first place. (or before, as with TDD)
  • 31. Refactoring  Thank you Adam Culp http://www.geekyboy.com http://github.com/adamculp Twitter @adamculp