SlideShare ist ein Scribd-Unternehmen logo
1 von 14
Downloaden Sie, um offline zu lesen
THE ART OF
REFACTORING
ENHANCING CODE QUALITY AND MAINTAINABILITY Prepared By: Asmit Ghimire
Introduction
➔ Refactoring is the process of
restructuring code while not changing
its original functionality.
➔ The main purpose of refactoring is to
enhance the code's readability,
maintainability, and overall quality,
making it easier to understand and
modify while reducing technical debt.
Why Refactoring Matters
➔ Improved code quality / readability
➔ Maintainability
➔ Reduced technical debt
➔ Quicker issue diagnosis
➔ Enhanced team collaboration
➔ Improved extensibility
➔ Performance gain in some cases
Signs It's Time to
Refactor
➔ Code Duplication
➔ Long Methods / Functions
➔ Complex Conditional
Statements
➔ Tight Coupling
➔ Performance Issues
➔ Changing Requirements
➔ Excessive Comments
Refactoring Techniques
➔ Descriptive names to variables,
methods, and classes
➔ Replace Magic Numbers with Named
Constants
➔ Consolidate Conditional Expressions
➔ Introduce Explaining Variable
➔ Introduce Parameter Object
➔ Remove Dead Code
➔ Separate Concerns with Design Patterns
➔ Pull Up / Push Down Methods
➔ Replace Conditional with Polymorphism
Pull Up Method
➔ Problem
◆ Your subclasses have methods that perform
similar work.
➔ Solution
◆ Make the methods identical and then move
them to the relevant superclass.
Push Down Method
➔ Problem
◆ Is behavior implemented in a superclass used by only one (or a few)
subclasses?
➔ Solution
◆ Move this behavior to the subclasses.
Replace Conditionals
with Polymorphism
➔ Problem
◆ You have a conditional that
performs various actions depending
on object type or properties.
class Bird {
// ...
public function getSpeed() {
switch ($this->type) {
case EUROPEAN:
return $this->getBaseSpeed();
case AFRICAN:
return $this->getBaseSpeed() -
$this->getLoadFactor() * $this->numberOfCoconuts;
case NORWEGIAN_BLUE:
return ($this->isNailed) ? 0 :
$this->getBaseSpeed($this->voltage);
}
throw new Exception("Should be unreachable" );
}
// ...
}
Replace Conditionals
with Polymorphism
➔ Solution
◆ Create subclasses matching the
branches of the conditional.
◆ In them, create a shared method and
move code from the corresponding
branch of the conditional to it.
◆ Then replace the conditional with the
relevant method call.
abstract class Bird {
// ...
abstract function getSpeed();
// ...
}
class European extends Bird {
public function getSpeed() {
return $this->getBaseSpeed();
}
}
class African extends Bird {
public function getSpeed() {
return $this->getBaseSpeed() -
$this->getLoadFactor() *
$this->numberOfCoconuts;
}
}
class NorwegianBlue extends Bird {
public function getSpeed() {
return ($this->isNailed) ? 0 :
$this->getBaseSpeed($this->voltage);
}
}
// Somewhere in Client code.
$speed = $bird->getSpeed();
Steps to Successful Refactoring
➔ Identify the target area for refactoring.
➔ Understand the existing behavior and write tests.
➔ Apply the chosen refactoring technique.
➔ Run tests to verify correctness.
➔ Commit changes to version control.
Tools and Resources
➔ SonarQube: Provides extensive static
code analysis, detecting bugs,
vulnerabilities, and code smells across
multiple languages.
➔ CodeClimate: Analyzes code quality,
security, and maintainability, offering
insights and metrics.
Challenges
➔ Time and Resources
➔ Risk of Introducing Bugs
➔ Lack of Automated Tests
➔ Legacy Code and Dependencies
➔ Team Buy-In
➔ Scope Creep
➔ Balancing Refactoring with New Features
➔ Resistance to Change
➔
“Code refactoring is like doing the dishes: it's not fun, but
leaving them all piled up will make things worse.”
The Art of Refactoring | Asmit Ghimire | Gurzu.pdf

Weitere ähnliche Inhalte

Ähnlich wie The Art of Refactoring | Asmit Ghimire | Gurzu.pdf

Dependency injection in Drupal 8
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8
Alexei Gorobets
 

Ähnlich wie The Art of Refactoring | Asmit Ghimire | Gurzu.pdf (20)

OOP Is More Then Cars and Dogs - Midwest PHP 2017
OOP Is More Then Cars and Dogs - Midwest PHP 2017OOP Is More Then Cars and Dogs - Midwest PHP 2017
OOP Is More Then Cars and Dogs - Midwest PHP 2017
 
Php
PhpPhp
Php
 
PHP OOP Lecture - 02.pptx
PHP OOP Lecture - 02.pptxPHP OOP Lecture - 02.pptx
PHP OOP Lecture - 02.pptx
 
Dependency injection in Drupal 8
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8
 
Patterns in PHP
Patterns in PHPPatterns in PHP
Patterns in PHP
 
From framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytvFrom framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytv
 
OOP Is More Than Cars and Dogs
OOP Is More Than Cars and DogsOOP Is More Than Cars and Dogs
OOP Is More Than Cars and Dogs
 
Drupalcon 2023 - How Drupal builds your pages.pdf
Drupalcon 2023 - How Drupal builds your pages.pdfDrupalcon 2023 - How Drupal builds your pages.pdf
Drupalcon 2023 - How Drupal builds your pages.pdf
 
2023 - Drupalcon - How Drupal builds your pages
2023 - Drupalcon - How Drupal builds your pages2023 - Drupalcon - How Drupal builds your pages
2023 - Drupalcon - How Drupal builds your pages
 
Quality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormQuality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStorm
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
PHPSpec BDD for PHP
PHPSpec BDD for PHPPHPSpec BDD for PHP
PHPSpec BDD for PHP
 
Coming to Terms with OOP In Drupal - php[world] 2016
Coming to Terms with OOP In Drupal - php[world] 2016Coming to Terms with OOP In Drupal - php[world] 2016
Coming to Terms with OOP In Drupal - php[world] 2016
 
mod_rewrite
mod_rewritemod_rewrite
mod_rewrite
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
WebCamp: Developer Day: DDD in PHP on example of Symfony - Олег Зинченко
WebCamp: Developer Day: DDD in PHP on example of Symfony - Олег ЗинченкоWebCamp: Developer Day: DDD in PHP on example of Symfony - Олег Зинченко
WebCamp: Developer Day: DDD in PHP on example of Symfony - Олег Зинченко
 
So S.O.L.I.D Fu - Designing Better Code
So S.O.L.I.D Fu - Designing Better CodeSo S.O.L.I.D Fu - Designing Better Code
So S.O.L.I.D Fu - Designing Better Code
 
Drupal Best Practices
Drupal Best PracticesDrupal Best Practices
Drupal Best Practices
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java Developers
 
Refactoring
RefactoringRefactoring
Refactoring
 

Mehr von GurzuInc

Mehr von GurzuInc (18)

Power of documentation | Aarati Shah | Gurzu.pdf
Power of documentation | Aarati Shah | Gurzu.pdfPower of documentation | Aarati Shah | Gurzu.pdf
Power of documentation | Aarati Shah | Gurzu.pdf
 
I'm Programmer _ Ganesh Kunwar _ Gurzu.pdf
I'm Programmer _ Ganesh Kunwar _ Gurzu.pdfI'm Programmer _ Ganesh Kunwar _ Gurzu.pdf
I'm Programmer _ Ganesh Kunwar _ Gurzu.pdf
 
Obtaining Your Tax Clearance Certificate_ A Quick Guide | Deepak Rai | Gurzu.pdf
Obtaining Your Tax Clearance Certificate_ A Quick Guide | Deepak Rai | Gurzu.pdfObtaining Your Tax Clearance Certificate_ A Quick Guide | Deepak Rai | Gurzu.pdf
Obtaining Your Tax Clearance Certificate_ A Quick Guide | Deepak Rai | Gurzu.pdf
 
Problem Solving Skill - Bishal Sapkota - Gurzu
Problem Solving Skill - Bishal Sapkota - GurzuProblem Solving Skill - Bishal Sapkota - Gurzu
Problem Solving Skill - Bishal Sapkota - Gurzu
 
My experience with Mobile Testing - Asmita Poudel - Gurzu
My experience with Mobile Testing - Asmita Poudel - GurzuMy experience with Mobile Testing - Asmita Poudel - Gurzu
My experience with Mobile Testing - Asmita Poudel - Gurzu
 
Upgrading Services _ Ashraya Tuldhar _ Knowledge ketchup.pptx
Upgrading Services _ Ashraya Tuldhar _ Knowledge ketchup.pptxUpgrading Services _ Ashraya Tuldhar _ Knowledge ketchup.pptx
Upgrading Services _ Ashraya Tuldhar _ Knowledge ketchup.pptx
 
The real definition of done (1).pptx.pdf
The real definition of done (1).pptx.pdfThe real definition of done (1).pptx.pdf
The real definition of done (1).pptx.pdf
 
Fantastic Blogs and How to Write Them | Alaka Acharya.pptx
Fantastic Blogs and How to Write Them | Alaka Acharya.pptxFantastic Blogs and How to Write Them | Alaka Acharya.pptx
Fantastic Blogs and How to Write Them | Alaka Acharya.pptx
 
The power of saying no | Abinash Bhattarai | Gurzu.pdf
The power of saying no | Abinash Bhattarai | Gurzu.pdfThe power of saying no | Abinash Bhattarai | Gurzu.pdf
The power of saying no | Abinash Bhattarai | Gurzu.pdf
 
DDOS Attack - Gurzu Nepal
DDOS Attack - Gurzu NepalDDOS Attack - Gurzu Nepal
DDOS Attack - Gurzu Nepal
 
Hotwire and Turbo - Knowledge Ketchup - Prajit Bhandari.pdf
Hotwire and Turbo - Knowledge Ketchup - Prajit Bhandari.pdfHotwire and Turbo - Knowledge Ketchup - Prajit Bhandari.pdf
Hotwire and Turbo - Knowledge Ketchup - Prajit Bhandari.pdf
 
Automation Testing - G1 conference Ch13.pptx
Automation Testing - G1 conference Ch13.pptxAutomation Testing - G1 conference Ch13.pptx
Automation Testing - G1 conference Ch13.pptx
 
CSS 101 - G1 conference Gurzu.pptx
CSS 101 - G1 conference Gurzu.pptxCSS 101 - G1 conference Gurzu.pptx
CSS 101 - G1 conference Gurzu.pptx
 
Discussion Regarding benefits on taxes on income from employment.pptx
Discussion Regarding benefits on taxes on income from employment.pptxDiscussion Regarding benefits on taxes on income from employment.pptx
Discussion Regarding benefits on taxes on income from employment.pptx
 
How not to Model Data - G1 conference.pptx
How not to Model Data - G1 conference.pptxHow not to Model Data - G1 conference.pptx
How not to Model Data - G1 conference.pptx
 
RTM and Test Closure Report Gurzu Inc.pptx
RTM and Test Closure Report Gurzu Inc.pptxRTM and Test Closure Report Gurzu Inc.pptx
RTM and Test Closure Report Gurzu Inc.pptx
 
API Testing.pptx
API Testing.pptxAPI Testing.pptx
API Testing.pptx
 
Building CI_CD for Mobile Development.pptx
Building CI_CD for Mobile Development.pptxBuilding CI_CD for Mobile Development.pptx
Building CI_CD for Mobile Development.pptx
 

Kürzlich hochgeladen

Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
Lovely Professional University
 
Final DBMS Manual (2).pdf final lab manual
Final DBMS Manual (2).pdf final lab manualFinal DBMS Manual (2).pdf final lab manual
Final DBMS Manual (2).pdf final lab manual
BalamuruganV28
 
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
drjose256
 
ALCOHOL PRODUCTION- Beer Brewing Process.pdf
ALCOHOL PRODUCTION- Beer Brewing Process.pdfALCOHOL PRODUCTION- Beer Brewing Process.pdf
ALCOHOL PRODUCTION- Beer Brewing Process.pdf
Madan Karki
 

Kürzlich hochgeladen (20)

Geometric constructions Engineering Drawing.pdf
Geometric constructions Engineering Drawing.pdfGeometric constructions Engineering Drawing.pdf
Geometric constructions Engineering Drawing.pdf
 
Developing a smart system for infant incubators using the internet of things ...
Developing a smart system for infant incubators using the internet of things ...Developing a smart system for infant incubators using the internet of things ...
Developing a smart system for infant incubators using the internet of things ...
 
SLIDESHARE PPT-DECISION MAKING METHODS.pptx
SLIDESHARE PPT-DECISION MAKING METHODS.pptxSLIDESHARE PPT-DECISION MAKING METHODS.pptx
SLIDESHARE PPT-DECISION MAKING METHODS.pptx
 
Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
 
Vip ℂall Girls Karkardooma Phone No 9999965857 High Profile ℂall Girl Delhi N...
Vip ℂall Girls Karkardooma Phone No 9999965857 High Profile ℂall Girl Delhi N...Vip ℂall Girls Karkardooma Phone No 9999965857 High Profile ℂall Girl Delhi N...
Vip ℂall Girls Karkardooma Phone No 9999965857 High Profile ℂall Girl Delhi N...
 
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdfInstruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
 
Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...
 
Final DBMS Manual (2).pdf final lab manual
Final DBMS Manual (2).pdf final lab manualFinal DBMS Manual (2).pdf final lab manual
Final DBMS Manual (2).pdf final lab manual
 
Autodesk Construction Cloud (Autodesk Build).pptx
Autodesk Construction Cloud (Autodesk Build).pptxAutodesk Construction Cloud (Autodesk Build).pptx
Autodesk Construction Cloud (Autodesk Build).pptx
 
The Entity-Relationship Model(ER Diagram).pptx
The Entity-Relationship Model(ER Diagram).pptxThe Entity-Relationship Model(ER Diagram).pptx
The Entity-Relationship Model(ER Diagram).pptx
 
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
 
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
 
UNIT-2 image enhancement.pdf Image Processing Unit 2 AKTU
UNIT-2 image enhancement.pdf Image Processing Unit 2 AKTUUNIT-2 image enhancement.pdf Image Processing Unit 2 AKTU
UNIT-2 image enhancement.pdf Image Processing Unit 2 AKTU
 
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas SachpazisSeismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
 
Dynamo Scripts for Task IDs and Space Naming.pptx
Dynamo Scripts for Task IDs and Space Naming.pptxDynamo Scripts for Task IDs and Space Naming.pptx
Dynamo Scripts for Task IDs and Space Naming.pptx
 
Electrical shop management system project report.pdf
Electrical shop management system project report.pdfElectrical shop management system project report.pdf
Electrical shop management system project report.pdf
 
ALCOHOL PRODUCTION- Beer Brewing Process.pdf
ALCOHOL PRODUCTION- Beer Brewing Process.pdfALCOHOL PRODUCTION- Beer Brewing Process.pdf
ALCOHOL PRODUCTION- Beer Brewing Process.pdf
 
handbook on reinforce concrete and detailing
handbook on reinforce concrete and detailinghandbook on reinforce concrete and detailing
handbook on reinforce concrete and detailing
 
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdflitvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
 
analog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptxanalog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptx
 

The Art of Refactoring | Asmit Ghimire | Gurzu.pdf

  • 1. THE ART OF REFACTORING ENHANCING CODE QUALITY AND MAINTAINABILITY Prepared By: Asmit Ghimire
  • 2. Introduction ➔ Refactoring is the process of restructuring code while not changing its original functionality. ➔ The main purpose of refactoring is to enhance the code's readability, maintainability, and overall quality, making it easier to understand and modify while reducing technical debt.
  • 3. Why Refactoring Matters ➔ Improved code quality / readability ➔ Maintainability ➔ Reduced technical debt ➔ Quicker issue diagnosis ➔ Enhanced team collaboration ➔ Improved extensibility ➔ Performance gain in some cases
  • 4. Signs It's Time to Refactor ➔ Code Duplication ➔ Long Methods / Functions ➔ Complex Conditional Statements ➔ Tight Coupling ➔ Performance Issues ➔ Changing Requirements ➔ Excessive Comments
  • 5. Refactoring Techniques ➔ Descriptive names to variables, methods, and classes ➔ Replace Magic Numbers with Named Constants ➔ Consolidate Conditional Expressions ➔ Introduce Explaining Variable ➔ Introduce Parameter Object ➔ Remove Dead Code ➔ Separate Concerns with Design Patterns ➔ Pull Up / Push Down Methods ➔ Replace Conditional with Polymorphism
  • 6. Pull Up Method ➔ Problem ◆ Your subclasses have methods that perform similar work. ➔ Solution ◆ Make the methods identical and then move them to the relevant superclass.
  • 7. Push Down Method ➔ Problem ◆ Is behavior implemented in a superclass used by only one (or a few) subclasses? ➔ Solution ◆ Move this behavior to the subclasses.
  • 8. Replace Conditionals with Polymorphism ➔ Problem ◆ You have a conditional that performs various actions depending on object type or properties. class Bird { // ... public function getSpeed() { switch ($this->type) { case EUROPEAN: return $this->getBaseSpeed(); case AFRICAN: return $this->getBaseSpeed() - $this->getLoadFactor() * $this->numberOfCoconuts; case NORWEGIAN_BLUE: return ($this->isNailed) ? 0 : $this->getBaseSpeed($this->voltage); } throw new Exception("Should be unreachable" ); } // ... }
  • 9. Replace Conditionals with Polymorphism ➔ Solution ◆ Create subclasses matching the branches of the conditional. ◆ In them, create a shared method and move code from the corresponding branch of the conditional to it. ◆ Then replace the conditional with the relevant method call. abstract class Bird { // ... abstract function getSpeed(); // ... } class European extends Bird { public function getSpeed() { return $this->getBaseSpeed(); } } class African extends Bird { public function getSpeed() { return $this->getBaseSpeed() - $this->getLoadFactor() * $this->numberOfCoconuts; } } class NorwegianBlue extends Bird { public function getSpeed() { return ($this->isNailed) ? 0 : $this->getBaseSpeed($this->voltage); } } // Somewhere in Client code. $speed = $bird->getSpeed();
  • 10. Steps to Successful Refactoring ➔ Identify the target area for refactoring. ➔ Understand the existing behavior and write tests. ➔ Apply the chosen refactoring technique. ➔ Run tests to verify correctness. ➔ Commit changes to version control.
  • 11. Tools and Resources ➔ SonarQube: Provides extensive static code analysis, detecting bugs, vulnerabilities, and code smells across multiple languages. ➔ CodeClimate: Analyzes code quality, security, and maintainability, offering insights and metrics.
  • 12. Challenges ➔ Time and Resources ➔ Risk of Introducing Bugs ➔ Lack of Automated Tests ➔ Legacy Code and Dependencies ➔ Team Buy-In ➔ Scope Creep ➔ Balancing Refactoring with New Features ➔ Resistance to Change ➔
  • 13. “Code refactoring is like doing the dishes: it's not fun, but leaving them all piled up will make things worse.”