SlideShare una empresa de Scribd logo
1 de 31
Refactoring
Improving the design of existing code
By Deepak Mehra & Mayank Bairagi
1
Agenda
● What is Refactoring ?
● Why Should You Refactor?
● When Should You Refactor?
● Why Refactoring Works?
● Process of Refactoring
● Bad smells in code
● Examples of Refactoring
2
What is Refactoring?
3
What is Refactoring?
a change made to the internal structure of software to
make it easier to understand and cheaper to modify
without changing its observable behavior.
4
The Two Hats
5
Why Should You Refactor?
★ Refactoring Improves the Design of Software.
6
Why Should You Refactor?
★ Refactoring Improves the Design of Software.
★ Refactoring Makes Software Easier to Understand.
7
early refactorings is like wiping the dirt off a window so you can see beyond.
-Ralph Johnson
8
Why Should You Refactor?
★ Refactoring Improves the Design of Software.
★ Refactoring Makes Software Easier to Understand.
★ Refactoring Helps You Program Faster.
9
When Should You Refactor?
★ Refactor When You Add Function
★ Refactor When You Need to Fix a Bug
★ Refactor As You Do a Code Review
10
Why Refactoring Works
Refactoring emphasize on what program can do for you tomorrow.
11
Programs, which are hard to work with
★ Programs that are hard to read are hard to modify.
★ Programs that have duplicated logic are hard to modify.
★ Programs that require additional behavior that requires you to change
running code are hard to modify.
★ Programs with complex conditional logic are hard to modif
12
Clutter Code
13
Clutter Code
Anything in your code that doesn't add value
14
What Do I Tell My Manager?
15
What Do I Tell My Manager?
Don't Tell
16
Process of Refactoring
● Detect a problem
Is there a problem? What is the problem?
● Characterise the problem
Why is it necessary to change something? What are the benefits? Are
there any risks?
● Design a solution
What should be the "goal state" of the code? Which code
transformation(s) will move the code towards the desired state?
● Modify the code
Steps that will carry out the code transformation(s) that leave the code
functioning the same way as it did before.
17
Bad smells in code
● Duplicated code
● Long method
● Large Class
● Long Parameter List
● Lazy Class
18
Examples of Refactoring
● Rename
Methods, variables, classes or other java items. Changing the name of
a Java item to make it less confusing and misleading.
● Move Class
Moving a class into a package where it would fit better. All import
statements should refer to the given class.
● Extract Method
Break up long methods to improve readability and maintainability.
Replace a section of code that accomplishes a single task with a new
method with a descriptive name. This will also allow methods to be
reused for a specific function.
19
Examples of Refactoring
● Inline Method
A method’s body is just as clear as its name. Put the method’s body
into the body of its callers and remove the method.
20
Examples of Refactoring
● Remove Assignments to Parameters
The code assigns to a parameter. Use a temporary variable instead.
● Extract Class
You have one class doing work that should be done by two. Create a
new class and move the relevant fields and methods from the old class
into the new class.
21
Examples of Refactoring
● Introduce Local Extension
A server class you are using needs several additional methods, but you
can't modify the class. Create a new class that contains these extra
methods. Make this extension class a subclass or a wrapper of the
original.
So the idea is, If want to add features to a library what you would do?
If you can modify the source that’s the best thing, If you cannot modify the
source then you can always add in a wrapper to it.
22
Examples of Refactoring
● Replace array with Object
You have an array in which certain elements mean different things.
Replace the array with an object that has a field for each element.
String[] row = new String[3];
row[0] = “Liverpool”;
row[1] = “15”;
Instead
Team team = new Team();
team.setName(“Liverpool”);
team.setWins(“15”);
23
Examples of Refactoring
● Replace Magic Number with Symbolic Constant
You have a literal number with a particular meaning. Create a constant,
name it after the meaning, and replace the number with it.
double potentialEnergy(double mass, double height) {
return mass * 9.81 * height;
}
double potentialEnergy(double mass, double height) {
return mass * GRAVITATIONAL_CONSTANT * height;
}
static final double GRAVITATIONAL_CONSTANT = 9.81;
24
Examples of Refactoring
● Decompose Conditional
You have a complicated conditional (if-then-else) statement.
Extract methods from the condition, then part, and else parts.
if (date.before (SUMMER_START) || date.after(SUMMER_END))
charge = quantity * _winterRate + _winterServiceCharge;
else charge = quantity * _summerRate;
Refactored to
if (notSummer(date))
charge = winterCharge(quantity);
else charge = summerCharge (quantity);
25
Examples of Refactoring
● Remove setting method
A field should be set at creation time and never altered. Remove any
setting method for that field.
26
Examples of Refactoring
● Replace error code with exception
A method returns a special code to indicate an error.
int withdraw(int amount) {
if (amount > _balance)
return -1;
else {
_balance -= amount;
return 0;
}
}
27
Examples of Refactoring
● Replace error code with exception
A method returns a special code to indicate an error.
void withdraw(int amount) throws BalanceException {
if (amount > _balance) throw new BalanceException();
_balance -= amount;
}
28
When we should not Refactor?
● There are times when existing code is such a mess that although you
could refactor it, it would be easier to start from the beginning.
● The other time you should avoid refactoring is, when you are close to a
deadline. At that point the productivity gain from refactoring would
appear after the deadline and thus be too late.
29
References
● https://www.slideshare.net/redigon/refactoring-1658371
● Book by Martin Fowler on Refactoring
30
Thank you
31

Más contenido relacionado

La actualidad más candente

Software Quality Attributes
Software Quality AttributesSoftware Quality Attributes
Software Quality AttributesHayim Makabee
 
Refactoring Techniques
Refactoring TechniquesRefactoring Techniques
Refactoring TechniquesMayada Ghanem
 
Code refactoring
Code refactoringCode refactoring
Code refactoringLalit Kale
 
Agile software development and extreme Programming
Agile software development and extreme Programming  Agile software development and extreme Programming
Agile software development and extreme Programming Fatemeh Karimi
 
extreme Programming
extreme Programmingextreme Programming
extreme ProgrammingBilal Shah
 
The Extreme Programming (XP) Model
The Extreme Programming (XP) ModelThe Extreme Programming (XP) Model
The Extreme Programming (XP) ModelDamian T. Gordon
 
Unit testing on embedded target with C++Test
Unit testing on embedded  target with C++TestUnit testing on embedded  target with C++Test
Unit testing on embedded target with C++TestEngineering Software Lab
 
Capability Maturity Model (CMM) in Software Engineering
Capability Maturity Model (CMM) in Software EngineeringCapability Maturity Model (CMM) in Software Engineering
Capability Maturity Model (CMM) in Software EngineeringFaizanAhmad340414
 
Test driven development
Test driven developmentTest driven development
Test driven developmentNascenia IT
 
Continuous Delivery, Continuous Integration
Continuous Delivery, Continuous Integration Continuous Delivery, Continuous Integration
Continuous Delivery, Continuous Integration Amazon Web Services
 
Agile Methodology PPT
Agile Methodology PPTAgile Methodology PPT
Agile Methodology PPTMohit Kumar
 
What is agile model?Working of agile model
What is agile model?Working of agile modelWhat is agile model?Working of agile model
What is agile model?Working of agile modelzoomers
 
Introduction to DevOps | Edureka
Introduction to DevOps | EdurekaIntroduction to DevOps | Edureka
Introduction to DevOps | EdurekaEdureka!
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentNaresh Jain
 

La actualidad más candente (20)

Software Quality Attributes
Software Quality AttributesSoftware Quality Attributes
Software Quality Attributes
 
Refactoring Techniques
Refactoring TechniquesRefactoring Techniques
Refactoring Techniques
 
CI CD Basics
CI CD BasicsCI CD Basics
CI CD Basics
 
The Software Development Process
The Software Development ProcessThe Software Development Process
The Software Development Process
 
Code refactoring
Code refactoringCode refactoring
Code refactoring
 
Agile software development and extreme Programming
Agile software development and extreme Programming  Agile software development and extreme Programming
Agile software development and extreme Programming
 
extreme Programming
extreme Programmingextreme Programming
extreme Programming
 
The Extreme Programming (XP) Model
The Extreme Programming (XP) ModelThe Extreme Programming (XP) Model
The Extreme Programming (XP) Model
 
Unit testing on embedded target with C++Test
Unit testing on embedded  target with C++TestUnit testing on embedded  target with C++Test
Unit testing on embedded target with C++Test
 
Capability Maturity Model (CMM) in Software Engineering
Capability Maturity Model (CMM) in Software EngineeringCapability Maturity Model (CMM) in Software Engineering
Capability Maturity Model (CMM) in Software Engineering
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Continuous Delivery, Continuous Integration
Continuous Delivery, Continuous Integration Continuous Delivery, Continuous Integration
Continuous Delivery, Continuous Integration
 
Refactoring
RefactoringRefactoring
Refactoring
 
Automation testing
Automation testingAutomation testing
Automation testing
 
Software Quality Metrics
Software Quality MetricsSoftware Quality Metrics
Software Quality Metrics
 
Agile Methodology PPT
Agile Methodology PPTAgile Methodology PPT
Agile Methodology PPT
 
Devops
DevopsDevops
Devops
 
What is agile model?Working of agile model
What is agile model?Working of agile modelWhat is agile model?Working of agile model
What is agile model?Working of agile model
 
Introduction to DevOps | Edureka
Introduction to DevOps | EdurekaIntroduction to DevOps | Edureka
Introduction to DevOps | Edureka
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 

Similar a Refactoring: Improving the design of existing code

Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerIgor Crvenov
 
Refactoring: Improve the design of existing code
Refactoring: Improve the design of existing codeRefactoring: Improve the design of existing code
Refactoring: Improve the design of existing codeValerio Maggio
 
Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Code Smells and Refactoring - Satyajit Dey & Ashif IqbalCode Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Code Smells and Refactoring - Satyajit Dey & Ashif IqbalCefalo
 
From Good to SOLID: How to become a better PHP developer
From Good to SOLID: How to become a better PHP developerFrom Good to SOLID: How to become a better PHP developer
From Good to SOLID: How to become a better PHP developerKaterina Trajchevska
 
A New Architecture Reconciling Refactorings and Transformations
A New Architecture Reconciling Refactorings and TransformationsA New Architecture Reconciling Refactorings and Transformations
A New Architecture Reconciling Refactorings and TransformationsESUG
 
Keeping code clean
Keeping code cleanKeeping code clean
Keeping code cleanBrett Child
 
Software Design Principles and Best Practices - Satyajit Dey
Software Design Principles and Best Practices - Satyajit DeySoftware Design Principles and Best Practices - Satyajit Dey
Software Design Principles and Best Practices - Satyajit DeyCefalo
 
Refactoring, Therapeutic Attitude to Programming.
Refactoring, Therapeutic Attitude to Programming.Refactoring, Therapeutic Attitude to Programming.
Refactoring, Therapeutic Attitude to Programming.Amin Shahnazari
 
Refactoring workshop
Refactoring workshop Refactoring workshop
Refactoring workshop Itzik Saban
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And RefactoringNaresh Jain
 
Agile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddAgile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddSrinivasa GV
 
Refactoring 101
Refactoring 101Refactoring 101
Refactoring 101Adam Culp
 
The Power Of Refactoring (php|tek 09)
The Power Of Refactoring (php|tek 09)The Power Of Refactoring (php|tek 09)
The Power Of Refactoring (php|tek 09)Stefan Koopmanschap
 
Refactoring PHP
Refactoring PHPRefactoring PHP
Refactoring PHPAdam Culp
 
Ddc2011 효과적으로레거시코드다루기
Ddc2011 효과적으로레거시코드다루기Ddc2011 효과적으로레거시코드다루기
Ddc2011 효과적으로레거시코드다루기Myeongseok Baek
 

Similar a Refactoring: Improving the design of existing code (20)

Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin Fowler
 
Refactoring: Improve the design of existing code
Refactoring: Improve the design of existing codeRefactoring: Improve the design of existing code
Refactoring: Improve the design of existing code
 
Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Code Smells and Refactoring - Satyajit Dey & Ashif IqbalCode Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal
 
31 days Refactoring
31 days Refactoring31 days Refactoring
31 days Refactoring
 
From Good to SOLID: How to become a better PHP developer
From Good to SOLID: How to become a better PHP developerFrom Good to SOLID: How to become a better PHP developer
From Good to SOLID: How to become a better PHP developer
 
A New Architecture Reconciling Refactorings and Transformations
A New Architecture Reconciling Refactorings and TransformationsA New Architecture Reconciling Refactorings and Transformations
A New Architecture Reconciling Refactorings and Transformations
 
Keeping code clean
Keeping code cleanKeeping code clean
Keeping code clean
 
Instant DBMS Homework Help
Instant DBMS Homework HelpInstant DBMS Homework Help
Instant DBMS Homework Help
 
Software Design Principles and Best Practices - Satyajit Dey
Software Design Principles and Best Practices - Satyajit DeySoftware Design Principles and Best Practices - Satyajit Dey
Software Design Principles and Best Practices - Satyajit Dey
 
Refactoring, Therapeutic Attitude to Programming.
Refactoring, Therapeutic Attitude to Programming.Refactoring, Therapeutic Attitude to Programming.
Refactoring, Therapeutic Attitude to Programming.
 
Refactoring workshop
Refactoring workshop Refactoring workshop
Refactoring workshop
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
 
Agile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddAgile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tdd
 
Design p atterns
Design p atternsDesign p atterns
Design p atterns
 
Refactoring 101
Refactoring 101Refactoring 101
Refactoring 101
 
The Power Of Refactoring (php|tek 09)
The Power Of Refactoring (php|tek 09)The Power Of Refactoring (php|tek 09)
The Power Of Refactoring (php|tek 09)
 
Vue.js Use Cases
Vue.js Use CasesVue.js Use Cases
Vue.js Use Cases
 
Facade Design Pattern
Facade Design PatternFacade Design Pattern
Facade Design Pattern
 
Refactoring PHP
Refactoring PHPRefactoring PHP
Refactoring PHP
 
Ddc2011 효과적으로레거시코드다루기
Ddc2011 효과적으로레거시코드다루기Ddc2011 효과적으로레거시코드다루기
Ddc2011 효과적으로레거시코드다루기
 

Más de Knoldus Inc.

Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxKnoldus Inc.
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingKnoldus Inc.
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionKnoldus Inc.
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxKnoldus Inc.
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptxKnoldus Inc.
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfKnoldus Inc.
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxKnoldus Inc.
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingKnoldus Inc.
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesKnoldus Inc.
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxKnoldus Inc.
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxKnoldus Inc.
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxKnoldus Inc.
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxKnoldus Inc.
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxKnoldus Inc.
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationKnoldus Inc.
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationKnoldus Inc.
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIsKnoldus Inc.
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II PresentationKnoldus Inc.
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAKnoldus Inc.
 

Más de Knoldus Inc. (20)

Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 

Último

Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsBert Jan Schrijver
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...Nitya salvi
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburgmasabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...masabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 

Último (20)

Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 

Refactoring: Improving the design of existing code

  • 1. Refactoring Improving the design of existing code By Deepak Mehra & Mayank Bairagi 1
  • 2. Agenda ● What is Refactoring ? ● Why Should You Refactor? ● When Should You Refactor? ● Why Refactoring Works? ● Process of Refactoring ● Bad smells in code ● Examples of Refactoring 2
  • 4. What is Refactoring? a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior. 4
  • 6. Why Should You Refactor? ★ Refactoring Improves the Design of Software. 6
  • 7. Why Should You Refactor? ★ Refactoring Improves the Design of Software. ★ Refactoring Makes Software Easier to Understand. 7
  • 8. early refactorings is like wiping the dirt off a window so you can see beyond. -Ralph Johnson 8
  • 9. Why Should You Refactor? ★ Refactoring Improves the Design of Software. ★ Refactoring Makes Software Easier to Understand. ★ Refactoring Helps You Program Faster. 9
  • 10. When Should You Refactor? ★ Refactor When You Add Function ★ Refactor When You Need to Fix a Bug ★ Refactor As You Do a Code Review 10
  • 11. Why Refactoring Works Refactoring emphasize on what program can do for you tomorrow. 11
  • 12. Programs, which are hard to work with ★ Programs that are hard to read are hard to modify. ★ Programs that have duplicated logic are hard to modify. ★ Programs that require additional behavior that requires you to change running code are hard to modify. ★ Programs with complex conditional logic are hard to modif 12
  • 14. Clutter Code Anything in your code that doesn't add value 14
  • 15. What Do I Tell My Manager? 15
  • 16. What Do I Tell My Manager? Don't Tell 16
  • 17. Process of Refactoring ● Detect a problem Is there a problem? What is the problem? ● Characterise the problem Why is it necessary to change something? What are the benefits? Are there any risks? ● Design a solution What should be the "goal state" of the code? Which code transformation(s) will move the code towards the desired state? ● Modify the code Steps that will carry out the code transformation(s) that leave the code functioning the same way as it did before. 17
  • 18. Bad smells in code ● Duplicated code ● Long method ● Large Class ● Long Parameter List ● Lazy Class 18
  • 19. Examples of Refactoring ● Rename Methods, variables, classes or other java items. Changing the name of a Java item to make it less confusing and misleading. ● Move Class Moving a class into a package where it would fit better. All import statements should refer to the given class. ● Extract Method Break up long methods to improve readability and maintainability. Replace a section of code that accomplishes a single task with a new method with a descriptive name. This will also allow methods to be reused for a specific function. 19
  • 20. Examples of Refactoring ● Inline Method A method’s body is just as clear as its name. Put the method’s body into the body of its callers and remove the method. 20
  • 21. Examples of Refactoring ● Remove Assignments to Parameters The code assigns to a parameter. Use a temporary variable instead. ● Extract Class You have one class doing work that should be done by two. Create a new class and move the relevant fields and methods from the old class into the new class. 21
  • 22. Examples of Refactoring ● Introduce Local Extension A server class you are using needs several additional methods, but you can't modify the class. Create a new class that contains these extra methods. Make this extension class a subclass or a wrapper of the original. So the idea is, If want to add features to a library what you would do? If you can modify the source that’s the best thing, If you cannot modify the source then you can always add in a wrapper to it. 22
  • 23. Examples of Refactoring ● Replace array with Object You have an array in which certain elements mean different things. Replace the array with an object that has a field for each element. String[] row = new String[3]; row[0] = “Liverpool”; row[1] = “15”; Instead Team team = new Team(); team.setName(“Liverpool”); team.setWins(“15”); 23
  • 24. Examples of Refactoring ● Replace Magic Number with Symbolic Constant You have a literal number with a particular meaning. Create a constant, name it after the meaning, and replace the number with it. double potentialEnergy(double mass, double height) { return mass * 9.81 * height; } double potentialEnergy(double mass, double height) { return mass * GRAVITATIONAL_CONSTANT * height; } static final double GRAVITATIONAL_CONSTANT = 9.81; 24
  • 25. Examples of Refactoring ● Decompose Conditional You have a complicated conditional (if-then-else) statement. Extract methods from the condition, then part, and else parts. if (date.before (SUMMER_START) || date.after(SUMMER_END)) charge = quantity * _winterRate + _winterServiceCharge; else charge = quantity * _summerRate; Refactored to if (notSummer(date)) charge = winterCharge(quantity); else charge = summerCharge (quantity); 25
  • 26. Examples of Refactoring ● Remove setting method A field should be set at creation time and never altered. Remove any setting method for that field. 26
  • 27. Examples of Refactoring ● Replace error code with exception A method returns a special code to indicate an error. int withdraw(int amount) { if (amount > _balance) return -1; else { _balance -= amount; return 0; } } 27
  • 28. Examples of Refactoring ● Replace error code with exception A method returns a special code to indicate an error. void withdraw(int amount) throws BalanceException { if (amount > _balance) throw new BalanceException(); _balance -= amount; } 28
  • 29. When we should not Refactor? ● There are times when existing code is such a mess that although you could refactor it, it would be easier to start from the beginning. ● The other time you should avoid refactoring is, when you are close to a deadline. At that point the productivity gain from refactoring would appear after the deadline and thus be too late. 29

Notas del editor

  1. Is refactoring just cleaning up code?No, It is cleaning up code in more efficient and controlled manner.Only changes made to make code "easy to understand" are refactoring. A good contrast is performance optimization. Like refactoring PO doesn't change the behaviour of the software (other than speed). It only ulter the internal structure, However purpose is different.
  2. As you develop software, you probably find yourself swapping hats frequently. You start by trying to add a new function, and you realize this would be much easier if the code were structured differently. So you swap hats and refactor for a while. Once the code is better structured, you swap hats and add the new function. Once you get the new function working, you realize you coded it in a way that's awkward to understand, so you swap hats again and refactor
  3. Without refactoring, the design of the program will decay. As people change code—changes to realize short-term goals or changes made without a full comprehension of the design of the code—the code loses its structure.It becomes harder to see the design by reading the code.
  4. Computer responds by doing exactly what you tell it. In time you close the gap between what you want it to do and what you tell it to do. Programming in this mode is all about saying exactly what you want. But there is another user of your source code. Someone will try to read your code in a few months'time to make some changes. We easily forget that extra user of the code, yet that user is actually the most important. When refactoring you have code that works but is not ideally structured. A little time spent refactoring can make the code better communicate its purpose. Programming in this mode is all about saying exactly what you mean.
  5. This sounds counterintuitive. When I talk about refactoring, people can easily see that it improves quality. Improving design, improving readability, reducing bugs, all these improve quality. But doesn't all this reduce the speed of development? I strongly believe that a good design is essential for rapid software development. Indeed, the whole point of having a good design is to allow rapid development. Without a good design, you can progress quickly for a while, but soon the poor design starts to slow you down. You spend time finding and fixing bugs instead of adding new function. Changes take longer as you try to understand the system and find the duplicate code. New features need more coding as you patch over a patch that patches a patch on the original code base.
  6. Programs have two kinds of value: what they can do for you today and what they can do for you tomorrow. Most times when we are programming, we are focused on what we want the program to do today. Whether we are fixing a bug or adding a feature, we are making today's program more valuable by making it more capable. You can't program long without realizing that what the system does today is only a part of the story. If you can get today's work done today, but you do it in such a way that you can't possibly get tomorrow's work done tomorrow, then you lose. Notice, though, that you know what you need to do today, but you're not quite sure about tomorrow. Maybe you'll do this, maybe that, maybe something you haven't imagined yet. I know enough to do today's work. I don't know enough to do tomorrow's. But if I only work for today, I won't be able to work tomorrow at all
  7. Subversive? I don't think so.A schedule-driven manager wants me to do things the fastest way I can; how I do it is my business. The fastest way is to refactor; therefore I refactor
  8. Subversive? I don't think so.A schedule-driven manager wants me to do things the fastest way I can; how I do it is my business. The fastest way is to refactor; therefore I refactor
  9. Code smells 1. Duplicated Code - if you see the same code structure in more than one place, then all you to have to do is Extract method. 2. Large class = when a class is trying to do too much 3. Long parameter lst = long parameter list are haard to understand. 4.Lazy class - Each class you create costs money to maintain and understand. A class that isn't doing enough to pay for itself should be eliminated.
  10. The other area of confusion is within the body of the code itself. It is much clearer if you use only the parameter to represent what has been passed in, because that is a consistent usage.You have to decide how to split the reponsibility of the class.
  11. Create an extension class either as a subclass or a wrapper of the original. Add new features to the extension.
  12. Create an extension class either as a subclass or a wrapper of the original. Add new features to the extension.
  13. When you need to reference to the same logical number in more than one place and if the number ever changes, making the change everywhere will be a nightmare.
  14. Decompose conditionals as much as possible
  15. Providing a setting method indicates that a field may be changed. If you don't want that field to change once the object is created, then don't provide a setting method (and make the field final).