SlideShare a Scribd company logo
Refactoring - Improving the smell of your code Vlad Mandrychenko October 2011
Agenda What is refactoring? Why refactor? When NOT to refactor? When to refactor? Code Smells How to refactor? Refactoring Tools
What is refactoring? Disciplined  technique for restructuring existing code without changing its external behavior. Series of  small (measured in minutes)  behavior preserving code transformations.
Why refactor? To make code easier to work with in the future  Speed up development Code is written once but is read many times Developers of all skill levels must be able to understand the code
Why refactor? To improve design  Improve reusability and remove duplication Allow for easier extensions and align code with functionality and usage Reduce complexity Improving code quality and rigidity, reduce bugs Simplify testing
Why refactor? Dramatically reduce  development  cost and headaches
When NOT to refactor? When it has no immediate business value Refactoring should be done as part of fixing a defect or adding new feature Code does not work Inadequate test coverage Breaking used interfaces Requires expensive data migrations  Tight deadline
When to refactor? During defect fix or addition of a new feature When code is hard to read and understand   When code requires complex unit tests   When upcoming changes are not easily supported by existing code   Existing code requires a change every time new feature is added   As result of code reviews
How to refactor Know your end goal Add missing unit tests Ensure unit tests pass before you start and in between each small refactoring Small, incremental, purposeful commits   Stop when you are unsure Backtrack  Pairing/Code Reviews
Refactoring and Design Patterns Go hand in hand Using patterns to improve existing design is better then using patterns in the new design   When designing new system, devs: Don't know all the requirements Don't have a full working application Guessing as to which patterns are actually applicable Tend to over-engineer
Code smell?  Code smell is a possible symptom of the deeper problem Duplicate code if   ( isSpecialDeal ())   {         total  =  price  *   0.95 ;         send();   }  else   {        total  =  price  *   0.98 ;        send();   } Long and complicated methods/classes public class PromotionFilterServiceImpl{      public LoyaltyProgramVO  filter (... ...){          // 1 method, 2  nested loops,  13   if  statements,  80  lines of code =  1000+  lines test  class      } }
Code smell?  Too many method params      public   void  calculate ( int   from ,  int   to ,  int   x ,  int   y ,  int  ... ){} Ungrouped related fields class  DayCalculator  {      private  Date to;        private  Date from;      private   boolean  skipSaturday;       private   boolean  skipSunday;          .....   } God classes class  ManagerServiceHelperImpl  {       public  BigInt  calculatePrice () {            //calculate stuff       }        public   void   handleResponse (){         //handle stuff       }        public  Report  manageReportPrinter (){          // manage stuff       }         public   boolean   isCanDoEverything ()     {           return true;     } }
Code smell?  Unused/temporary object fields public class SessionVO  {       private PartnerFeatureVO partnerFeatureVO  =   null ;     private ReserveCertificateVO reserveCertificateVO;  // only used for claim       private boolean giftOrTransfer;     ......     ......    } Complicated VOs and Data Classes public   class  Session VO   {      // contains 20 different nested mutable objects        // contains over 100 variables      // unknown lifecycle }
Code smells (cont'd) Numerous switch/if/else statements     public   double  calculateArea ( Object  shape )   {          double  area  =   0 ;          if  (shape  instanceof  Square) {             Square square  =   ( Square )  shape ;             area  =  square. getA ()   *  square. getA () ;          }  else   if  (shape  instanceof  Rectangle) {            Rectangle  rectangle  =   ( Rectangle )  shape ;             area  =  rectangle. getA ()   *  rectangle. getB () ;   }          } else   if  (shape  instanceof  Circle) {             Circle circle  =   ( Circle )  shape ;             area  =   Math . PI   *  cirle. getR ()   *  cirle. getR () ;          }        return  area ;       } Deep method chains     getHelper(){         getHandlerHelper(){             handleResponse(){                processReport();{                }             }         }     }
Code smells (cont'd) Comments class DistanceCalculator (){     // FIXME: rename this method       public int process(Coordinates coords){      //this method calculates the distance between 2 coordinates       ..... .     .....     } } Cascading change Small change in 1 place cascades into multiple changes in other parts of the code
Refactoring Tools IDE
How to refactor: catalog of techniques http://refactoring.com/catalog/index.html  
How to refactor: some techniques Rename Method class DistanceCalculator (){     // FIXME: rename this method       public int process(Coordinates coords){      //this method calculates the distance between 2 coordinates       ..... .     .....     } } class DistanceCalculator (){     public int calculateDistance(Coordinates coords){      ..... .     .....     } }
How to refactor: some techniques Extract Interface class Employee (){     double getRate(){ ... }     boolean hasSpecialSkill(){ ... }     getName (){ ... }     getDepartment(){ ... }     } interface Billable{     double getRate();     boolean hasSpecialSkill(); } class Employee  implements Billable() {} class Contractor  implements Billable() {} 
How to refactor: some techniques Introduce Parameter Object     public   void  calculate ( int   from ,  int   to ,  int   x ,  int   y ){ ... }     public   void  calculate ( Range range ,  Location location ){ ... }
How to refactor: some techniques Replace Conditional with Polymorphism public   class  Client  {          public   double  calculateArea ( Object  shape )   {          double  area  =   0 ;          if  (shape  instanceof  Square) {             Square square  =   ( Square )  shape ;             area  =  square. getA ()   *  square. getA () ;          }  else   if  (shape  instanceof  Rectangle) {            Rectangle  rectangle  =   ( Rectangle )  shape ;             area  =  rectangle. getA ()   *  rectangle. getB () ;   }          } else   if  (shape  instanceof  Circle) {             Circle circle  =   ( Circle )  shape ;             area  =   Math . PI   *  cirle. getR ()   *  cirle. getR () ;          }        return  area ;        } } public   class  Square  implements  Shape   {     private   double  a ;      ...          public   double   getArea ()   {         return  a  *  a ;       } } public class Rectangle  implements Shape  {     private double a;     private double b;     ...     public double  getArea () {        return a * b;     } } public class Client {     private Shape shape;     ...     public double calculateArea() {        return  shape.getArea();     } }
How to refactor: some techniques Replace Type Code with State/Strategy
How to refactor: some techniques Replace Inheritance with Delegation
Reference Material Books: M Fowler -  Refactoring: Improving the Design of Existing Code   Gang Of Four -  Design Patterns Joshua Karievsky -  Refactoring to Patterns Websites: refactoring.com https://mwiki.points.com/wiki/SoftwareEngineering
Ad

More Related Content

What's hot (17)

Csphtp1 09
Csphtp1 09Csphtp1 09
Csphtp1 09
HUST
 
Constructor
ConstructorConstructor
Constructor
poonamchopra7975
 
Constructor in c++
Constructor in c++Constructor in c++
Constructor in c++
Jay Patel
 
Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Csphtp1 08
Csphtp1 08Csphtp1 08
Csphtp1 08
HUST
 
Object Oriented Programming using C++ - Part 1
Object Oriented Programming using C++ - Part 1Object Oriented Programming using C++ - Part 1
Object Oriented Programming using C++ - Part 1
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
Envision Computer Training Institute
 
Csphtp1 16
Csphtp1 16Csphtp1 16
Csphtp1 16
HUST
 
Constructor and destructor
Constructor and destructorConstructor and destructor
Constructor and destructor
Selvin Josy Bai Somu
 
Object Oriented Programming using C++ - Part 5
Object Oriented Programming using C++ - Part 5Object Oriented Programming using C++ - Part 5
Object Oriented Programming using C++ - Part 5
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
Kumar Gaurav
 
CBSE Grade12, Computer Science, Sample Question Paper
CBSE Grade12, Computer Science, Sample Question PaperCBSE Grade12, Computer Science, Sample Question Paper
CBSE Grade12, Computer Science, Sample Question Paper
Malathi Senthil
 
Java basic understand OOP
Java basic understand OOPJava basic understand OOP
Java basic understand OOP
Habitamu Asimare
 
Cbse question-paper-computer-science-2009
Cbse question-paper-computer-science-2009Cbse question-paper-computer-science-2009
Cbse question-paper-computer-science-2009
Deepak Singh
 
麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)
ProCharm
 
Csphtp1 09
Csphtp1 09Csphtp1 09
Csphtp1 09
HUST
 
Constructor in c++
Constructor in c++Constructor in c++
Constructor in c++
Jay Patel
 
Csphtp1 08
Csphtp1 08Csphtp1 08
Csphtp1 08
HUST
 
Csphtp1 16
Csphtp1 16Csphtp1 16
Csphtp1 16
HUST
 
CBSE Grade12, Computer Science, Sample Question Paper
CBSE Grade12, Computer Science, Sample Question PaperCBSE Grade12, Computer Science, Sample Question Paper
CBSE Grade12, Computer Science, Sample Question Paper
Malathi Senthil
 
Cbse question-paper-computer-science-2009
Cbse question-paper-computer-science-2009Cbse question-paper-computer-science-2009
Cbse question-paper-computer-science-2009
Deepak Singh
 
麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)
ProCharm
 

Similar to Refactoring - improving the smell of your code (20)

Csphtp1 10
Csphtp1 10Csphtp1 10
Csphtp1 10
HUST
 
CDI in JEE6
CDI in JEE6CDI in JEE6
CDI in JEE6
PrasannaKumar Sathyanarayanan
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing Scenario
Tara Hardin
 
What’s new in .NET
What’s new in .NETWhat’s new in .NET
What’s new in .NET
Doommaker
 
Refactoring
RefactoringRefactoring
Refactoring
Tausun Akhtary
 
Cleaner Code - CodeStock 2019 Edition
Cleaner Code - CodeStock 2019 EditionCleaner Code - CodeStock 2019 Edition
Cleaner Code - CodeStock 2019 Edition
Dave Fancher
 
Visual studio 2008
Visual studio 2008Visual studio 2008
Visual studio 2008
Luis Enrique
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
Adam Stephensen
 
Functions in C++ programming language.pptx
Functions in  C++ programming language.pptxFunctions in  C++ programming language.pptx
Functions in C++ programming language.pptx
rebin5725
 
Chapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classChapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-class
Deepak Singh
 
Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)
Geeks Anonymes
 
JDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
JDD 2016 - Sebastian Malaca - You Dont Need Unit TestsJDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
JDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
PROIDEA
 
Cleaner Code: How Clean Code is Functional Code
Cleaner Code: How Clean Code is Functional CodeCleaner Code: How Clean Code is Functional Code
Cleaner Code: How Clean Code is Functional Code
Dave Fancher
 
Design patters java_meetup_slideshare [compatibility mode]
Design patters java_meetup_slideshare [compatibility mode]Design patters java_meetup_slideshare [compatibility mode]
Design patters java_meetup_slideshare [compatibility mode]
Dimitris Dranidis
 
Oops concept
Oops conceptOops concept
Oops concept
baabtra.com - No. 1 supplier of quality freshers
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
Stefano Fago
 
Core2 Document - Java SCORE Overview.pptx.pdf
Core2 Document - Java SCORE Overview.pptx.pdfCore2 Document - Java SCORE Overview.pptx.pdf
Core2 Document - Java SCORE Overview.pptx.pdf
ThchTrngGia
 
An Introduction to the SOLID Principles
An Introduction to the SOLID PrinciplesAn Introduction to the SOLID Principles
An Introduction to the SOLID Principles
Attila Bertók
 
JSLounge - TypeScript 소개
JSLounge - TypeScript 소개JSLounge - TypeScript 소개
JSLounge - TypeScript 소개
Reagan Hwang
 
Who killed object oriented design?
Who killed object oriented design?Who killed object oriented design?
Who killed object oriented design?
Amir Barylko
 
Csphtp1 10
Csphtp1 10Csphtp1 10
Csphtp1 10
HUST
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing Scenario
Tara Hardin
 
What’s new in .NET
What’s new in .NETWhat’s new in .NET
What’s new in .NET
Doommaker
 
Cleaner Code - CodeStock 2019 Edition
Cleaner Code - CodeStock 2019 EditionCleaner Code - CodeStock 2019 Edition
Cleaner Code - CodeStock 2019 Edition
Dave Fancher
 
Visual studio 2008
Visual studio 2008Visual studio 2008
Visual studio 2008
Luis Enrique
 
Functions in C++ programming language.pptx
Functions in  C++ programming language.pptxFunctions in  C++ programming language.pptx
Functions in C++ programming language.pptx
rebin5725
 
Chapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classChapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-class
Deepak Singh
 
Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)
Geeks Anonymes
 
JDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
JDD 2016 - Sebastian Malaca - You Dont Need Unit TestsJDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
JDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
PROIDEA
 
Cleaner Code: How Clean Code is Functional Code
Cleaner Code: How Clean Code is Functional CodeCleaner Code: How Clean Code is Functional Code
Cleaner Code: How Clean Code is Functional Code
Dave Fancher
 
Design patters java_meetup_slideshare [compatibility mode]
Design patters java_meetup_slideshare [compatibility mode]Design patters java_meetup_slideshare [compatibility mode]
Design patters java_meetup_slideshare [compatibility mode]
Dimitris Dranidis
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
Stefano Fago
 
Core2 Document - Java SCORE Overview.pptx.pdf
Core2 Document - Java SCORE Overview.pptx.pdfCore2 Document - Java SCORE Overview.pptx.pdf
Core2 Document - Java SCORE Overview.pptx.pdf
ThchTrngGia
 
An Introduction to the SOLID Principles
An Introduction to the SOLID PrinciplesAn Introduction to the SOLID Principles
An Introduction to the SOLID Principles
Attila Bertók
 
JSLounge - TypeScript 소개
JSLounge - TypeScript 소개JSLounge - TypeScript 소개
JSLounge - TypeScript 소개
Reagan Hwang
 
Who killed object oriented design?
Who killed object oriented design?Who killed object oriented design?
Who killed object oriented design?
Amir Barylko
 
Ad

Recently uploaded (20)

Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Ad

Refactoring - improving the smell of your code

  • 1. Refactoring - Improving the smell of your code Vlad Mandrychenko October 2011
  • 2. Agenda What is refactoring? Why refactor? When NOT to refactor? When to refactor? Code Smells How to refactor? Refactoring Tools
  • 3. What is refactoring? Disciplined  technique for restructuring existing code without changing its external behavior. Series of small (measured in minutes) behavior preserving code transformations.
  • 4. Why refactor? To make code easier to work with in the future  Speed up development Code is written once but is read many times Developers of all skill levels must be able to understand the code
  • 5. Why refactor? To improve design  Improve reusability and remove duplication Allow for easier extensions and align code with functionality and usage Reduce complexity Improving code quality and rigidity, reduce bugs Simplify testing
  • 6. Why refactor? Dramatically reduce  development  cost and headaches
  • 7. When NOT to refactor? When it has no immediate business value Refactoring should be done as part of fixing a defect or adding new feature Code does not work Inadequate test coverage Breaking used interfaces Requires expensive data migrations  Tight deadline
  • 8. When to refactor? During defect fix or addition of a new feature When code is hard to read and understand   When code requires complex unit tests   When upcoming changes are not easily supported by existing code   Existing code requires a change every time new feature is added   As result of code reviews
  • 9. How to refactor Know your end goal Add missing unit tests Ensure unit tests pass before you start and in between each small refactoring Small, incremental, purposeful commits   Stop when you are unsure Backtrack  Pairing/Code Reviews
  • 10. Refactoring and Design Patterns Go hand in hand Using patterns to improve existing design is better then using patterns in the new design   When designing new system, devs: Don't know all the requirements Don't have a full working application Guessing as to which patterns are actually applicable Tend to over-engineer
  • 11. Code smell?  Code smell is a possible symptom of the deeper problem Duplicate code if ( isSpecialDeal ()) {         total = price * 0.95 ;         send();   }  else {       total = price * 0.98 ;       send();   } Long and complicated methods/classes public class PromotionFilterServiceImpl{     public LoyaltyProgramVO filter (... ...){         // 1 method, 2  nested loops,  13   if  statements,  80  lines of code =  1000+  lines test  class      } }
  • 12. Code smell?  Too many method params     public void calculate ( int from , int to , int x , int y , int ... ){} Ungrouped related fields class DayCalculator  {     private Date to;       private  Date from;     private boolean skipSaturday;      private boolean skipSunday;         .....   } God classes class  ManagerServiceHelperImpl  {       public BigInt calculatePrice () {           //calculate stuff       }        public void handleResponse (){         //handle stuff       }       public Report manageReportPrinter (){          // manage stuff       }        public boolean isCanDoEverything ()     {           return true;     } }
  • 13. Code smell?  Unused/temporary object fields public class SessionVO {       private PartnerFeatureVO partnerFeatureVO = null ;     private ReserveCertificateVO reserveCertificateVO; // only used for claim       private boolean giftOrTransfer;     ......     ......    } Complicated VOs and Data Classes public class Session VO {     // contains 20 different nested mutable objects       // contains over 100 variables     // unknown lifecycle }
  • 14. Code smells (cont'd) Numerous switch/if/else statements     public double calculateArea ( Object shape )   {         double area = 0 ;         if (shape instanceof Square) {             Square square = ( Square ) shape ;             area = square. getA () * square. getA () ;          } else if (shape instanceof Rectangle) {            Rectangle rectangle = ( Rectangle ) shape ;             area = rectangle. getA () * rectangle. getB () ; }         } else if (shape instanceof Circle) {             Circle circle = ( Circle ) shape ;             area = Math . PI * cirle. getR () * cirle. getR () ;         }       return area ;       } Deep method chains     getHelper(){         getHandlerHelper(){             handleResponse(){               processReport();{               }             }         }     }
  • 15. Code smells (cont'd) Comments class DistanceCalculator (){     // FIXME: rename this method       public int process(Coordinates coords){      //this method calculates the distance between 2 coordinates       ..... .     .....     } } Cascading change Small change in 1 place cascades into multiple changes in other parts of the code
  • 17. How to refactor: catalog of techniques http://refactoring.com/catalog/index.html  
  • 18. How to refactor: some techniques Rename Method class DistanceCalculator (){     // FIXME: rename this method       public int process(Coordinates coords){      //this method calculates the distance between 2 coordinates       ..... .     .....     } } class DistanceCalculator (){     public int calculateDistance(Coordinates coords){      ..... .     .....     } }
  • 19. How to refactor: some techniques Extract Interface class Employee (){     double getRate(){ ... }     boolean hasSpecialSkill(){ ... }     getName (){ ... }     getDepartment(){ ... }     } interface Billable{     double getRate();     boolean hasSpecialSkill(); } class Employee implements Billable() {} class Contractor implements Billable() {} 
  • 20. How to refactor: some techniques Introduce Parameter Object     public   void  calculate ( int   from ,  int   to ,  int   x ,  int   y ){ ... }     public   void  calculate ( Range range ,  Location location ){ ... }
  • 21. How to refactor: some techniques Replace Conditional with Polymorphism public class Client {          public   double  calculateArea ( Object  shape )   {         double  area  =   0 ;         if  (shape  instanceof  Square) {             Square square  =   ( Square )  shape ;             area  =  square. getA ()   *  square. getA () ;          }  else   if  (shape  instanceof  Rectangle) {            Rectangle  rectangle  =   ( Rectangle )  shape ;             area  =  rectangle. getA ()   *  rectangle. getB () ;   }         } else   if  (shape  instanceof  Circle) {             Circle circle  =   ( Circle )  shape ;             area  =   Math . PI   *  cirle. getR ()   *  cirle. getR () ;         }       return  area ;        } } public class Square implements Shape   {     private double a ;      ...          public double getArea ()   {        return a * a ;       } } public class Rectangle implements Shape {     private double a;     private double b;     ...     public double getArea () {       return a * b;     } } public class Client {     private Shape shape;     ...     public double calculateArea() {       return shape.getArea();     } }
  • 22. How to refactor: some techniques Replace Type Code with State/Strategy
  • 23. How to refactor: some techniques Replace Inheritance with Delegation
  • 24. Reference Material Books: M Fowler - Refactoring: Improving the Design of Existing Code   Gang Of Four - Design Patterns Joshua Karievsky - Refactoring to Patterns Websites: refactoring.com https://mwiki.points.com/wiki/SoftwareEngineering