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 Code for Clarity

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
 
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
 
Introduction to programming by MUFIX Commnity
Introduction to programming by MUFIX CommnityIntroduction to programming by MUFIX Commnity
Introduction to programming by MUFIX Commnitymazenet
 

Similar to Refactoring Code for Clarity (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
 
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)
 
Introduction to programming by MUFIX Commnity
Introduction to programming by MUFIX CommnityIntroduction to programming by MUFIX Commnity
Introduction to programming by MUFIX Commnity
 

Recently uploaded

PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineeringssuserb3a23b
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 

Recently uploaded (20)

PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineering
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 

Refactoring Code for Clarity

  • 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