SlideShare a Scribd company logo
1 of 30
Download to read offline
Refactoring
1
‣ Refactoring is the process of changing a software
system in such a way that it does not* alter the
external behavior of the code yet improves its
internal structure [Fowler et al.; 2002]
‣ The art of safely* improving the design of existing
code [Fowler et al.; 2009]
*Importance of Testing in Refactoring 2
Definition
‣ Refactoring (noun): A change made to the
internal structure of software to make it easier to
understand and cheaper to modify without
changing its observable behavior
‣ Refactor (verb): To restructure software by
applying a series of refactorings without changing
its observable behavior 3
Definition
‣ Refactoring does not include any functional
change to the system
‣ Refactoring is not “Rewriting from scratch”
‣ Refactoring is not just any restructuring
intended to improve the code
4
Refactoring is not
‣ Start with an existing code and make it better
‣ Change the internal structure while preserving
the overall semantics
‣ Refactoring changes the programs in small steps
If you make a mistake, it is easy to find the bug
5
Refactoring is
‣ Improves Quality of the Code
‣ Improves Maintainability while reducing Coupling
‣ Improves the Design of Software
‣ Makes Software Easier to Understand
‣ Helps You Find Bugs
6
Benefits
‣ Refactor When You Add Function
‣ Refactor When You Need to Fix a Bug
‣ Refactor As You Do a Code Review
‣ Refactoring for Greater Understanding
The third time you do something similar, you refactor
7
When
‣ Changing Interfaces
Don’t publish interfaces prematurely. Modify your
code ownership policies to smooth refactoring
‣ Databases
‣ Design Changes That Are Difficult to Refactor
‣ When Shouldn’t You Refactor?
‣ It Takes A While to Create Nothing
‣ Refactoring and Performance 8
Problems with refactoring
[Pytel et al.; 2010]
class Address < ActiveRecord::Base
belongs_to :customer
end
class Customer < ActiveRecord::Base
has_one :address
has_many :invoices
end
class Invoice < ActiveRecord::Base
belongs_to :customer
end 9
AntiPattern: Voyeuristic Models
<%= @invoice.customer.name %>
<%= @invoice.customer.address.street %>
<%= @invoice.customer.address.city %>,
<%= @invoice.customer.address.state %>
<%= @invoice.customer.address.zip_code %>
10
AntiPattern: Voyeuristic Models
class Customer < ActiveRecord::Base
has_one :address
has_many :invoices
def street
Address.street
end
def city
Address.city
end
def state
Address.state
end
def zip_code
Address.zip_code
end
end
Principle of Least Knowledge
11
class Invoice < ActiveRecord::Base
belongs_to :customer
def customer_name
Customer.name
end
def customer_street
Customer.street
end
def customer_city
Customer.city
end
def customer_state
customer.state
end
def customer_zip_code
customer.zip_code
end
Principle of Least Knowledge
12
class Address < ActiveRecord::Base
belongs_to :customer
end
<%= @invoice.customer_name %>
<%= @invoice.customer_street %>
<%= @invoice.customer_city %>
<%= @invoice.customer_state %>
<%= @invoice.customer_zip_code %>
“use only one dot”
13
Principle of Least Knowledge (Demeter)
class Customer < ActiveRecord::Base
has_one :address
has_many :invoices
delegate :street, :city, :state, :zip_code, :to => :address
end
class Invoice < ActiveRecord::Base
belongs_to :customer
delegate :name,
:street,
:city,
:state,
:zip_code,
:to => :customer,
:prefix => true
end
14
Thanks to the class-level delegate method!
You have the benefit of following the Law of
Demeter without so much extra clutter in
your models.
‣ Case Statements
‣ Comments
‣ Long Method
‣ Long Parameter List
‣ Middle Man
‣ Repetitive Boilerplate
‣ Data Clumps
…
Chapter 3 - Bad Smells in Code [Fowler et al.; 2009] 15
If it stinks, change it [Grandma Beck; 2002]
‣ A class is doing too much simple delegation
One of the prime features of objects is encapsulation,
hiding internal details from the rest of the world.
Encapsulation often comes with delegation.
You ask a director whether is free for a meeting. The Director
delegates the message to a diary and gives you an answer.
There is no need to know whether the director uses a diary, an
electronic gizmo, or a secretary.
16
Remove middle man [Fowler et al.; 2002]
Get the client to call the delegate directly
‣ If half the methods are delegating to this other class. It is time
to use remove middle man and talk to the object that really
knows what’s going on
Inline Method:
If only a few methods
aren’t doing much, use
Inline Method to inline
them into the caller.
17
Remove middle man
class Person…
def initialize(department)
@department = department
end
def manager
@department.manager
end
class Department
attr_reader :manager
def initialize(manager)
@manager = manager
end
...
This is simple to use and encapsulates the
department. However, if a lot of methods are
doing this, I end up with too many of these
simple delegations on the person. That’s
when it is good to remove the middle man.
manager = john.manager
Take each method at a time. Find clients
that use the method on person and change it
to first get the delegate. Then use it:
Make an accessor for the delegate:
class Person…
attr_reader :department
manager = john.department.manager 18
Remove middle man
‣ 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: def get_rating
more_than_five_late_deliveries ? 2 : 1
end
def more_than_five_late_deliveries
@number_of_late_deliveries > 5
end
def get_rating
@number_of_late_deliveries > 5 ? 2 : 1
end
19
Inline method [Fowler et al.; 2002]
When you feel the need to write a comment, first try to refactor
the code so that any comment becomes superfluous.
20
Comments Should Describe Things
That Aren’t Obvious From The Code:
Why, not What
[9.4 Book SaaS apud John Ousterhout]
Comments are a sweet smell [Fowler]
21
# Scan the array to see if the symbol exists
# Loop through every array index, get the third value of the list
# in the content to determine if it has the symbol we are
# looking for. Set the result to the symbol if we find it.
Comments [Fox, A.; Patterson, D.; 2015]
Symptoms that often indicate code smells:
‣ Is it SHORT?
‣ Does it do ONE thing?
‣ Does it have FEW arguments?
‣ Is it a consistent level of ABSTRACTION?
22
SOFA [Martin, R.; 2008]
‣ One of the easiest ways to remove duplication is
Extract Method.
‣ Extract the method and call it from multiple places.
‣ Some kinds of methods become so commonplace that
we can go even further.
‣ Take for example attr_reader in Ruby.
23
Repetitive boilerplate [Fowler et al.; 2009]
‣ Ninety-nine percent of the time, all you have to do to
shorten a method is Extract Method
‣ Find parts of the method that seem to go nicely
together and make a new method
24
Long method [Fowler et al.; 2002]
‣ You have a code fragment that can be grouped together
Turn the fragment into a method whose name explains the
purpose of the method
def print_owning(amount)
Print_banner
puts "name: #{@name}"
puts "amount: #{amount}"
end
def print_owning(amount)
print_banner
print_details amount
end
def print_details(amount)
puts "name: #{@name}"
puts "amount: #{amount}"
end 25
Extract method [Fowler et al.; 2002]
‣ You have different methods that use the same group of
variables
Treatment: Introduce a Parameter Object
def directions(lat, long)
...
end
def distance(lat, long)
...
end
def directions(location)
...
end
def distance(location)
...
end
26
Data clumps [Fowler et al.; 2002]
‣ The code has a temporary variable that’s being used to hold
intermediate results of an expression
Return self on the methods so it’s possible to chain the calls
mock = Mock.new
expectation = mock.expects(:
a_method)
expectation.with("arguments")
expectation.returns([1, :array])
mock = Mock.new
mock.expects(:a_method_name).with
("arguments").returns([1, :array])
27
Replace temp with chain [Fowler; 2002]
‣ TDD refactoring
‣ Litter-pickup refactoring
‣ Comprehension refactoring
‣ Preparatory refactoring
‣ Planned refactoring
‣ Long-term refactoring
28
Workflows of refactoring
‣ Refactoring plugin (Eclipse)
‣ Aptana Studio 3
‣ RubyMine
‣ Rails tool reek finds code smells
‣ metric_fu (book SaaS: saikuro (CC), flog (ABC))
‣ Rake metrics
‣ CodeClimate
‣ Mezuro 29
Tools
‣M. Fowler; K. Beck; Addison Wesley, 2002;
Refactoring: Improving the Design of Existing Code
‣Fields, J.; S. Harvie; M. Fowler; K. Beck; Addison Wesley, 2009;
Refactoring Ruby Edition
‣Pytel, C.; Saleh, T.; Addison Wesley, 2010;
Rails Antipatterns Best Practice Ruby on Rails Refactoring
‣Martin, R.; Prentice Hall, 2008;
Clean Code: A Handbook of Agile Software Craftsmanship
‣Fox, A.; Patterson, D.; Strawberry Canyon, 2015;
Construindo Software como Serviço (Capítulo 9)
‣http://refactoring.com/catalog/
30
References

More Related Content

What's hot (17)

VB Function and procedure
VB Function and procedureVB Function and procedure
VB Function and procedure
 
structured programming
structured programmingstructured programming
structured programming
 
Savitch Ch 05
Savitch Ch 05Savitch Ch 05
Savitch Ch 05
 
Ch9 Functions
Ch9 FunctionsCh9 Functions
Ch9 Functions
 
selection structures
selection structuresselection structures
selection structures
 
Ecs 10 programming assignment 4 loopapalooza
Ecs 10 programming assignment 4   loopapaloozaEcs 10 programming assignment 4   loopapalooza
Ecs 10 programming assignment 4 loopapalooza
 
Savitch ch 05
Savitch ch 05Savitch ch 05
Savitch ch 05
 
Savitch Ch 04
Savitch Ch 04Savitch Ch 04
Savitch Ch 04
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of Variable
 
Devry cis 170 c i lab 5 of 7 arrays and strings
Devry cis 170 c i lab 5 of 7 arrays and stringsDevry cis 170 c i lab 5 of 7 arrays and strings
Devry cis 170 c i lab 5 of 7 arrays and strings
 
TDD in Powershell
TDD in PowershellTDD in Powershell
TDD in Powershell
 
Devry cis-170-c-i lab-5-of-7-arrays-and-strings
Devry cis-170-c-i lab-5-of-7-arrays-and-stringsDevry cis-170-c-i lab-5-of-7-arrays-and-strings
Devry cis-170-c-i lab-5-of-7-arrays-and-strings
 
DIG1108 Lesson 8
DIG1108 Lesson 8DIG1108 Lesson 8
DIG1108 Lesson 8
 
Scope of variables
Scope of variablesScope of variables
Scope of variables
 
Notes part5
Notes part5Notes part5
Notes part5
 
Basics of Functional Programming
Basics of Functional ProgrammingBasics of Functional Programming
Basics of Functional Programming
 
Scope of variable
Scope of variableScope of variable
Scope of variable
 

Similar to Refactoring

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
 
Save time by applying clean code principles
Save time by applying clean code principlesSave time by applying clean code principles
Save time by applying clean code principlesEdorian
 
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...DevDay.org
 
Agile korea 2013 유석문
Agile korea 2013 유석문Agile korea 2013 유석문
Agile korea 2013 유석문Sangcheol Hwang
 
Refactoring, 2nd Edition
Refactoring, 2nd EditionRefactoring, 2nd Edition
Refactoring, 2nd Editionjexp
 
Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.
Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.
Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.Chris Laning
 
Code Review
Code ReviewCode Review
Code ReviewRavi Raj
 
Program logic and design
Program logic and designProgram logic and design
Program logic and designChaffey College
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review ProcessDr. Syed Hassan Amin
 
Problem Solving Techniques
Problem Solving TechniquesProblem Solving Techniques
Problem Solving TechniquesAshesh R
 
agile refactoring and integration techniques.pdf
agile refactoring and integration techniques.pdfagile refactoring and integration techniques.pdf
agile refactoring and integration techniques.pdfshreyassoni7
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2Hammad Rajjoub
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2Hammad Rajjoub
 
Agile development with Ruby
Agile development with RubyAgile development with Ruby
Agile development with Rubykhelll
 

Similar to Refactoring (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
 
Save time by applying clean code principles
Save time by applying clean code principlesSave time by applying clean code principles
Save time by applying clean code principles
 
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
 
Agile korea 2013 유석문
Agile korea 2013 유석문Agile korea 2013 유석문
Agile korea 2013 유석문
 
Refactoring, 2nd Edition
Refactoring, 2nd EditionRefactoring, 2nd Edition
Refactoring, 2nd Edition
 
Put to the Test
Put to the TestPut to the Test
Put to the Test
 
Quick Intro to Clean Coding
Quick Intro to Clean CodingQuick Intro to Clean Coding
Quick Intro to Clean Coding
 
Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.
Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.
Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.
 
Code Review
Code ReviewCode Review
Code Review
 
Program logic and design
Program logic and designProgram logic and design
Program logic and design
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review Process
 
Problem Solving Techniques
Problem Solving TechniquesProblem Solving Techniques
Problem Solving Techniques
 
agile refactoring and integration techniques.pdf
agile refactoring and integration techniques.pdfagile refactoring and integration techniques.pdf
agile refactoring and integration techniques.pdf
 
Intro To AOP
Intro To AOPIntro To AOP
Intro To AOP
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2
 
Refactoring
RefactoringRefactoring
Refactoring
 
Agile development with Ruby
Agile development with RubyAgile development with Ruby
Agile development with Ruby
 
Introduction To Programming (2009 2010)
Introduction To Programming (2009 2010)Introduction To Programming (2009 2010)
Introduction To Programming (2009 2010)
 

Recently uploaded

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
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
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
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
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
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
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
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
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
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 

Recently uploaded (20)

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 🔝✔️✔️
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
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
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
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
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
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 🔝✔️✔️
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
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...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 

Refactoring

  • 2. ‣ Refactoring is the process of changing a software system in such a way that it does not* alter the external behavior of the code yet improves its internal structure [Fowler et al.; 2002] ‣ The art of safely* improving the design of existing code [Fowler et al.; 2009] *Importance of Testing in Refactoring 2 Definition
  • 3. ‣ Refactoring (noun): A change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior ‣ Refactor (verb): To restructure software by applying a series of refactorings without changing its observable behavior 3 Definition
  • 4. ‣ Refactoring does not include any functional change to the system ‣ Refactoring is not “Rewriting from scratch” ‣ Refactoring is not just any restructuring intended to improve the code 4 Refactoring is not
  • 5. ‣ Start with an existing code and make it better ‣ Change the internal structure while preserving the overall semantics ‣ Refactoring changes the programs in small steps If you make a mistake, it is easy to find the bug 5 Refactoring is
  • 6. ‣ Improves Quality of the Code ‣ Improves Maintainability while reducing Coupling ‣ Improves the Design of Software ‣ Makes Software Easier to Understand ‣ Helps You Find Bugs 6 Benefits
  • 7. ‣ Refactor When You Add Function ‣ Refactor When You Need to Fix a Bug ‣ Refactor As You Do a Code Review ‣ Refactoring for Greater Understanding The third time you do something similar, you refactor 7 When
  • 8. ‣ Changing Interfaces Don’t publish interfaces prematurely. Modify your code ownership policies to smooth refactoring ‣ Databases ‣ Design Changes That Are Difficult to Refactor ‣ When Shouldn’t You Refactor? ‣ It Takes A While to Create Nothing ‣ Refactoring and Performance 8 Problems with refactoring
  • 9. [Pytel et al.; 2010] class Address < ActiveRecord::Base belongs_to :customer end class Customer < ActiveRecord::Base has_one :address has_many :invoices end class Invoice < ActiveRecord::Base belongs_to :customer end 9 AntiPattern: Voyeuristic Models
  • 10. <%= @invoice.customer.name %> <%= @invoice.customer.address.street %> <%= @invoice.customer.address.city %>, <%= @invoice.customer.address.state %> <%= @invoice.customer.address.zip_code %> 10 AntiPattern: Voyeuristic Models
  • 11. class Customer < ActiveRecord::Base has_one :address has_many :invoices def street Address.street end def city Address.city end def state Address.state end def zip_code Address.zip_code end end Principle of Least Knowledge 11
  • 12. class Invoice < ActiveRecord::Base belongs_to :customer def customer_name Customer.name end def customer_street Customer.street end def customer_city Customer.city end def customer_state customer.state end def customer_zip_code customer.zip_code end Principle of Least Knowledge 12
  • 13. class Address < ActiveRecord::Base belongs_to :customer end <%= @invoice.customer_name %> <%= @invoice.customer_street %> <%= @invoice.customer_city %> <%= @invoice.customer_state %> <%= @invoice.customer_zip_code %> “use only one dot” 13 Principle of Least Knowledge (Demeter)
  • 14. class Customer < ActiveRecord::Base has_one :address has_many :invoices delegate :street, :city, :state, :zip_code, :to => :address end class Invoice < ActiveRecord::Base belongs_to :customer delegate :name, :street, :city, :state, :zip_code, :to => :customer, :prefix => true end 14 Thanks to the class-level delegate method! You have the benefit of following the Law of Demeter without so much extra clutter in your models.
  • 15. ‣ Case Statements ‣ Comments ‣ Long Method ‣ Long Parameter List ‣ Middle Man ‣ Repetitive Boilerplate ‣ Data Clumps … Chapter 3 - Bad Smells in Code [Fowler et al.; 2009] 15 If it stinks, change it [Grandma Beck; 2002]
  • 16. ‣ A class is doing too much simple delegation One of the prime features of objects is encapsulation, hiding internal details from the rest of the world. Encapsulation often comes with delegation. You ask a director whether is free for a meeting. The Director delegates the message to a diary and gives you an answer. There is no need to know whether the director uses a diary, an electronic gizmo, or a secretary. 16 Remove middle man [Fowler et al.; 2002]
  • 17. Get the client to call the delegate directly ‣ If half the methods are delegating to this other class. It is time to use remove middle man and talk to the object that really knows what’s going on Inline Method: If only a few methods aren’t doing much, use Inline Method to inline them into the caller. 17 Remove middle man
  • 18. class Person… def initialize(department) @department = department end def manager @department.manager end class Department attr_reader :manager def initialize(manager) @manager = manager end ... This is simple to use and encapsulates the department. However, if a lot of methods are doing this, I end up with too many of these simple delegations on the person. That’s when it is good to remove the middle man. manager = john.manager Take each method at a time. Find clients that use the method on person and change it to first get the delegate. Then use it: Make an accessor for the delegate: class Person… attr_reader :department manager = john.department.manager 18 Remove middle man
  • 19. ‣ 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: def get_rating more_than_five_late_deliveries ? 2 : 1 end def more_than_five_late_deliveries @number_of_late_deliveries > 5 end def get_rating @number_of_late_deliveries > 5 ? 2 : 1 end 19 Inline method [Fowler et al.; 2002]
  • 20. When you feel the need to write a comment, first try to refactor the code so that any comment becomes superfluous. 20 Comments Should Describe Things That Aren’t Obvious From The Code: Why, not What [9.4 Book SaaS apud John Ousterhout] Comments are a sweet smell [Fowler]
  • 21. 21 # Scan the array to see if the symbol exists # Loop through every array index, get the third value of the list # in the content to determine if it has the symbol we are # looking for. Set the result to the symbol if we find it. Comments [Fox, A.; Patterson, D.; 2015]
  • 22. Symptoms that often indicate code smells: ‣ Is it SHORT? ‣ Does it do ONE thing? ‣ Does it have FEW arguments? ‣ Is it a consistent level of ABSTRACTION? 22 SOFA [Martin, R.; 2008]
  • 23. ‣ One of the easiest ways to remove duplication is Extract Method. ‣ Extract the method and call it from multiple places. ‣ Some kinds of methods become so commonplace that we can go even further. ‣ Take for example attr_reader in Ruby. 23 Repetitive boilerplate [Fowler et al.; 2009]
  • 24. ‣ Ninety-nine percent of the time, all you have to do to shorten a method is Extract Method ‣ Find parts of the method that seem to go nicely together and make a new method 24 Long method [Fowler et al.; 2002]
  • 25. ‣ You have a code fragment that can be grouped together Turn the fragment into a method whose name explains the purpose of the method def print_owning(amount) Print_banner puts "name: #{@name}" puts "amount: #{amount}" end def print_owning(amount) print_banner print_details amount end def print_details(amount) puts "name: #{@name}" puts "amount: #{amount}" end 25 Extract method [Fowler et al.; 2002]
  • 26. ‣ You have different methods that use the same group of variables Treatment: Introduce a Parameter Object def directions(lat, long) ... end def distance(lat, long) ... end def directions(location) ... end def distance(location) ... end 26 Data clumps [Fowler et al.; 2002]
  • 27. ‣ The code has a temporary variable that’s being used to hold intermediate results of an expression Return self on the methods so it’s possible to chain the calls mock = Mock.new expectation = mock.expects(: a_method) expectation.with("arguments") expectation.returns([1, :array]) mock = Mock.new mock.expects(:a_method_name).with ("arguments").returns([1, :array]) 27 Replace temp with chain [Fowler; 2002]
  • 28. ‣ TDD refactoring ‣ Litter-pickup refactoring ‣ Comprehension refactoring ‣ Preparatory refactoring ‣ Planned refactoring ‣ Long-term refactoring 28 Workflows of refactoring
  • 29. ‣ Refactoring plugin (Eclipse) ‣ Aptana Studio 3 ‣ RubyMine ‣ Rails tool reek finds code smells ‣ metric_fu (book SaaS: saikuro (CC), flog (ABC)) ‣ Rake metrics ‣ CodeClimate ‣ Mezuro 29 Tools
  • 30. ‣M. Fowler; K. Beck; Addison Wesley, 2002; Refactoring: Improving the Design of Existing Code ‣Fields, J.; S. Harvie; M. Fowler; K. Beck; Addison Wesley, 2009; Refactoring Ruby Edition ‣Pytel, C.; Saleh, T.; Addison Wesley, 2010; Rails Antipatterns Best Practice Ruby on Rails Refactoring ‣Martin, R.; Prentice Hall, 2008; Clean Code: A Handbook of Agile Software Craftsmanship ‣Fox, A.; Patterson, D.; Strawberry Canyon, 2015; Construindo Software como Serviço (Capítulo 9) ‣http://refactoring.com/catalog/ 30 References