SlideShare a Scribd company logo
Refactoring
Ricardo Terra
rterrabh [at] gmail.com
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 1 / 46
CV
Nome: Ricardo Terra
Email: rterrabh [at] gmail.com
www: ricardoterra.com.br
Twitter: rterrabh
Lattes: lattes.cnpq.br/ 0162081093970868
Ph.D. (UFMG/UWaterloo),
Post-Ph.D. (INRIA/Université Lille 1)
Background
Education: UFLA (since 2014), UFSJ (1 year), FUMEC (3 years), UNIPAC (1 year), FAMINAS (3 years)
Work Experience: DBA Eng. (1 year), Synos (2 years), Stefanini (1 year)
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 2 / 46
Agenda
1 Overview
2 Refactoring
3 Refactoring & Agile Methodologies
4 Final Considerations
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 3 / 46
Overview
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 4 / 46
Overview – What is it?
Process of changing a computer program’s source code
without modifying its external functional behavior
To improve some of the nonfunctional attributes:
code readability
reduced complexity to improve maintainability
better design =⇒ extensibility
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 5 / 46
Overview – What is it?
“By continuously improving the design of code, we make
it easier and easier to work with. This is in sharp contrast
to what typically happens: little refactoring and a great
deal of attention paid to expediently adding new features. If
you get into the hygienic habit of refactoring continuously,
you’ll find that it is easier to extend and maintain code.”
— Joshua Kerievsky [Refactoring to Patterns]
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 6 / 46
Overview – What is it?
“By continuously improving the design of code, we make
it easier and easier to work with. This is in sharp contrast
to what typically happens: little refactoring and a great
deal of attention paid to expediently adding new features. If
you get into the hygienic habit of refactoring continuously,
you’ll find that it is easier to extend and maintain code.”
— Joshua Kerievsky [Refactoring to Patterns]
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 6 / 46
Overview – What is it?
“By continuously improving the design of code, we make
it easier and easier to work with. This is in sharp contrast
to what typically happens: little refactoring and a great
deal of attention paid to expediently adding new features. If
you get into the hygienic habit of refactoring continuously,
you’ll find that it is easier to extend and maintain code.”
— Joshua Kerievsky [Refactoring to Patterns]
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 6 / 46
Overview – History of Use
In the past, refactoring was not a common practice in
development processes
For example, CVS (created in 1984) does not version the
moving or renaming of files and directories
Nowadays, refactoring is one fundamental technique
adopted in agile methodologies1
eXtreme Programming, Scrum, etc.
1
I’ll discuss about it later...
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 7 / 46
Overview – When do I use?
Bad smells!
A structure in the code suggests, and sometimes even
scream for, opportunities for refactoring
This humorous advice rely on the experience of programmers
and on the clarity of code
Indications to possible bad smells:
Duplicated code →
Long method →
Large class →
Long parameter list →
...
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 8 / 46
Overview – When do I use?
Bad smells!
A structure in the code suggests, and sometimes even
scream for, opportunities for refactoring
This humorous advice rely on the experience of programmers
and on the clarity of code
Indications to possible bad smells:
Duplicated code → share one same method
Long method →
Large class →
Long parameter list →
...
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 8 / 46
Overview – When do I use?
Bad smells!
A structure in the code suggests, and sometimes even
scream for, opportunities for refactoring
This humorous advice rely on the experience of programmers
and on the clarity of code
Indications to possible bad smells:
Duplicated code → share one same method
Long method → extract one or more smaller methods
Large class →
Long parameter list →
...
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 8 / 46
Overview – When do I use?
Bad smells!
A structure in the code suggests, and sometimes even
scream for, opportunities for refactoring
This humorous advice rely on the experience of programmers
and on the clarity of code
Indications to possible bad smells:
Duplicated code → share one same method
Long method → extract one or more smaller methods
Large class → divide in more cohesive classes
Long parameter list →
...
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 8 / 46
Overview – When do I use?
Bad smells!
A structure in the code suggests, and sometimes even
scream for, opportunities for refactoring
This humorous advice rely on the experience of programmers
and on the clarity of code
Indications to possible bad smells:
Duplicated code → share one same method
Long method → extract one or more smaller methods
Large class → divide in more cohesive classes
Long parameter list → encapsulate them
...
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 8 / 46
Refactoring
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 9 / 46
Refactoring
There is a almost a hundred catalogued refactorings
each one has a name, a motivation, and a mechanics
They are usually organized into the following groups:
Composing Methods (e.g., Extract Method)
Moving Features Between Objects (e.g., Move Method)
Organizing Data (e.g., Encapsulate Field)
Simplifying Conditional Expressions (e.g., Consolidate Conditional Expression)
Making Method Calls Simpler (e.g., Rename Method)
Dealing with Generalization (e.g., Pull Up Method)
Big Refactorings (e.g., Extract Hierarchy)
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 10 / 46
Refactoring
In this section, we will explain some refactorings and show
an example of its usage
We have chosen the popular refactorings, more specifically,
refactorings that Eclipse IDE has already automated:
Extract Method
Pull Up Method
Move Method
Extract Superclass
Introduce Parameter Object
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 11 / 46
Extract Method
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 12 / 46
Refactoring #1 – Extract Method
You have a code fragment that can be grouped together
⇓
Turn the fragment into a method whose name explains the
purpose of the method
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 13 / 46
Refactoring #1 – Extract Method – Theoretical Example
1 void printOwing (double amount) {
2 printBanner ( ) ;
3
4 // print details
5 System . out . p r i n t l n ( "name: " + t h i s .name) ;
6 System . out . p r i n t l n ( "amount: " + amount ) ;
7 }
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 14 / 46
Refactoring #1 – Extract Method – Theoretical Example
1 void printOwing (double amount) {
2 printBanner ( ) ;
3
4 // print details
5 System . out . p r i n t l n ( "name: " + t h i s .name) ;
6 System . out . p r i n t l n ( "amount: " + amount ) ;
7 }
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 14 / 46
Refactoring #1 – Extract Method – Theoretical Example
1 void printOwing (double amount) {
2 printBanner ( ) ;
3
4 // print details
5 System . out . p r i n t l n ( "name: " + t h i s .name) ;
6 System . out . p r i n t l n ( "amount: " + amount ) ;
7 }
⇓
1 void printOwing (double amount) {
2 printBanner ( ) ;
3 printDetails (amount ) ;
4 }
5
6 void printDetails (double amount) {
7 System . out . p r i n t l n ( "name: " + t h i s .name) ;
8 System . out . p r i n t l n ( "amount: " + amount ) ;
9 }
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 14 / 46
Refactoring #1 – Extract Method – Motivation
It is one of the most common refactorings
Long methods or look at code that needs a comment to
understand its purpose
So, I turn that fragment of code into its own method.
Reasons to do that:
Increases the chances that other methods can use a method
when the method is fine-grained
Allows the higher-level methods to read more like a series of
comments
Overriding also is easier
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 15 / 46
Refactoring #1 – Extract Method – Practice
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 16 / 46
Pull Up Method
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 17 / 46
Refactoring #2 – Pull Up Method
You have methods with identical results on subclasses
⇓
Move them to the superclass
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 18 / 46
Refactoring #2 – Pull Up Method – Theoretical Example
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 19 / 46
Refactoring #2 – Pull Up Method – Theoretical Example
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 19 / 46
Refactoring #2 – Pull Up Method – Theoretical Example
⇒
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 19 / 46
Refactoring #2 – Pull Up Method – Motivation
Eliminating duplicate behavior is important
if not, the risk that a change to one not be made to other
The easiest case: methods have the same body
of course it is not always obvious as that. So, look for the
differences and test for safety
Special case: you have a subclass method that overrides a
superclass method yet does the same thing (WDF?)
The most awkward case: the method may refer to features
that are on the subclass but not on the superclass
possible solutions: generalize methods, create abstract
method on superclass, change a method’s signature...
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 20 / 46
Refactoring #2 – Pull Up Method – Practice
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 21 / 46
Move Method
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 22 / 46
Refactoring #3 – Move Method
A method is, or will be, using or used by more features of another
class than the class on which it is defined
(Feature Envy)
⇓
Create a new method with similar body in the class it uses most.
Either turn the old method into a simple delegation, or remove it
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 23 / 46
Refactoring #3 – Move Method – Theoretical Example
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 24 / 46
Refactoring #3 – Move Method – Theoretical Example
⇒
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 24 / 46
Refactoring #3 – Move Method – Motivation
Moving methods is the bread and butter of refactoring
classes with too much behavior
classes are collaborating too much (too highly coupled)
By moving methods around:
make classes simpler
high cohesion (classes end up being a more crisp implementation of a set of responsibilities)
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 25 / 46
Refactoring #3 – Move Method – Practice
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 26 / 46
Extract Superclass
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 27 / 46
Refactoring #4 – Extract Superclass
You have two classes with similar features
⇓
Create a superclass and move the common features to the
superclass
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 28 / 46
Refactoring #4 – Extract Superclass – Theoretical Example
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 29 / 46
Refactoring #4 – Extract Superclass – Theoretical Example
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 29 / 46
Refactoring #4 – Extract Superclass – Theoretical Example
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 29 / 46
Refactoring #4 – Extract Superclass – Theoretical Example
⇓
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 29 / 46
Refactoring #4 – Extract Superclass – Motivation
Duplicate code is one of the principal bad things in systems
Duplicate code:
two classes that do similar things in the same way or
two classes that do similar things in different ways
A well-known solution: inheritance (everything)
However, you often do not notice the commonalities until you
have created some classes
In this case, you need to create the inheritance structure later
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 30 / 46
Refactoring #4 – Extract Superclass – Practice
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 31 / 46
Introduce Parameter Object
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 32 / 46
Refactoring #5 – Introduce Parameter Object
You have a group of parameters that naturally go together
⇓
Replace them with an object
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 33 / 46
Refactoring #5 – Introduce Parameter Object – Theoretical
Example
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 34 / 46
Refactoring #5 – Introduce Parameter Object – Theoretical
Example
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 34 / 46
Refactoring #5 – Introduce Parameter Object – Theoretical
Example
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 34 / 46
Refactoring #5 – Introduce Parameter Object – Theoretical
Example
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 34 / 46
Refactoring #5 – Introduce Parameter Object – Theoretical
Example
⇓
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 34 / 46
Refactoring #5 – Introduce Parameter Object – Motivation
Often you see a particular group of parameters that tend to
be passed together
It is worthwhile to turn these parameters into objects just to
group the data together
It is useful because it reduces the size of the parameter lists,
and long parameter list are hard to understand
Deeper, when you do this refactoring, you can see common
manipulations of the parameter values
By moving this behavior into the new object, you can remove
a lot of duplicated code
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 35 / 46
Refactoring #5 – Introduce Parameter Object – Practice
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 36 / 46
rename as well?
Refactoring & Agile Methodologies
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 37 / 46
Refactoring & Agile Methodologies – XP
eXtreme Programming (XP)
XP prescribes several engineering practices:
TDD (automated testing), Pair programming, Simple design,
and Refactoring (mercilessly)
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 38 / 46
Refactoring & Agile Methodologies – XP
eXtreme Programming (XP) — Collective Code Ownership
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 39 / 46
Refactoring & Agile Methodologies – Scrum
Scrum
Scrum, on the other hand, does not prescribe engineering
practices
But, it does not mean you can’t use TDD, PP, Refactoring, etc.
I.M.H.O, Scrum solely does not make their usage mandatory
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 40 / 46
Final Considerations
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 41 / 46
Final Considerations – Why should I refactor?
Improves the design of software
Loss of the structure (mostly by changes) has a cumulative effect
Regular refactorings helps code retain its shape
Makes software easier to understand
when you refactor, your code is more readable
Helps you find bugs
when you refactor, you understand what the code does, and
put that understanding right back into the code
Helps you program faster (does it sound counterintuitive?)
without a good design, you spend time finding and fixing
bugs instead of adding new functions
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 42 / 46
Final Considerations – Refactoring vs Performance Optimization
Like refactoring, performance optimization does not change
the behavior of a component (other that its speed)
Indeed, it only alters the internal structure
However, the purpose is different
Refactoring: software easier to understand and modify
Performance Optimization: often makes code harder to
understand and modify
but you get the performance you need
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 43 / 46
Final Considerations – When should I refactor?
“Refactoring is something you do all the time in little bursts. You
don’t decide to refactor, you refactor because you want to do
something else, and refactoring helps you do that other thing.”
— Martin Fowler [Refactoring: Improving the Design of Existing Code]
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 44 / 46
References
William Opdyke. Refactoring object-oriented frameworks.
Ph.D. thesis, University of Illinois at Urbana-Champaign, 1992.
Martin Fowler et al. Refactoring: Improving the Design of
Existing Code. Addison Wesley, 1999.
Joshua Kerievsky. Refactoring to Patterns. Addison Wesley,
2004.
Ken Schwaber and Jeff Sutherland. The Scrum Guide. 2011.
Available at: http://www.scrum.org.
Don Wells. Extreme Programming: A gentle introduction.
2011. Available at: http://www.extremeprogramming.org.
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 45 / 46
Thanks a lot!!!
This presentation and the Eclipse Java project are publicly available at:
www.ricardoterra.com.br/public
Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 46 / 46

More Related Content

PPT
Refactoring Tips by Martin Fowler
ODP
Refactoring Techniques
PDF
Code Refactoring
PDF
Refactoring
PDF
Refactoring
PDF
Gof design pattern
PDF
Introduction to Design Pattern
PPTX
Code smell overview
Refactoring Tips by Martin Fowler
Refactoring Techniques
Code Refactoring
Refactoring
Refactoring
Gof design pattern
Introduction to Design Pattern
Code smell overview

What's hot (20)

PPT
PDF
Domain Driven Design Introduction
PPTX
Solid principles
PDF
Code Smells and Its type (With Example)
PPTX
Laravel Tutorial PPT
PPTX
laravel.pptx
PPTX
C# Interface | Interfaces In C# | C# Interfaces Explained | C# Tutorial For B...
PPTX
Refactoring and code smells
PDF
Git 101: Git and GitHub for Beginners
PDF
The New JavaScript: ES6
PDF
Laravel Introduction
PDF
Rest in flask
PPT
SOLID Design Principles
PDF
Workshop 21: React Router
PPTX
Laravel ppt
PPTX
ReactJS presentation.pptx
PPTX
Apache tomcat
PPTX
Code refactoring
PDF
Object Oriented Analysis Design using UML
Domain Driven Design Introduction
Solid principles
Code Smells and Its type (With Example)
Laravel Tutorial PPT
laravel.pptx
C# Interface | Interfaces In C# | C# Interfaces Explained | C# Tutorial For B...
Refactoring and code smells
Git 101: Git and GitHub for Beginners
The New JavaScript: ES6
Laravel Introduction
Rest in flask
SOLID Design Principles
Workshop 21: React Router
Laravel ppt
ReactJS presentation.pptx
Apache tomcat
Code refactoring
Object Oriented Analysis Design using UML
Ad

Viewers also liked (11)

PPTX
Как найти первую работу и как с нее не вылететь
PPTX
Service oriented architecture, Oracle Service Bus
PPTX
Быть разработчиком: вызовы, ожидания, перестроение мозгов
PPTX
Как найти первую работу и не вылететь с нее
PPTX
основы Java переменные, циклы
PPT
Шаблоны разработки ПО. Часть 1. Введние
PPTX
Как пишутся и поддерживаются Enterprise системы
PPTX
Clean code
PPTX
Enterprise или на чем стоит мир
PPTX
Java enterprise: обучение, работа, перспективы
DOC
Конспект лекций по курсу "Шаблоны разработки ПО"
Как найти первую работу и как с нее не вылететь
Service oriented architecture, Oracle Service Bus
Быть разработчиком: вызовы, ожидания, перестроение мозгов
Как найти первую работу и не вылететь с нее
основы Java переменные, циклы
Шаблоны разработки ПО. Часть 1. Введние
Как пишутся и поддерживаются Enterprise системы
Clean code
Enterprise или на чем стоит мир
Java enterprise: обучение, работа, перспективы
Конспект лекций по курсу "Шаблоны разработки ПО"
Ad

Similar to Refactoring (20)

PPTX
SAD10 - Refactoring
PPTX
Why We Refactor? Confessions of GitHub Contributors
ODP
Refactoring: Improving the design of existing code
PPTX
31 days Refactoring
PDF
Refactoring: Improve the design of existing code
PDF
Code refactoring workshop (in Javascript)
PPTX
Agile korea 2013 유석문
PDF
Refactoring 2TheMax (con ReSharper)
PPTX
Code Refactoring using rails
PPTX
Speeding up web_application
PDF
Big code refactoring with agility
PPTX
Refactoring
PPT
Code Refactoring
PPTX
Refactoring, 2nd Edition
PPTX
Refactoring
PDF
Refactoring
PPTX
Refactoring workshop
PDF
Code Refactoring in Software Development
PPTX
Refactoring
PPTX
Refactoring code in .net
SAD10 - Refactoring
Why We Refactor? Confessions of GitHub Contributors
Refactoring: Improving the design of existing code
31 days Refactoring
Refactoring: Improve the design of existing code
Code refactoring workshop (in Javascript)
Agile korea 2013 유석문
Refactoring 2TheMax (con ReSharper)
Code Refactoring using rails
Speeding up web_application
Big code refactoring with agility
Refactoring
Code Refactoring
Refactoring, 2nd Edition
Refactoring
Refactoring
Refactoring workshop
Code Refactoring in Software Development
Refactoring
Refactoring code in .net

More from Ricardo Terra (20)

PDF
Microsserviços com Spring Boot e ORM
PDF
Apostila Linguagens Formais e Autômatos (LFA)
PDF
Análise Estática de Código: Aplicações
PDF
Engenharia de Software: POC
PDF
Which Programming Language is the best one?
PDF
Programação Orientada a Aspectos
PDF
Matemática Computacional
PDF
English---and LaTeX---Writing Tips
PDF
Casamento de Padrões
PDF
Apostila Algoritmos e Estrutura de Dados (AEDS)
PDF
Segurança da Internet
PDF
Java Net: Interagindo com a Internet
PDF
Software Architecture
PDF
Aula Zero
PDF
Apostila Tecnologia da Informação (TI)
PDF
Apostila Lógica de Programação
PDF
Apostila XML, DTD, XSD e XSLT
PDF
Java JDBC: Aplicação Java que acessa um SGDB
PDF
Apostila UML
PDF
Apostila Modelo ER (Entidade Relacionamento)
Microsserviços com Spring Boot e ORM
Apostila Linguagens Formais e Autômatos (LFA)
Análise Estática de Código: Aplicações
Engenharia de Software: POC
Which Programming Language is the best one?
Programação Orientada a Aspectos
Matemática Computacional
English---and LaTeX---Writing Tips
Casamento de Padrões
Apostila Algoritmos e Estrutura de Dados (AEDS)
Segurança da Internet
Java Net: Interagindo com a Internet
Software Architecture
Aula Zero
Apostila Tecnologia da Informação (TI)
Apostila Lógica de Programação
Apostila XML, DTD, XSD e XSLT
Java JDBC: Aplicação Java que acessa um SGDB
Apostila UML
Apostila Modelo ER (Entidade Relacionamento)

Recently uploaded (20)

PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Cell Structure & Organelles in detailed.
PDF
Trump Administration's workforce development strategy
PDF
Weekly quiz Compilation Jan -July 25.pdf
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Cell Types and Its function , kingdom of life
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
RMMM.pdf make it easy to upload and study
PPTX
GDM (1) (1).pptx small presentation for students
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PDF
Classroom Observation Tools for Teachers
PDF
Complications of Minimal Access Surgery at WLH
PDF
Yogi Goddess Pres Conference Studio Updates
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
Cell Structure & Organelles in detailed.
Trump Administration's workforce development strategy
Weekly quiz Compilation Jan -July 25.pdf
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Cell Types and Its function , kingdom of life
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
RMMM.pdf make it easy to upload and study
GDM (1) (1).pptx small presentation for students
VCE English Exam - Section C Student Revision Booklet
Chinmaya Tiranga quiz Grand Finale.pdf
Supply Chain Operations Speaking Notes -ICLT Program
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
Classroom Observation Tools for Teachers
Complications of Minimal Access Surgery at WLH
Yogi Goddess Pres Conference Studio Updates
3rd Neelam Sanjeevareddy Memorial Lecture.pdf

Refactoring

  • 1. Refactoring Ricardo Terra rterrabh [at] gmail.com Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 1 / 46
  • 2. CV Nome: Ricardo Terra Email: rterrabh [at] gmail.com www: ricardoterra.com.br Twitter: rterrabh Lattes: lattes.cnpq.br/ 0162081093970868 Ph.D. (UFMG/UWaterloo), Post-Ph.D. (INRIA/Université Lille 1) Background Education: UFLA (since 2014), UFSJ (1 year), FUMEC (3 years), UNIPAC (1 year), FAMINAS (3 years) Work Experience: DBA Eng. (1 year), Synos (2 years), Stefanini (1 year) Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 2 / 46
  • 3. Agenda 1 Overview 2 Refactoring 3 Refactoring & Agile Methodologies 4 Final Considerations Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 3 / 46
  • 4. Overview Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 4 / 46
  • 5. Overview – What is it? Process of changing a computer program’s source code without modifying its external functional behavior To improve some of the nonfunctional attributes: code readability reduced complexity to improve maintainability better design =⇒ extensibility Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 5 / 46
  • 6. Overview – What is it? “By continuously improving the design of code, we make it easier and easier to work with. This is in sharp contrast to what typically happens: little refactoring and a great deal of attention paid to expediently adding new features. If you get into the hygienic habit of refactoring continuously, you’ll find that it is easier to extend and maintain code.” — Joshua Kerievsky [Refactoring to Patterns] Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 6 / 46
  • 7. Overview – What is it? “By continuously improving the design of code, we make it easier and easier to work with. This is in sharp contrast to what typically happens: little refactoring and a great deal of attention paid to expediently adding new features. If you get into the hygienic habit of refactoring continuously, you’ll find that it is easier to extend and maintain code.” — Joshua Kerievsky [Refactoring to Patterns] Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 6 / 46
  • 8. Overview – What is it? “By continuously improving the design of code, we make it easier and easier to work with. This is in sharp contrast to what typically happens: little refactoring and a great deal of attention paid to expediently adding new features. If you get into the hygienic habit of refactoring continuously, you’ll find that it is easier to extend and maintain code.” — Joshua Kerievsky [Refactoring to Patterns] Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 6 / 46
  • 9. Overview – History of Use In the past, refactoring was not a common practice in development processes For example, CVS (created in 1984) does not version the moving or renaming of files and directories Nowadays, refactoring is one fundamental technique adopted in agile methodologies1 eXtreme Programming, Scrum, etc. 1 I’ll discuss about it later... Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 7 / 46
  • 10. Overview – When do I use? Bad smells! A structure in the code suggests, and sometimes even scream for, opportunities for refactoring This humorous advice rely on the experience of programmers and on the clarity of code Indications to possible bad smells: Duplicated code → Long method → Large class → Long parameter list → ... Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 8 / 46
  • 11. Overview – When do I use? Bad smells! A structure in the code suggests, and sometimes even scream for, opportunities for refactoring This humorous advice rely on the experience of programmers and on the clarity of code Indications to possible bad smells: Duplicated code → share one same method Long method → Large class → Long parameter list → ... Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 8 / 46
  • 12. Overview – When do I use? Bad smells! A structure in the code suggests, and sometimes even scream for, opportunities for refactoring This humorous advice rely on the experience of programmers and on the clarity of code Indications to possible bad smells: Duplicated code → share one same method Long method → extract one or more smaller methods Large class → Long parameter list → ... Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 8 / 46
  • 13. Overview – When do I use? Bad smells! A structure in the code suggests, and sometimes even scream for, opportunities for refactoring This humorous advice rely on the experience of programmers and on the clarity of code Indications to possible bad smells: Duplicated code → share one same method Long method → extract one or more smaller methods Large class → divide in more cohesive classes Long parameter list → ... Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 8 / 46
  • 14. Overview – When do I use? Bad smells! A structure in the code suggests, and sometimes even scream for, opportunities for refactoring This humorous advice rely on the experience of programmers and on the clarity of code Indications to possible bad smells: Duplicated code → share one same method Long method → extract one or more smaller methods Large class → divide in more cohesive classes Long parameter list → encapsulate them ... Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 8 / 46
  • 15. Refactoring Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 9 / 46
  • 16. Refactoring There is a almost a hundred catalogued refactorings each one has a name, a motivation, and a mechanics They are usually organized into the following groups: Composing Methods (e.g., Extract Method) Moving Features Between Objects (e.g., Move Method) Organizing Data (e.g., Encapsulate Field) Simplifying Conditional Expressions (e.g., Consolidate Conditional Expression) Making Method Calls Simpler (e.g., Rename Method) Dealing with Generalization (e.g., Pull Up Method) Big Refactorings (e.g., Extract Hierarchy) Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 10 / 46
  • 17. Refactoring In this section, we will explain some refactorings and show an example of its usage We have chosen the popular refactorings, more specifically, refactorings that Eclipse IDE has already automated: Extract Method Pull Up Method Move Method Extract Superclass Introduce Parameter Object Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 11 / 46
  • 18. Extract Method Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 12 / 46
  • 19. Refactoring #1 – Extract Method You have a code fragment that can be grouped together ⇓ Turn the fragment into a method whose name explains the purpose of the method Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 13 / 46
  • 20. Refactoring #1 – Extract Method – Theoretical Example 1 void printOwing (double amount) { 2 printBanner ( ) ; 3 4 // print details 5 System . out . p r i n t l n ( "name: " + t h i s .name) ; 6 System . out . p r i n t l n ( "amount: " + amount ) ; 7 } Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 14 / 46
  • 21. Refactoring #1 – Extract Method – Theoretical Example 1 void printOwing (double amount) { 2 printBanner ( ) ; 3 4 // print details 5 System . out . p r i n t l n ( "name: " + t h i s .name) ; 6 System . out . p r i n t l n ( "amount: " + amount ) ; 7 } Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 14 / 46
  • 22. Refactoring #1 – Extract Method – Theoretical Example 1 void printOwing (double amount) { 2 printBanner ( ) ; 3 4 // print details 5 System . out . p r i n t l n ( "name: " + t h i s .name) ; 6 System . out . p r i n t l n ( "amount: " + amount ) ; 7 } ⇓ 1 void printOwing (double amount) { 2 printBanner ( ) ; 3 printDetails (amount ) ; 4 } 5 6 void printDetails (double amount) { 7 System . out . p r i n t l n ( "name: " + t h i s .name) ; 8 System . out . p r i n t l n ( "amount: " + amount ) ; 9 } Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 14 / 46
  • 23. Refactoring #1 – Extract Method – Motivation It is one of the most common refactorings Long methods or look at code that needs a comment to understand its purpose So, I turn that fragment of code into its own method. Reasons to do that: Increases the chances that other methods can use a method when the method is fine-grained Allows the higher-level methods to read more like a series of comments Overriding also is easier Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 15 / 46
  • 24. Refactoring #1 – Extract Method – Practice Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 16 / 46
  • 25. Pull Up Method Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 17 / 46
  • 26. Refactoring #2 – Pull Up Method You have methods with identical results on subclasses ⇓ Move them to the superclass Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 18 / 46
  • 27. Refactoring #2 – Pull Up Method – Theoretical Example Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 19 / 46
  • 28. Refactoring #2 – Pull Up Method – Theoretical Example Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 19 / 46
  • 29. Refactoring #2 – Pull Up Method – Theoretical Example ⇒ Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 19 / 46
  • 30. Refactoring #2 – Pull Up Method – Motivation Eliminating duplicate behavior is important if not, the risk that a change to one not be made to other The easiest case: methods have the same body of course it is not always obvious as that. So, look for the differences and test for safety Special case: you have a subclass method that overrides a superclass method yet does the same thing (WDF?) The most awkward case: the method may refer to features that are on the subclass but not on the superclass possible solutions: generalize methods, create abstract method on superclass, change a method’s signature... Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 20 / 46
  • 31. Refactoring #2 – Pull Up Method – Practice Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 21 / 46
  • 32. Move Method Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 22 / 46
  • 33. Refactoring #3 – Move Method A method is, or will be, using or used by more features of another class than the class on which it is defined (Feature Envy) ⇓ Create a new method with similar body in the class it uses most. Either turn the old method into a simple delegation, or remove it Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 23 / 46
  • 34. Refactoring #3 – Move Method – Theoretical Example Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 24 / 46
  • 35. Refactoring #3 – Move Method – Theoretical Example ⇒ Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 24 / 46
  • 36. Refactoring #3 – Move Method – Motivation Moving methods is the bread and butter of refactoring classes with too much behavior classes are collaborating too much (too highly coupled) By moving methods around: make classes simpler high cohesion (classes end up being a more crisp implementation of a set of responsibilities) Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 25 / 46
  • 37. Refactoring #3 – Move Method – Practice Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 26 / 46
  • 38. Extract Superclass Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 27 / 46
  • 39. Refactoring #4 – Extract Superclass You have two classes with similar features ⇓ Create a superclass and move the common features to the superclass Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 28 / 46
  • 40. Refactoring #4 – Extract Superclass – Theoretical Example Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 29 / 46
  • 41. Refactoring #4 – Extract Superclass – Theoretical Example Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 29 / 46
  • 42. Refactoring #4 – Extract Superclass – Theoretical Example Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 29 / 46
  • 43. Refactoring #4 – Extract Superclass – Theoretical Example ⇓ Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 29 / 46
  • 44. Refactoring #4 – Extract Superclass – Motivation Duplicate code is one of the principal bad things in systems Duplicate code: two classes that do similar things in the same way or two classes that do similar things in different ways A well-known solution: inheritance (everything) However, you often do not notice the commonalities until you have created some classes In this case, you need to create the inheritance structure later Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 30 / 46
  • 45. Refactoring #4 – Extract Superclass – Practice Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 31 / 46
  • 46. Introduce Parameter Object Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 32 / 46
  • 47. Refactoring #5 – Introduce Parameter Object You have a group of parameters that naturally go together ⇓ Replace them with an object Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 33 / 46
  • 48. Refactoring #5 – Introduce Parameter Object – Theoretical Example Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 34 / 46
  • 49. Refactoring #5 – Introduce Parameter Object – Theoretical Example Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 34 / 46
  • 50. Refactoring #5 – Introduce Parameter Object – Theoretical Example Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 34 / 46
  • 51. Refactoring #5 – Introduce Parameter Object – Theoretical Example Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 34 / 46
  • 52. Refactoring #5 – Introduce Parameter Object – Theoretical Example ⇓ Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 34 / 46
  • 53. Refactoring #5 – Introduce Parameter Object – Motivation Often you see a particular group of parameters that tend to be passed together It is worthwhile to turn these parameters into objects just to group the data together It is useful because it reduces the size of the parameter lists, and long parameter list are hard to understand Deeper, when you do this refactoring, you can see common manipulations of the parameter values By moving this behavior into the new object, you can remove a lot of duplicated code Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 35 / 46
  • 54. Refactoring #5 – Introduce Parameter Object – Practice Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 36 / 46 rename as well?
  • 55. Refactoring & Agile Methodologies Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 37 / 46
  • 56. Refactoring & Agile Methodologies – XP eXtreme Programming (XP) XP prescribes several engineering practices: TDD (automated testing), Pair programming, Simple design, and Refactoring (mercilessly) Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 38 / 46
  • 57. Refactoring & Agile Methodologies – XP eXtreme Programming (XP) — Collective Code Ownership Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 39 / 46
  • 58. Refactoring & Agile Methodologies – Scrum Scrum Scrum, on the other hand, does not prescribe engineering practices But, it does not mean you can’t use TDD, PP, Refactoring, etc. I.M.H.O, Scrum solely does not make their usage mandatory Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 40 / 46
  • 59. Final Considerations Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 41 / 46
  • 60. Final Considerations – Why should I refactor? Improves the design of software Loss of the structure (mostly by changes) has a cumulative effect Regular refactorings helps code retain its shape Makes software easier to understand when you refactor, your code is more readable Helps you find bugs when you refactor, you understand what the code does, and put that understanding right back into the code Helps you program faster (does it sound counterintuitive?) without a good design, you spend time finding and fixing bugs instead of adding new functions Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 42 / 46
  • 61. Final Considerations – Refactoring vs Performance Optimization Like refactoring, performance optimization does not change the behavior of a component (other that its speed) Indeed, it only alters the internal structure However, the purpose is different Refactoring: software easier to understand and modify Performance Optimization: often makes code harder to understand and modify but you get the performance you need Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 43 / 46
  • 62. Final Considerations – When should I refactor? “Refactoring is something you do all the time in little bursts. You don’t decide to refactor, you refactor because you want to do something else, and refactoring helps you do that other thing.” — Martin Fowler [Refactoring: Improving the Design of Existing Code] Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 44 / 46
  • 63. References William Opdyke. Refactoring object-oriented frameworks. Ph.D. thesis, University of Illinois at Urbana-Champaign, 1992. Martin Fowler et al. Refactoring: Improving the Design of Existing Code. Addison Wesley, 1999. Joshua Kerievsky. Refactoring to Patterns. Addison Wesley, 2004. Ken Schwaber and Jeff Sutherland. The Scrum Guide. 2011. Available at: http://www.scrum.org. Don Wells. Extreme Programming: A gentle introduction. 2011. Available at: http://www.extremeprogramming.org. Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 45 / 46
  • 64. Thanks a lot!!! This presentation and the Eclipse Java project are publicly available at: www.ricardoterra.com.br/public Ricardo Terra (rterrabh [at] gmail.com) Refactoring Janeiro, 2014 46 / 46