SlideShare une entreprise Scribd logo
1  sur  81
Télécharger pour lire hors ligne
CODE REFACTORING
LINGI2252 – PROF. KIM MENS
* Slides mostly based on Martin Fowler’s book:

Refactoring: Improving the Design of Existing Code. ©Addison Wesley, 2000
*
(These slides are part of the course LINGI2252 “Software Maintenance and Evolution”, given by Prof. Kim Mens at UCL, Belgium)
Refactoring:

Improving the Design of Existing Code
One of the best references on software refactoring,

with illustrative examples in Java:
Refactoring: Improving the Design of Existing Code.

Martin Fowler. Addison Wesley, 2000. ISBN: 0201485672
See also www.refactoring.com
Overview of this presentation
A. Refactoring basics
B. Categories of refactoring
C. Words of warning
2
A. REFACTORING BASICS
LINGI2252 – PROF. KIM MENS
* Based on Chapter 2 of Martin Fowler’s book:

Refactoring: Improving the Design of Existing Code. ©Addison Wesley, 2000
*
What is refactoring?
A refactoring is a software transformation that
preserves the external behaviour of the software;
improves the internal structure of the software.
It is a disciplined way to clean up code that minimises the
chances of introducing bugs.
4
Definition of Refactoring [Fowler2000]
[noun] “a change made to the internal structure of
software to make it easier to understand and cheaper to
modify without changing its observable behaviour”
[verb] “to restructure software by applying a series of
refactorings without changing its observable behaviour”
typically with the purpose of making the software
easier to understand and modify
5
6
Why should you refactor?
Why should you refactor?
To improve the design of software
To counter code decay (software ageing)
refactoring helps code to remain in shape
To increase software comprehensibility
To find bugs and write more robust code
To increase productivity (program faster)
on a long term basis, not on a short term basis
7
Why should you refactor?
To reduce costs of software maintenance
To reduce testing
automatic refactorings are guaranteed to be behaviour
preserving
To prepare for / facilitate future customisations
To turn an OO application into a framework
To introduce design patterns in a behaviourally preserving way
8
When should you refactor?
Whenever you see the need for it
Do it all the time in little bursts
Not on a pre-set periodical basis
Apply the rule of three
1
st
time : implement from scratch
2
nd
time : implement something similar by code duplication
3
rd
time : do not implement similar things again, but refactor
9
When should you refactor?
Refactor when adding new features or functions
Especially if feature is difficult to integrate with the existing
code
Refactor during bug fixing
If a bug is very hard to trace, refactor first to make the code
more understandable, so that you can understand better where
the bug is located
Refactor during code reviews
10
When should you refactor?
Refactoring also fits naturally in the agile methods
philosophy
Is needed to address the principle "Maintain simplicity"
Wherever possible, actively work to eliminate
complexity from the system
By refactoring the code
11
What do you tell the manager?
When (s)he’s technically aware (s)he’ll understand
why refactoring is important.
When (s)he’s interested in quality, (s)he’ll understand
that refactoring will improve software quality.
When (s)he’s only interested in the schedule, don’t
tell that you’re doing refactoring, just do it anyway.
In the end refactoring will make you more
productive.
12
When shouldn’t you refactor?
When the existing code is such a mess that although you could refactor
it, it would be easier to rewrite everything from scratch instead.
When you are too close to a deadline.
The productivity gain would appear after the deadline and thus
be too late.
However, when you are not close to a deadline you should never
put off refactoring because you don’t have the time.
Not having enough time usually is a sign that refactoring is
needed.
13
B. CATEGORIES OF REFACTORINGS
LINGI2252 – PROF. KIM MENS
* Based on Martin Fowler’s book:

Refactoring: Improving the Design of Existing Code. ©Addison Wesley, 2000
*
Categories of refactorings
Small refactorings
(de)composing methods
moving features between objects
organizing data
simplifying conditional expressions
dealing with generalisation
simplifying method calls
Big refactorings
Tease apart inheritance
Extract hierarchy
Convert procedural design to objects
Separate domain from presentation
15
Small refactorings
(de)composing methods [9 refactorings]
moving features between objects [8 refactorings]
organizing data [16 refactorings]
simplifying conditional expressions [8 refactorings]
dealing with generalisation [12 refactorings]
simplifying method calls [15 refactorings]
16
Small Refactorings :

(de)composing methods
1. Extract Method
2. Inline Method
3. Inline Temp
4. Replace Temp With Query
5. Introduce Explaining Variable
6. Split Temporary Variable
7. Remove Assignments to Parameter
8. Replace Method With Method Object
9. Substitute Algorithm
17
= we will zoom in on these
= home reading
Legend:
(De)composing methods:

1. Extract Method
18
What? When you have a fragment of code that can be grouped together,
turn it into a method with a name that explains the purpose of the
method
Why? improves clarity, removes redundancy
Example:
public void accept(Packet p) {

if ((p.getAddressee() == this) &&

(this.isASCII(p.getContents())))

this.print(p);

else

super.accept(p); }
public void accept(Packet p) {
if this.isDestFor(p) this.print(p);
else super.accept(p); }
public boolean isDestFor(Packet p) {
return
((p.getAddressee() == this) &&
(this.isASCII(p.getContents()))); }
Beware of local variables !
(Opposite of Extract Method)


What? When a method’s body is just as clear as its name, put the method’s
body into the body of its caller and remove the method
Why? To remove too much indirection and delegation
Example:
int getRating(){
return moreThanFiveLateDeliveries();
}

boolean moreThanFiveLateDeliveries(){
return _numberOfLateDeliveries > 5;
}
(De)composing methods :

2. Inline Method
19
int getRating(){
return (_numberOfLateDeliveries > 5);
}
(De)composing methods :

3. Inline Temp
20
What? When you have a temp that is assigned once with a simple
expression, and the temp is getting in the way of refactorings,

replace all references to that temp with the expression.

Why? (Part of Replace Temp with Query refactoring)


Example:
	
return (anOrder. basePrice() > 100)
double basePrice = anOrder.basePrice();
return (basePrice > 100)
(De)composing methods :

4. Replace Temp with Query
21
What? When you use a temporary variable to hold the result of an
expression, extract the expression into a method and replace all

references to the temp with a method call
Why? Cleaner code
Example:
	
double basePrice = _quantity * _itemPrice;
if (basePrice > 1000)
return basePrice * 0.95;
else
return basePrice * 0.98;
if (basePrice() > 1000)
return basePrice() * 0.95;
else
return basePrice() * 0.98;
…
double basePrice(){
return _quantity * _itemPrice;
}
(De)composing methods :

5. Introduce Explaining Variable
22
What? When you have a complex expression, put the result of the

(parts of the) expression in a temporary variable with a name
that explains the purpose
Why? Breaking down complex expressions for clarity
Example:
if ( (platform.toUpperCase().indexOf(“MAC”) > -1) &&
(browser.toUpperCase().indexOf(“IE”) > -1) &&
wasInitialized() && resize > 0 )
{
//ACTION
}
final boolean isMacOs = platform.toUpperCase().indexOf(“MAC”) > -1;
final boolean isIEBrowser = browser.toUpperCase().indexOf(“IE”) > -1;
final boolean wasResized = resize > 0;
if (isMacOs && isIEBrowser && wasInitialized() && wasResized){
//ACTION
}
(De)composing methods :

6. Split Temporary Variable
23
What? When you assign a temporary variable more than once,
	 but it is not a loop variable nor a collecting temporary
	 variable, make a separate temporary variable for each
	 assignment
Why? Using temps more than once is confusing
Example:
	
double temp = 2 * (_height + _width);
System.out.println (temp);
temp = _height * _width;
System.out.println (temp);
final double perimeter =
2 * (_height + _width);
System.out.println (perimeter);
final double area = _height * _width;
System.out.println (area);
(De)composing methods :

7. Remove Assignments To Parameter
24
What? When the code assigns to a parameter,
use a temporary variable instead
Why? Lack of clarity and confusion between “pass by value”
and “pass by reference”


Example:
	
int discount (int inputVal, int quantity,
int yearToDate){
if (inputVal > 50) inputVal -= 2;
... MORE CODE HERE ... int discount (int inputVal, int quantity,
int yearToDate){
int result = inputVal;
if (inputVal > 50) result -= 2;
... MORE CODE HERE ...
(De)composing methods :

8. Replace Method with Method Object
25
What? When you have local variables but cannot use
	 extract method, turn the method into its own object,
	 with the local variables as its fields
Why? Extracting pieces out of large methods makes things more
comprehensible
Example:
	
Order
price()
PriceCalculator
primaryBasePrice
secondaryBasePrice
compute()
return new PriceCalculator(this). compute()
1
Order
price()
double primaryBasePrice;
double secondaryBasePrice;
// long computation
(De)composing methods :

9. Substitute Algorithm
26
What? When you want to replace an algorithm with a clearer
alternative, replace the body of the method with the
new algorithm
Why? To replace complicated algorithms with clearer ones
Example:
	
String foundPerson(String[] people){
for (int i = 0; i < people.length; i++){
if (people[i]. equals (“John”) ) {
return “John”;
}
if (people[i]. equals (“Jack”) ) {
return “Jack”;
}
}
}
String foundPerson(String[] people){
List candidates = Array.asList(new String[] {“John”, “Jack”})
for (int i = 0; i < people.length; i++)
if (candidates[i]. contains (people[i]))
return people[i];
}
Small refactorings
(de)composing methods [9 refactorings]
moving features between objects [8 refactorings]
organizing data [16 refactorings]
simplifying conditional expressions [8 refactorings]
dealing with generalisation [12 refactorings]
simplifying method calls [15 refactorings]
27
Small Refactorings :

moving features between objects
1. Move Method
2. Move Field
3. Extract Class
4. Inline Class
5. Hide Delegate
6. Remove Middle Man
7. Introduce Foreign Method
8. Introduce Local Extension
= we will zoom in on these
= home reading
Legend:
28
Moving features between objects :

1,2. Move Method / Field
29
What? When a method (resp. field) is used by or uses more features of
another class than its own, create a similar method (resp. field)

in the other class; remove or delegate original method (resp. field)

and redirect all references to it.

Why? Essence of refactoring

Example:
	
Class 1
aMethod()
Class 2
Class 1
Class 2
aMethod()
Moving features between objects :

3. Extract Class
30
What? When you have a class doing work that should be done by two,
create a new class and move the relevant fields and methods to

the new class
Why? Large classes are hard to understand
Example:	
	
PhoneNumber
areaCode
number
getPhoneNumber
1
Person
name
officeAreaCode
officeNumber
homeAreaCode
homeNumber
getOfficePhone
getHomPhone
Person
name
getOfficePhone
getHomePhone
phone
Moving features between objects :

4. Inline Class
31
What? When you have a class that does not do very much, move
all its features into another class and delete it
Why? To remove useless classes (as a result of other refactorings)
Example:	
PhoneNumber
areaCode
number
getPhoneNumber()
1
Person
name
getPhoneNumber()
office-
phone
1
Person
name
officeAreaCode
officeNumber
getPhoneNumber()
Moving features between objects :

5. Hide Delegate
32
What? When you have a client calling a delegate class of an object,
create methods on the server to hide the delegate
Why? Increase encapsulation
Example:	
Person
getDepartment()
Department
getManager()
Person
getManager()
Client Class Client Class
Department
getManager()
Moving features between objects :

6. Remove Middle Man
33
What? When a class is doing too much simple delegation, get the
client to call the delegate directly
Why? To remove too much indirection (as a result of other
refactorings)
Example:
Person
getManager()
Department
Person
getDepartment()
Department
getManager()
Client ClassClient Class
What? When a server class needs an additional method, but you
cannot modify the class, create a method in the client
class with an instance of the server class as its first argument
Why? To introduce one additional service
Example:	
Date newStart = new Date (previousEnd.getYear(),
previousEnd.getMonth(), previousEnd.getDate() + 1);
Date newStart = nextDay(previousEnd);
private static Date nextDay(Date arg) {
return new Date (arg.getYear(),
arg.getMonth(), arg.getDate() + 1);
}
Moving features between objects :

7. Introduce Foreign Method
34
What? When a server class needs several additional methods but you cannot

modify the class, create a new class containing the extra methods;
make the extension class a subclass or wrapper
Why? To introduce several additional services
Example:	
Client Class
nextDayDate(Date): Date
MfDate
nextDay(): Date
Date
Moving features between objects :

8. Introduce Local Extension
35
Small refactorings
(de)composing methods [9 refactorings]
moving features between objects [8 refactorings]
organizing data [16 refactorings]
simplifying conditional expressions [8 refactorings]
dealing with generalisation [12 refactorings]
simplifying method calls [15 refactorings]
36
Small Refactorings :

organizing data
1. Encapsulate field
2. Replace data value with
object
3. Change value to reference
4. Change reference to value
5. Replace array with object
6. Duplicate observed data
7. Change unidirectional
association to bidirectional
8. Change bidirectional
association to unidirectional
9. Replace magic number with
symbolic constant
10. Encapsulate collection
11. Replace record with data class
12. Replace subclass with fields
13-16. Replace type code with
class / subclass / state /
strategy 37
38
Organizing Data :

1. Encapsulate Field
private String name;

public String getName() {

return this.name; }

public void setName(String s) {

this.name = s; }
public String name;
What? There is a public field. Make it private and provide accessors.
Why? Encapsulating state increases modularity, and facilitates code reuse

and maintenance.
When the state of an object is represented as a collection of private

variables, the internal representation can be changed without
modifying the external interface
Example:
39
private Document doc;

public String getContents() {

return this.doc.getContents(); }

public void setContents(String s) {

this.doc.setContents(s); }
public class Document {

private String contents;
public String getContents() {
return this.contents; }
public void setContents(String s) {

this.contents = s; }

}
private String contents;
public String getContents() {
return this.contents; }
public void setContents(String s) {
this.contents = s; }
Organizing Data :

2. Replace Data Value with Object
40
Organizing Data :

13. Replace Type Code with Subclass
What? An immutable type code affects the behaviour of a class
Example:	
Employee
const Engineer=0
const Salesman=1
const Manager=2
type:Int
Employee
Engineer Salesman Manager
41
When? If subclassing cannot be used, e.g. because of dynamic
type changes during object lifetime (e.g. promotion of employees)

Example:	
Employee
const Engineer=0
const Salesman=1
const Manager=2
type:Int
Employee EmployeeType
Engineer Salesman Manager
Organizing Data :

15,16. Replace Type Code with State/Strategy
Makes use of state pattern or strategy design pattern
42
Organizing Data :

12. Replace Subclass with Fields
What? Subclasses vary only in methods that return constant data
Solution: Change methods to superclass fields and eliminate subclasses
Example:
	
Person
sex: [M, F]
Person
Male Female
Similar to replace inheritance with aggregation
Small refactorings
(de)composing methods [9 refactorings]
moving features between objects [8 refactorings]
organizing data [16 refactorings]
simplifying conditional expressions [8 refactorings]
dealing with generalisation [12 refactorings]
simplifying method calls [15 refactorings]
43
Small Refactorings :

simplifying conditional expressions
1. Decompose conditional
2. Consolidate conditional expression
3. Consolidate duplicate conditional fragments
4. Remove control flag
5. Replace nested conditional with guard clauses
6. Replace conditional with polymorphism
7. Introduce null objects
8. Introduce assertion
44
Small refactorings
(de)composing methods [9 refactorings]
moving features between objects [8 refactorings]
organizing data [16 refactorings]
simplifying conditional expressions [8 refactorings]
dealing with generalisation [12 refactorings]
simplifying method calls [15 refactorings]
45
Small Refactorings :

dealing with generalisation
1. Push down method / field
2. Pull up method / field / constructor body
3. Extract subclass / superclass / interface
4. Collapse hierarchy
5. Form template method
6. Replace inheritance with delegation (and vice versa)
46
Dealing with Generalisation:

1. Push Down Method
When behaviour on a superclass is relevant only for some of its subclasses,
move it to those subclasses
Engineer
Employee
getQuota
Salesman
47
Salesman
getQuota
Employee
Engineer
ASCIIPrinter PSPrinter
Printserver
accept
ASCIIPrinter
accept
PSPrinter
accept
Printserver
Dealing with Generalisation:

2. Pull Up Method
Simple variant: look for methods with same name in subclasses that do not appear in
superclass
More complex variant: do not look at the name but at the behaviour of the method
If the method that is being pulled up already exists in the superclass as an abstract method,
make it concrete with the common behaviour
48
When you have 2 classes with similar features
PrintServer FileServer FileserverPrintserver
Outputserver
Dealing with Generalisation:

3. Extract Superclass
49
Small refactorings
(de)composing methods [9 refactorings]
moving features between objects [8 refactorings]
organizing data [16 refactorings]
simplifying conditional expressions [8 refactorings]
dealing with generalisation [12 refactorings]
simplifying method calls [15 refactorings]
50
Small Refactorings :

simplifying method calls
1. Rename method
2. Add parameter
3. Remove parameter
4. Separate query from modifier
5. Parameterize method
6. Replace parameter with method
7. Replace parameter with explicit
methods
8. Preserve whole object
9. Introduce parameter object
10. Remove setting method
11. Hide method
12. Replace constructor with factory
method
13. Encapsulate downcast
14. Replace error code with exception
15. Replace exception with test
51
Simplifying method calls :

9. Introduce Parameter Object
Group parameters that belong together in a
separate object
Customer
amountInvoicedIn(from:Date,to:Date)
amountReceivedIn(from:Date,to:Date)
amountOverdueIn(from:Date,to:Date)
Customer
amountInvoicedIn(r:DateRange)
amountReceivedIn(r:DateRange)
amountOverdueIn(r:DateRange)
DataRange
from : Date
to : Date
52
Simplifying method calls:

14. Replace Error Code with Exception
What? When a method returns a special code to indicate an
	 error, throw an exception instead
Why? Clearly separate normal processing from error processing
Example:
	
int withdraw(int amount) {
if (amount > balance)
return -1
else
{balance -= amount;
return 0}
}
void withdraw(int amount) throws BalanceException {
if (amount > balance) throw new BalanceException();
balance -= amount;
}
53
Categories of refactorings
(according to [Fowler2000])
Small refactorings
(de)composing methods [9]
moving features between objects [8]
organizing data [16]
simplifying conditional expressions [8]
dealing with generalisation [12]
simplifying method calls [15]
Big refactorings
Tease apart inheritance
Extract hierarchy
Convert procedural design to objects
Separate domain from presentation
54
Big refactorings
Require a large amount of time (> 1 month)
Require a degree of agreement among the
development team
No instant satisfaction, no visible progress
55
Big Refactorings
1. Tease apart inheritance
2. Extract hierarchy
3. Convert procedural design to objects
4. Separate domain from presentation
Big refactorings:

1. Tease apart inheritance
Problem
A tangled inheritance hierarchy that is doing 2 jobs at
once
Solution
Create 2 separate hierarchies and use delegation to invoke
one from the other
57
Big refactorings:

1. Tease apart inheritance
Approach
Identify the different jobs done by the hierarchy.
Extract least important job into a separate hierarchy.
Use extract class to create common parent of new hierarchy.
Create appropriate subclasses.
Use move method to move part of the behaviour from the
old hierarchy to the new one.
58
Big refactorings:

1. Tease apart inheritance
59
Window
FullXWin FullMSWin IconXWin
Full Iconised
IconMSWin
WindowImpl
FullXWin
Window
IconisedMSWin
1
Big refactorings:

1. Tease apart inheritance
Related design patterns
Bridge
decouples an abstraction from its
implementation so that the two can vary
independently
Strategy / Visitor / Iterator / State
60
Big refactorings:

2. Extract hierarchy
Problem
An overly-complex class that is doing too much work,
at least in part through many conditional statements.
Solution
Turn class into a hierarchy where each subclass
represents a special case.
61
Big refactorings:

2. Extract hierarchy
Approach
Create a subclass for each special case.
Use one of the following refactorings to return the appropriate subclass
for each variation:
replace constructor with factory method
replace type code with subclasses
replace type code with state/strategy
Take methods with conditional logic and apply:
replace conditional with polymorphism
62
Calculating electricity bills.
Lots of conditional logic needed to cover many different cases:
different charges for summer/winter
different tax rates
different billing plans for personal / business / government / …
reduced rates for persons with

disabilities or social security
Customer
Billing Scheme
Big refactorings:

2. Extract hierarchy (example)
63
Big refactorings:

3. Convert procedural design

into objects
Problem
You have code written in a procedural style.
Solution
Turn the data records into objects, break up the behaviour, and
move the behaviour to the objects.
Smaller refactorings used
extract method, move method, …
64
Big refactorings:

4. Separate domain

from presentation
Goal
Change a two-tier design (user interface/database) into a a
three-tier one (UI/business logic/database).
Solution
Separate domain logic into separate domain classes.
Smaller refactorings used
extract method, move method/field, duplicate observed data, …
65
C. REFACTORING TOOLS
LINGI2252 – PROF. KIM MENS
*
CODE REFACTORING – REFACTORING TOOLS
AUTOMATED CODE REFACTORING TOOLS
Available for all major programming languages

(and OO programming languages in particular)
Java : IntelliJ IDEA, Eclipse, NetBeans, JDeveloper, …
JavaScript : WebStorm, Eclipse, …
C++ : VisualStudio, Eclipse, …
ObjectiveC and SWIFT : XCode
.NET : VisualStudio
Smalltalk, PHP, Ruby, Python, C#, Delphi, …
67
CODE REFACTORING – REFACTORING TOOLS
LIMITATIONS OF MOST REFACTORING TOOLS
Only support for primitive refactorings
class refactorings
add (sub)class to hierarchy, rename class, remove class
method refactorings
add to class, rename, remove, push down, pull up, add parameter, move to
component, extract code
variable refactorings
add to class, rename, remove, push down, pull up, create accessors, abstract
variable
Often no support for higher-level refactorings
68
CODE REFACTORING – REFACTORING TOOLS
REFACTORING IN ECLIPSE
The refactoring tool in Eclipse supports a number of
transformations described in Martin Fowler's book
Refactoring can be accessed via the Refactor menu.
Refactoring commands are also available from the context
menus in many views or appear as quick assists.
CODE REFACTORING – REFACTORING TOOLS
SUPPORTED REFACTORING ACTIONS IN ECLIPSE (2016)
Rename, Move, Change Method Signature
Extract Method, Extract Local Variable, Extract Constant
Inline, Move Type to New File, Use Supertype Where Possible
Convert Anonymous Class to Nested, Convert Local Variable to Field
Extract Superclass, Extract Interface, Extract Class
Push Down, Pull Up, Encapsulate Field
Introduce Parameter Object, Introduce Indirection
Introduce Factory, Introduce Parameter
Generalize Declared Type , Infer Generic Type Arguments
(and more)
CODE REFACTORING – REFACTORING TOOLS 71
CODE REFACTORING – REFACTORING TOOLS 72
CODE REFACTORING – REFACTORING TOOLS 73
D. WORDS OF WARNING
LINGI2252 – PROF. KIM MENS
*
CODE REFACTORING – WORDS OF WARNING
A WORD OF WARNING (1)
Know what you are doing
If not applied well, refactoring may decrease quality rather
than improve it
75
CODE REFACTORING – WORDS OF WARNING
A WORD OF WARNING (1)
“Bad smells” are symptoms that something is wrong
Refactoring are supposed to remove “bad smells”
PhoneNumber
areaCode
number
getPhoneNumber
1
Person
name
officeAreaCode
officeNumber
homeAreaCode
homeNumber
getOfficePhone
getHomPhone
Person
name
getOfficePhone
getHomePhone
phone
1
EXTRACT

CLASS
SMELLS LIKE A
TOO “LARGE CLASS” SMELLS BETTER
NOW…
76
CODE REFACTORING – WORDS OF WARNING
A WORD OF WARNING (1)
Refactoring should not introduce new smells
HumanBeing
Person
name
getOfficePhone
getHomePhone
EXTRACT

SUPERCLASS
Person
name
getOfficePhone
getHomePhone
SMELLS LIKE A
TOO ABSTRACT CLASS
77
CODE REFACTORING – WORDS OF WARNING
NEXT SESSION: INTRODUCTION TO “BAD SMELLS”
Bad code smells
indicate that your code is ripe for refactoring
Refactoring is about
how to change code
Bad smells are about
when to modify it
78
CODE REFACTORING – WORDS OF WARNING
A WORD OF WARNING (2)
Independently applied refactorings can introduce subtle
merge conflicts
79
Bank
Account
Loan
handles
Company
Agency
Account
Loan
handles
Bank Company
represents
Bank
Account
Loan
handles
Company
Safe
EXTRACT

CLASS
CREATE
SUBCLASS
REFACTORING CONFLICT :
In the new version, Safe should not
be handled by Bank, but by Agency
CODE REFACTORING
POSSIBLE QUESTIONS
▸ Give a definition of refactoring in your own words

and illustrate it with a concrete example of a refactoring.
▸ Explain why you should refactor.
▸ Explain when (= at what moment) refactoring should (or should not) be performed.
▸ Like refactoring, performance optimisation does not usually change the behaviour of code
(other than its speed); it only alters the internal structure. So how does it differ from refactoring?
▸ Explain and illustrate one of the following refactorings in detail:
▸ Extract Method, Move Method, Extract Class, Replace Type Code with Subclass, Replace
Subclass with Fields, Pull Up Method, Introduce Parameter Object
▸ Give a concrete example of how a refactoring could accidentally reduce quality.
▸ Give a concrete example of how to independently applied refactorings could accidentally
introduce a subtle merge conflict.

Contenu connexe

Tendances

Hexagonal architecture - message-oriented software design
Hexagonal architecture  - message-oriented software designHexagonal architecture  - message-oriented software design
Hexagonal architecture - message-oriented software designMatthias Noback
 
An Introduction To Jenkins
An Introduction To JenkinsAn Introduction To Jenkins
An Introduction To JenkinsKnoldus Inc.
 
Introduction to MERN Stack
Introduction to MERN StackIntroduction to MERN Stack
Introduction to MERN StackSurya937648
 
Build CICD Pipeline for Container Presentation Slides
Build CICD Pipeline for Container Presentation SlidesBuild CICD Pipeline for Container Presentation Slides
Build CICD Pipeline for Container Presentation SlidesAmazon Web Services
 
What is DevOps | DevOps Introduction | DevOps Training | DevOps Tutorial | Ed...
What is DevOps | DevOps Introduction | DevOps Training | DevOps Tutorial | Ed...What is DevOps | DevOps Introduction | DevOps Training | DevOps Tutorial | Ed...
What is DevOps | DevOps Introduction | DevOps Training | DevOps Tutorial | Ed...Edureka!
 
Git 101: Git and GitHub for Beginners
Git 101: Git and GitHub for Beginners Git 101: Git and GitHub for Beginners
Git 101: Git and GitHub for Beginners HubSpot
 
Introduction to CICD
Introduction to CICDIntroduction to CICD
Introduction to CICDKnoldus Inc.
 
Monoliths and Microservices
Monoliths and Microservices Monoliths and Microservices
Monoliths and Microservices Bozhidar Bozhanov
 
Coding Best Practices
Coding Best PracticesCoding Best Practices
Coding Best Practicesmh_azad
 
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
 
Refactoring 101
Refactoring 101Refactoring 101
Refactoring 101Adam Culp
 
Introduction To Single Page Application
Introduction To Single Page ApplicationIntroduction To Single Page Application
Introduction To Single Page ApplicationKMS Technology
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JSArno Lordkronos
 
Refactoring and code smells
Refactoring and code smellsRefactoring and code smells
Refactoring and code smellsPaul Nguyen
 

Tendances (20)

Hexagonal architecture - message-oriented software design
Hexagonal architecture  - message-oriented software designHexagonal architecture  - message-oriented software design
Hexagonal architecture - message-oriented software design
 
Code smell overview
Code smell overviewCode smell overview
Code smell overview
 
DevOps and Tools
DevOps and ToolsDevOps and Tools
DevOps and Tools
 
An Introduction To Jenkins
An Introduction To JenkinsAn Introduction To Jenkins
An Introduction To Jenkins
 
Code Refactoring
Code RefactoringCode Refactoring
Code Refactoring
 
Introduction to MERN Stack
Introduction to MERN StackIntroduction to MERN Stack
Introduction to MERN Stack
 
Build CICD Pipeline for Container Presentation Slides
Build CICD Pipeline for Container Presentation SlidesBuild CICD Pipeline for Container Presentation Slides
Build CICD Pipeline for Container Presentation Slides
 
Refactoring
RefactoringRefactoring
Refactoring
 
What is DevOps | DevOps Introduction | DevOps Training | DevOps Tutorial | Ed...
What is DevOps | DevOps Introduction | DevOps Training | DevOps Tutorial | Ed...What is DevOps | DevOps Introduction | DevOps Training | DevOps Tutorial | Ed...
What is DevOps | DevOps Introduction | DevOps Training | DevOps Tutorial | Ed...
 
TypeScript - An Introduction
TypeScript - An IntroductionTypeScript - An Introduction
TypeScript - An Introduction
 
Git 101: Git and GitHub for Beginners
Git 101: Git and GitHub for Beginners Git 101: Git and GitHub for Beginners
Git 101: Git and GitHub for Beginners
 
Introduction to CICD
Introduction to CICDIntroduction to CICD
Introduction to CICD
 
Monoliths and Microservices
Monoliths and Microservices Monoliths and Microservices
Monoliths and Microservices
 
Coding Best Practices
Coding Best PracticesCoding Best Practices
Coding Best Practices
 
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
 
Refactoring 101
Refactoring 101Refactoring 101
Refactoring 101
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Introduction To Single Page Application
Introduction To Single Page ApplicationIntroduction To Single Page Application
Introduction To Single Page Application
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JS
 
Refactoring and code smells
Refactoring and code smellsRefactoring and code smells
Refactoring and code smells
 

En vedette

Code Refactoring
Code RefactoringCode Refactoring
Code RefactoringYu-Chih Lin
 
Refactoring code smell
Refactoring code smellRefactoring code smell
Refactoring code smellmartintsch
 
Refaktoryzacja kodu w języku PHP
Refaktoryzacja kodu w języku PHPRefaktoryzacja kodu w języku PHP
Refaktoryzacja kodu w języku PHPDevCastZone
 
"Git Hooked!" Using Git hooks to improve your software development process
"Git Hooked!" Using Git hooks to improve your software development process"Git Hooked!" Using Git hooks to improve your software development process
"Git Hooked!" Using Git hooks to improve your software development processPolished Geek LLC
 
FLTK Summer Course - Part VII - Seventh Impact
FLTK Summer Course - Part VII  - Seventh ImpactFLTK Summer Course - Part VII  - Seventh Impact
FLTK Summer Course - Part VII - Seventh ImpactMichel Alves
 
Introduction to Git Commands and Concepts
Introduction to Git Commands and ConceptsIntroduction to Git Commands and Concepts
Introduction to Git Commands and ConceptsCarl Brown
 
FLTK Summer Course - Part VIII - Eighth Impact
FLTK Summer Course - Part VIII - Eighth ImpactFLTK Summer Course - Part VIII - Eighth Impact
FLTK Summer Course - Part VIII - Eighth ImpactMichel Alves
 
Blisstering drupal module development ppt v1.2
Blisstering drupal module development ppt v1.2Blisstering drupal module development ppt v1.2
Blisstering drupal module development ppt v1.2Anil Sagar
 
Creating Custom Drupal Modules
Creating Custom Drupal ModulesCreating Custom Drupal Modules
Creating Custom Drupal Modulestanoshimi
 
FLTK Summer Course - Part II - Second Impact - Exercises
FLTK Summer Course - Part II - Second Impact - Exercises FLTK Summer Course - Part II - Second Impact - Exercises
FLTK Summer Course - Part II - Second Impact - Exercises Michel Alves
 
FLTK Summer Course - Part I - First Impact - Exercises
FLTK Summer Course - Part I - First Impact - ExercisesFLTK Summer Course - Part I - First Impact - Exercises
FLTK Summer Course - Part I - First Impact - ExercisesMichel Alves
 
FLTK Summer Course - Part III - Third Impact
FLTK Summer Course - Part III - Third ImpactFLTK Summer Course - Part III - Third Impact
FLTK Summer Course - Part III - Third ImpactMichel Alves
 
Code Refactoring - Live Coding Demo (JavaDay 2014)
Code Refactoring - Live Coding Demo (JavaDay 2014)Code Refactoring - Live Coding Demo (JavaDay 2014)
Code Refactoring - Live Coding Demo (JavaDay 2014)Peter Kofler
 
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...Alessandro Molina
 
Servicios web con Python
Servicios web con PythonServicios web con Python
Servicios web con PythonManuel Pérez
 
FLTK Summer Course - Part II - Second Impact
FLTK Summer Course - Part II - Second ImpactFLTK Summer Course - Part II - Second Impact
FLTK Summer Course - Part II - Second ImpactMichel Alves
 
Using Git on the Command Line
Using Git on the Command LineUsing Git on the Command Line
Using Git on the Command LineBrian Richards
 
Git hooks For PHP Developers
Git hooks For PHP DevelopersGit hooks For PHP Developers
Git hooks For PHP DevelopersUmut IŞIK
 
FLTK Summer Course - Part VI - Sixth Impact - Exercises
FLTK Summer Course - Part VI - Sixth Impact - ExercisesFLTK Summer Course - Part VI - Sixth Impact - Exercises
FLTK Summer Course - Part VI - Sixth Impact - ExercisesMichel Alves
 

En vedette (20)

Code Refactoring
Code RefactoringCode Refactoring
Code Refactoring
 
Refactoring code smell
Refactoring code smellRefactoring code smell
Refactoring code smell
 
Refaktoryzacja kodu w języku PHP
Refaktoryzacja kodu w języku PHPRefaktoryzacja kodu w języku PHP
Refaktoryzacja kodu w języku PHP
 
"Git Hooked!" Using Git hooks to improve your software development process
"Git Hooked!" Using Git hooks to improve your software development process"Git Hooked!" Using Git hooks to improve your software development process
"Git Hooked!" Using Git hooks to improve your software development process
 
FLTK Summer Course - Part VII - Seventh Impact
FLTK Summer Course - Part VII  - Seventh ImpactFLTK Summer Course - Part VII  - Seventh Impact
FLTK Summer Course - Part VII - Seventh Impact
 
Introduction to Git Commands and Concepts
Introduction to Git Commands and ConceptsIntroduction to Git Commands and Concepts
Introduction to Git Commands and Concepts
 
FLTK Summer Course - Part VIII - Eighth Impact
FLTK Summer Course - Part VIII - Eighth ImpactFLTK Summer Course - Part VIII - Eighth Impact
FLTK Summer Course - Part VIII - Eighth Impact
 
Blisstering drupal module development ppt v1.2
Blisstering drupal module development ppt v1.2Blisstering drupal module development ppt v1.2
Blisstering drupal module development ppt v1.2
 
Creating Custom Drupal Modules
Creating Custom Drupal ModulesCreating Custom Drupal Modules
Creating Custom Drupal Modules
 
Advanced Git
Advanced GitAdvanced Git
Advanced Git
 
FLTK Summer Course - Part II - Second Impact - Exercises
FLTK Summer Course - Part II - Second Impact - Exercises FLTK Summer Course - Part II - Second Impact - Exercises
FLTK Summer Course - Part II - Second Impact - Exercises
 
FLTK Summer Course - Part I - First Impact - Exercises
FLTK Summer Course - Part I - First Impact - ExercisesFLTK Summer Course - Part I - First Impact - Exercises
FLTK Summer Course - Part I - First Impact - Exercises
 
FLTK Summer Course - Part III - Third Impact
FLTK Summer Course - Part III - Third ImpactFLTK Summer Course - Part III - Third Impact
FLTK Summer Course - Part III - Third Impact
 
Code Refactoring - Live Coding Demo (JavaDay 2014)
Code Refactoring - Live Coding Demo (JavaDay 2014)Code Refactoring - Live Coding Demo (JavaDay 2014)
Code Refactoring - Live Coding Demo (JavaDay 2014)
 
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
 
Servicios web con Python
Servicios web con PythonServicios web con Python
Servicios web con Python
 
FLTK Summer Course - Part II - Second Impact
FLTK Summer Course - Part II - Second ImpactFLTK Summer Course - Part II - Second Impact
FLTK Summer Course - Part II - Second Impact
 
Using Git on the Command Line
Using Git on the Command LineUsing Git on the Command Line
Using Git on the Command Line
 
Git hooks For PHP Developers
Git hooks For PHP DevelopersGit hooks For PHP Developers
Git hooks For PHP Developers
 
FLTK Summer Course - Part VI - Sixth Impact - Exercises
FLTK Summer Course - Part VI - Sixth Impact - ExercisesFLTK Summer Course - Part VI - Sixth Impact - Exercises
FLTK Summer Course - Part VI - Sixth Impact - Exercises
 

Similaire à Code Refactoring Techniques

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
 
Combating software entropy 2-roc1-
Combating software entropy 2-roc1-Combating software entropy 2-roc1-
Combating software entropy 2-roc1-Hammad Rajjoub
 
Generic Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkGeneric Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkAkhil Mittal
 
Agile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddAgile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddSrinivasa GV
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principlesdeonpmeyer
 
Refactoring PHP
Refactoring PHPRefactoring PHP
Refactoring PHPAdam Culp
 
Working Effectively With Legacy Perl Code
Working Effectively With Legacy Perl CodeWorking Effectively With Legacy Perl Code
Working Effectively With Legacy Perl Codeerikmsp
 
Getting Started with Test-Driven Development at Longhorn PHP 2023
Getting Started with Test-Driven Development at Longhorn PHP 2023Getting Started with Test-Driven Development at Longhorn PHP 2023
Getting Started with Test-Driven Development at Longhorn PHP 2023Scott Keck-Warren
 
EKON 23 Code_review_checklist
EKON 23 Code_review_checklistEKON 23 Code_review_checklist
EKON 23 Code_review_checklistMax Kleiner
 
Lecture: Refactoring
Lecture: RefactoringLecture: Refactoring
Lecture: RefactoringMarcus Denker
 
An Introduction to Enterprise Design Patterns
An Introduction to Enterprise Design PatternsAn Introduction to Enterprise Design Patterns
An Introduction to Enterprise Design PatternsAdam Stephensen
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And RefactoringNaresh Jain
 
Refactoring: Improving the design of existing code
Refactoring: Improving the design of existing codeRefactoring: Improving the design of existing code
Refactoring: Improving the design of existing codeKnoldus Inc.
 
Introduction to Refactoring
Introduction to RefactoringIntroduction to Refactoring
Introduction to RefactoringVorleak Chy
 
Metrics ekon 14_2_kleiner
Metrics ekon 14_2_kleinerMetrics ekon 14_2_kleiner
Metrics ekon 14_2_kleinerMax Kleiner
 

Similaire à Code Refactoring Techniques (20)

Refactoring
RefactoringRefactoring
Refactoring
 
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
 
Combating software entropy 2-roc1-
Combating software entropy 2-roc1-Combating software entropy 2-roc1-
Combating software entropy 2-roc1-
 
Generic Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkGeneric Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity Framework
 
Agile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddAgile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tdd
 
Refactoring
RefactoringRefactoring
Refactoring
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
 
Refactoring PHP
Refactoring PHPRefactoring PHP
Refactoring PHP
 
Working Effectively With Legacy Perl Code
Working Effectively With Legacy Perl CodeWorking Effectively With Legacy Perl Code
Working Effectively With Legacy Perl Code
 
Getting Started with Test-Driven Development at Longhorn PHP 2023
Getting Started with Test-Driven Development at Longhorn PHP 2023Getting Started with Test-Driven Development at Longhorn PHP 2023
Getting Started with Test-Driven Development at Longhorn PHP 2023
 
EKON 23 Code_review_checklist
EKON 23 Code_review_checklistEKON 23 Code_review_checklist
EKON 23 Code_review_checklist
 
Best practices tekx
Best practices tekxBest practices tekx
Best practices tekx
 
Refactoring
RefactoringRefactoring
Refactoring
 
Lecture: Refactoring
Lecture: RefactoringLecture: Refactoring
Lecture: Refactoring
 
An Introduction to Enterprise Design Patterns
An Introduction to Enterprise Design PatternsAn Introduction to Enterprise Design Patterns
An Introduction to Enterprise Design Patterns
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
 
Refactoring: Improving the design of existing code
Refactoring: Improving the design of existing codeRefactoring: Improving the design of existing code
Refactoring: Improving the design of existing code
 
Introduction to Refactoring
Introduction to RefactoringIntroduction to Refactoring
Introduction to Refactoring
 
Metrics ekon 14_2_kleiner
Metrics ekon 14_2_kleinerMetrics ekon 14_2_kleiner
Metrics ekon 14_2_kleiner
 

Plus de kim.mens

Software Maintenance and Evolution
Software Maintenance and EvolutionSoftware Maintenance and Evolution
Software Maintenance and Evolutionkim.mens
 
Context-Oriented Programming
Context-Oriented ProgrammingContext-Oriented Programming
Context-Oriented Programmingkim.mens
 
Software Reuse and Object-Oriented Programming
Software Reuse and Object-Oriented ProgrammingSoftware Reuse and Object-Oriented Programming
Software Reuse and Object-Oriented Programmingkim.mens
 
Bad Code Smells
Bad Code SmellsBad Code Smells
Bad Code Smellskim.mens
 
Object-Oriented Design Heuristics
Object-Oriented Design HeuristicsObject-Oriented Design Heuristics
Object-Oriented Design Heuristicskim.mens
 
Software Patterns
Software PatternsSoftware Patterns
Software Patternskim.mens
 
Domain Modelling
Domain ModellingDomain Modelling
Domain Modellingkim.mens
 
Object-Oriented Application Frameworks
Object-Oriented Application FrameworksObject-Oriented Application Frameworks
Object-Oriented Application Frameworkskim.mens
 
Towards a Context-Oriented Software Implementation Framework
Towards a Context-Oriented Software Implementation FrameworkTowards a Context-Oriented Software Implementation Framework
Towards a Context-Oriented Software Implementation Frameworkkim.mens
 
Towards a Taxonomy of Context-Aware Software Variabilty Approaches
Towards a Taxonomy of Context-Aware Software Variabilty ApproachesTowards a Taxonomy of Context-Aware Software Variabilty Approaches
Towards a Taxonomy of Context-Aware Software Variabilty Approacheskim.mens
 
Breaking the Walls: A Unified Vision on Context-Oriented Software Engineering
Breaking the Walls: A Unified Vision on Context-Oriented Software EngineeringBreaking the Walls: A Unified Vision on Context-Oriented Software Engineering
Breaking the Walls: A Unified Vision on Context-Oriented Software Engineeringkim.mens
 
Context-oriented programming
Context-oriented programmingContext-oriented programming
Context-oriented programmingkim.mens
 
Basics of reflection
Basics of reflectionBasics of reflection
Basics of reflectionkim.mens
 
Advanced Reflection in Java
Advanced Reflection in JavaAdvanced Reflection in Java
Advanced Reflection in Javakim.mens
 
Basics of reflection in java
Basics of reflection in javaBasics of reflection in java
Basics of reflection in javakim.mens
 
Reflection in Ruby
Reflection in RubyReflection in Ruby
Reflection in Rubykim.mens
 
Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to Rubykim.mens
 
Introduction to Smalltalk
Introduction to SmalltalkIntroduction to Smalltalk
Introduction to Smalltalkkim.mens
 
A gentle introduction to reflection
A gentle introduction to reflectionA gentle introduction to reflection
A gentle introduction to reflectionkim.mens
 
Managing the Evolution of Information Systems with Intensional Views and Rela...
Managing the Evolution of Information Systems with Intensional Views and Rela...Managing the Evolution of Information Systems with Intensional Views and Rela...
Managing the Evolution of Information Systems with Intensional Views and Rela...kim.mens
 

Plus de kim.mens (20)

Software Maintenance and Evolution
Software Maintenance and EvolutionSoftware Maintenance and Evolution
Software Maintenance and Evolution
 
Context-Oriented Programming
Context-Oriented ProgrammingContext-Oriented Programming
Context-Oriented Programming
 
Software Reuse and Object-Oriented Programming
Software Reuse and Object-Oriented ProgrammingSoftware Reuse and Object-Oriented Programming
Software Reuse and Object-Oriented Programming
 
Bad Code Smells
Bad Code SmellsBad Code Smells
Bad Code Smells
 
Object-Oriented Design Heuristics
Object-Oriented Design HeuristicsObject-Oriented Design Heuristics
Object-Oriented Design Heuristics
 
Software Patterns
Software PatternsSoftware Patterns
Software Patterns
 
Domain Modelling
Domain ModellingDomain Modelling
Domain Modelling
 
Object-Oriented Application Frameworks
Object-Oriented Application FrameworksObject-Oriented Application Frameworks
Object-Oriented Application Frameworks
 
Towards a Context-Oriented Software Implementation Framework
Towards a Context-Oriented Software Implementation FrameworkTowards a Context-Oriented Software Implementation Framework
Towards a Context-Oriented Software Implementation Framework
 
Towards a Taxonomy of Context-Aware Software Variabilty Approaches
Towards a Taxonomy of Context-Aware Software Variabilty ApproachesTowards a Taxonomy of Context-Aware Software Variabilty Approaches
Towards a Taxonomy of Context-Aware Software Variabilty Approaches
 
Breaking the Walls: A Unified Vision on Context-Oriented Software Engineering
Breaking the Walls: A Unified Vision on Context-Oriented Software EngineeringBreaking the Walls: A Unified Vision on Context-Oriented Software Engineering
Breaking the Walls: A Unified Vision on Context-Oriented Software Engineering
 
Context-oriented programming
Context-oriented programmingContext-oriented programming
Context-oriented programming
 
Basics of reflection
Basics of reflectionBasics of reflection
Basics of reflection
 
Advanced Reflection in Java
Advanced Reflection in JavaAdvanced Reflection in Java
Advanced Reflection in Java
 
Basics of reflection in java
Basics of reflection in javaBasics of reflection in java
Basics of reflection in java
 
Reflection in Ruby
Reflection in RubyReflection in Ruby
Reflection in Ruby
 
Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to Ruby
 
Introduction to Smalltalk
Introduction to SmalltalkIntroduction to Smalltalk
Introduction to Smalltalk
 
A gentle introduction to reflection
A gentle introduction to reflectionA gentle introduction to reflection
A gentle introduction to reflection
 
Managing the Evolution of Information Systems with Intensional Views and Rela...
Managing the Evolution of Information Systems with Intensional Views and Rela...Managing the Evolution of Information Systems with Intensional Views and Rela...
Managing the Evolution of Information Systems with Intensional Views and Rela...
 

Dernier

Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 

Dernier (20)

Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 

Code Refactoring Techniques

  • 1. CODE REFACTORING LINGI2252 – PROF. KIM MENS * Slides mostly based on Martin Fowler’s book:
 Refactoring: Improving the Design of Existing Code. ©Addison Wesley, 2000 * (These slides are part of the course LINGI2252 “Software Maintenance and Evolution”, given by Prof. Kim Mens at UCL, Belgium)
  • 2. Refactoring:
 Improving the Design of Existing Code One of the best references on software refactoring,
 with illustrative examples in Java: Refactoring: Improving the Design of Existing Code.
 Martin Fowler. Addison Wesley, 2000. ISBN: 0201485672 See also www.refactoring.com Overview of this presentation A. Refactoring basics B. Categories of refactoring C. Words of warning 2
  • 3. A. REFACTORING BASICS LINGI2252 – PROF. KIM MENS * Based on Chapter 2 of Martin Fowler’s book:
 Refactoring: Improving the Design of Existing Code. ©Addison Wesley, 2000 *
  • 4. What is refactoring? A refactoring is a software transformation that preserves the external behaviour of the software; improves the internal structure of the software. It is a disciplined way to clean up code that minimises the chances of introducing bugs. 4
  • 5. Definition of Refactoring [Fowler2000] [noun] “a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behaviour” [verb] “to restructure software by applying a series of refactorings without changing its observable behaviour” typically with the purpose of making the software easier to understand and modify 5
  • 6. 6 Why should you refactor?
  • 7. Why should you refactor? To improve the design of software To counter code decay (software ageing) refactoring helps code to remain in shape To increase software comprehensibility To find bugs and write more robust code To increase productivity (program faster) on a long term basis, not on a short term basis 7
  • 8. Why should you refactor? To reduce costs of software maintenance To reduce testing automatic refactorings are guaranteed to be behaviour preserving To prepare for / facilitate future customisations To turn an OO application into a framework To introduce design patterns in a behaviourally preserving way 8
  • 9. When should you refactor? Whenever you see the need for it Do it all the time in little bursts Not on a pre-set periodical basis Apply the rule of three 1 st time : implement from scratch 2 nd time : implement something similar by code duplication 3 rd time : do not implement similar things again, but refactor 9
  • 10. When should you refactor? Refactor when adding new features or functions Especially if feature is difficult to integrate with the existing code Refactor during bug fixing If a bug is very hard to trace, refactor first to make the code more understandable, so that you can understand better where the bug is located Refactor during code reviews 10
  • 11. When should you refactor? Refactoring also fits naturally in the agile methods philosophy Is needed to address the principle "Maintain simplicity" Wherever possible, actively work to eliminate complexity from the system By refactoring the code 11
  • 12. What do you tell the manager? When (s)he’s technically aware (s)he’ll understand why refactoring is important. When (s)he’s interested in quality, (s)he’ll understand that refactoring will improve software quality. When (s)he’s only interested in the schedule, don’t tell that you’re doing refactoring, just do it anyway. In the end refactoring will make you more productive. 12
  • 13. When shouldn’t you refactor? When the existing code is such a mess that although you could refactor it, it would be easier to rewrite everything from scratch instead. When you are too close to a deadline. The productivity gain would appear after the deadline and thus be too late. However, when you are not close to a deadline you should never put off refactoring because you don’t have the time. Not having enough time usually is a sign that refactoring is needed. 13
  • 14. B. CATEGORIES OF REFACTORINGS LINGI2252 – PROF. KIM MENS * Based on Martin Fowler’s book:
 Refactoring: Improving the Design of Existing Code. ©Addison Wesley, 2000 *
  • 15. Categories of refactorings Small refactorings (de)composing methods moving features between objects organizing data simplifying conditional expressions dealing with generalisation simplifying method calls Big refactorings Tease apart inheritance Extract hierarchy Convert procedural design to objects Separate domain from presentation 15
  • 16. Small refactorings (de)composing methods [9 refactorings] moving features between objects [8 refactorings] organizing data [16 refactorings] simplifying conditional expressions [8 refactorings] dealing with generalisation [12 refactorings] simplifying method calls [15 refactorings] 16
  • 17. Small Refactorings :
 (de)composing methods 1. Extract Method 2. Inline Method 3. Inline Temp 4. Replace Temp With Query 5. Introduce Explaining Variable 6. Split Temporary Variable 7. Remove Assignments to Parameter 8. Replace Method With Method Object 9. Substitute Algorithm 17 = we will zoom in on these = home reading Legend:
  • 18. (De)composing methods:
 1. Extract Method 18 What? When you have a fragment of code that can be grouped together, turn it into a method with a name that explains the purpose of the method Why? improves clarity, removes redundancy Example: public void accept(Packet p) {
 if ((p.getAddressee() == this) &&
 (this.isASCII(p.getContents())))
 this.print(p);
 else
 super.accept(p); } public void accept(Packet p) { if this.isDestFor(p) this.print(p); else super.accept(p); } public boolean isDestFor(Packet p) { return ((p.getAddressee() == this) && (this.isASCII(p.getContents()))); } Beware of local variables !
  • 19. (Opposite of Extract Method) 
 What? When a method’s body is just as clear as its name, put the method’s body into the body of its caller and remove the method Why? To remove too much indirection and delegation Example: int getRating(){ return moreThanFiveLateDeliveries(); }
 boolean moreThanFiveLateDeliveries(){ return _numberOfLateDeliveries > 5; } (De)composing methods :
 2. Inline Method 19 int getRating(){ return (_numberOfLateDeliveries > 5); }
  • 20. (De)composing methods :
 3. Inline Temp 20 What? When you have a temp that is assigned once with a simple expression, and the temp is getting in the way of refactorings,
 replace all references to that temp with the expression.
 Why? (Part of Replace Temp with Query refactoring) 
 Example: return (anOrder. basePrice() > 100) double basePrice = anOrder.basePrice(); return (basePrice > 100)
  • 21. (De)composing methods :
 4. Replace Temp with Query 21 What? When you use a temporary variable to hold the result of an expression, extract the expression into a method and replace all
 references to the temp with a method call Why? Cleaner code Example: double basePrice = _quantity * _itemPrice; if (basePrice > 1000) return basePrice * 0.95; else return basePrice * 0.98; if (basePrice() > 1000) return basePrice() * 0.95; else return basePrice() * 0.98; … double basePrice(){ return _quantity * _itemPrice; }
  • 22. (De)composing methods :
 5. Introduce Explaining Variable 22 What? When you have a complex expression, put the result of the
 (parts of the) expression in a temporary variable with a name that explains the purpose Why? Breaking down complex expressions for clarity Example: if ( (platform.toUpperCase().indexOf(“MAC”) > -1) && (browser.toUpperCase().indexOf(“IE”) > -1) && wasInitialized() && resize > 0 ) { //ACTION } final boolean isMacOs = platform.toUpperCase().indexOf(“MAC”) > -1; final boolean isIEBrowser = browser.toUpperCase().indexOf(“IE”) > -1; final boolean wasResized = resize > 0; if (isMacOs && isIEBrowser && wasInitialized() && wasResized){ //ACTION }
  • 23. (De)composing methods :
 6. Split Temporary Variable 23 What? When you assign a temporary variable more than once, but it is not a loop variable nor a collecting temporary variable, make a separate temporary variable for each assignment Why? Using temps more than once is confusing Example: double temp = 2 * (_height + _width); System.out.println (temp); temp = _height * _width; System.out.println (temp); final double perimeter = 2 * (_height + _width); System.out.println (perimeter); final double area = _height * _width; System.out.println (area);
  • 24. (De)composing methods :
 7. Remove Assignments To Parameter 24 What? When the code assigns to a parameter, use a temporary variable instead Why? Lack of clarity and confusion between “pass by value” and “pass by reference” 
 Example: int discount (int inputVal, int quantity, int yearToDate){ if (inputVal > 50) inputVal -= 2; ... MORE CODE HERE ... int discount (int inputVal, int quantity, int yearToDate){ int result = inputVal; if (inputVal > 50) result -= 2; ... MORE CODE HERE ...
  • 25. (De)composing methods :
 8. Replace Method with Method Object 25 What? When you have local variables but cannot use extract method, turn the method into its own object, with the local variables as its fields Why? Extracting pieces out of large methods makes things more comprehensible Example: Order price() PriceCalculator primaryBasePrice secondaryBasePrice compute() return new PriceCalculator(this). compute() 1 Order price() double primaryBasePrice; double secondaryBasePrice; // long computation
  • 26. (De)composing methods :
 9. Substitute Algorithm 26 What? When you want to replace an algorithm with a clearer alternative, replace the body of the method with the new algorithm Why? To replace complicated algorithms with clearer ones Example: String foundPerson(String[] people){ for (int i = 0; i < people.length; i++){ if (people[i]. equals (“John”) ) { return “John”; } if (people[i]. equals (“Jack”) ) { return “Jack”; } } } String foundPerson(String[] people){ List candidates = Array.asList(new String[] {“John”, “Jack”}) for (int i = 0; i < people.length; i++) if (candidates[i]. contains (people[i])) return people[i]; }
  • 27. Small refactorings (de)composing methods [9 refactorings] moving features between objects [8 refactorings] organizing data [16 refactorings] simplifying conditional expressions [8 refactorings] dealing with generalisation [12 refactorings] simplifying method calls [15 refactorings] 27
  • 28. Small Refactorings :
 moving features between objects 1. Move Method 2. Move Field 3. Extract Class 4. Inline Class 5. Hide Delegate 6. Remove Middle Man 7. Introduce Foreign Method 8. Introduce Local Extension = we will zoom in on these = home reading Legend: 28
  • 29. Moving features between objects :
 1,2. Move Method / Field 29 What? When a method (resp. field) is used by or uses more features of another class than its own, create a similar method (resp. field)
 in the other class; remove or delegate original method (resp. field)
 and redirect all references to it.
 Why? Essence of refactoring
 Example: Class 1 aMethod() Class 2 Class 1 Class 2 aMethod()
  • 30. Moving features between objects :
 3. Extract Class 30 What? When you have a class doing work that should be done by two, create a new class and move the relevant fields and methods to
 the new class Why? Large classes are hard to understand Example: PhoneNumber areaCode number getPhoneNumber 1 Person name officeAreaCode officeNumber homeAreaCode homeNumber getOfficePhone getHomPhone Person name getOfficePhone getHomePhone phone
  • 31. Moving features between objects :
 4. Inline Class 31 What? When you have a class that does not do very much, move all its features into another class and delete it Why? To remove useless classes (as a result of other refactorings) Example: PhoneNumber areaCode number getPhoneNumber() 1 Person name getPhoneNumber() office- phone 1 Person name officeAreaCode officeNumber getPhoneNumber()
  • 32. Moving features between objects :
 5. Hide Delegate 32 What? When you have a client calling a delegate class of an object, create methods on the server to hide the delegate Why? Increase encapsulation Example: Person getDepartment() Department getManager() Person getManager() Client Class Client Class Department getManager()
  • 33. Moving features between objects :
 6. Remove Middle Man 33 What? When a class is doing too much simple delegation, get the client to call the delegate directly Why? To remove too much indirection (as a result of other refactorings) Example: Person getManager() Department Person getDepartment() Department getManager() Client ClassClient Class
  • 34. What? When a server class needs an additional method, but you cannot modify the class, create a method in the client class with an instance of the server class as its first argument Why? To introduce one additional service Example: Date newStart = new Date (previousEnd.getYear(), previousEnd.getMonth(), previousEnd.getDate() + 1); Date newStart = nextDay(previousEnd); private static Date nextDay(Date arg) { return new Date (arg.getYear(), arg.getMonth(), arg.getDate() + 1); } Moving features between objects :
 7. Introduce Foreign Method 34
  • 35. What? When a server class needs several additional methods but you cannot
 modify the class, create a new class containing the extra methods; make the extension class a subclass or wrapper Why? To introduce several additional services Example: Client Class nextDayDate(Date): Date MfDate nextDay(): Date Date Moving features between objects :
 8. Introduce Local Extension 35
  • 36. Small refactorings (de)composing methods [9 refactorings] moving features between objects [8 refactorings] organizing data [16 refactorings] simplifying conditional expressions [8 refactorings] dealing with generalisation [12 refactorings] simplifying method calls [15 refactorings] 36
  • 37. Small Refactorings :
 organizing data 1. Encapsulate field 2. Replace data value with object 3. Change value to reference 4. Change reference to value 5. Replace array with object 6. Duplicate observed data 7. Change unidirectional association to bidirectional 8. Change bidirectional association to unidirectional 9. Replace magic number with symbolic constant 10. Encapsulate collection 11. Replace record with data class 12. Replace subclass with fields 13-16. Replace type code with class / subclass / state / strategy 37
  • 38. 38 Organizing Data :
 1. Encapsulate Field private String name;
 public String getName() {
 return this.name; }
 public void setName(String s) {
 this.name = s; } public String name; What? There is a public field. Make it private and provide accessors. Why? Encapsulating state increases modularity, and facilitates code reuse
 and maintenance. When the state of an object is represented as a collection of private
 variables, the internal representation can be changed without modifying the external interface Example:
  • 39. 39 private Document doc;
 public String getContents() {
 return this.doc.getContents(); }
 public void setContents(String s) {
 this.doc.setContents(s); } public class Document {
 private String contents; public String getContents() { return this.contents; } public void setContents(String s) {
 this.contents = s; }
 } private String contents; public String getContents() { return this.contents; } public void setContents(String s) { this.contents = s; } Organizing Data :
 2. Replace Data Value with Object
  • 40. 40 Organizing Data :
 13. Replace Type Code with Subclass What? An immutable type code affects the behaviour of a class Example: Employee const Engineer=0 const Salesman=1 const Manager=2 type:Int Employee Engineer Salesman Manager
  • 41. 41 When? If subclassing cannot be used, e.g. because of dynamic type changes during object lifetime (e.g. promotion of employees)
 Example: Employee const Engineer=0 const Salesman=1 const Manager=2 type:Int Employee EmployeeType Engineer Salesman Manager Organizing Data :
 15,16. Replace Type Code with State/Strategy Makes use of state pattern or strategy design pattern
  • 42. 42 Organizing Data :
 12. Replace Subclass with Fields What? Subclasses vary only in methods that return constant data Solution: Change methods to superclass fields and eliminate subclasses Example: Person sex: [M, F] Person Male Female Similar to replace inheritance with aggregation
  • 43. Small refactorings (de)composing methods [9 refactorings] moving features between objects [8 refactorings] organizing data [16 refactorings] simplifying conditional expressions [8 refactorings] dealing with generalisation [12 refactorings] simplifying method calls [15 refactorings] 43
  • 44. Small Refactorings :
 simplifying conditional expressions 1. Decompose conditional 2. Consolidate conditional expression 3. Consolidate duplicate conditional fragments 4. Remove control flag 5. Replace nested conditional with guard clauses 6. Replace conditional with polymorphism 7. Introduce null objects 8. Introduce assertion 44
  • 45. Small refactorings (de)composing methods [9 refactorings] moving features between objects [8 refactorings] organizing data [16 refactorings] simplifying conditional expressions [8 refactorings] dealing with generalisation [12 refactorings] simplifying method calls [15 refactorings] 45
  • 46. Small Refactorings :
 dealing with generalisation 1. Push down method / field 2. Pull up method / field / constructor body 3. Extract subclass / superclass / interface 4. Collapse hierarchy 5. Form template method 6. Replace inheritance with delegation (and vice versa) 46
  • 47. Dealing with Generalisation:
 1. Push Down Method When behaviour on a superclass is relevant only for some of its subclasses, move it to those subclasses Engineer Employee getQuota Salesman 47 Salesman getQuota Employee Engineer
  • 48. ASCIIPrinter PSPrinter Printserver accept ASCIIPrinter accept PSPrinter accept Printserver Dealing with Generalisation:
 2. Pull Up Method Simple variant: look for methods with same name in subclasses that do not appear in superclass More complex variant: do not look at the name but at the behaviour of the method If the method that is being pulled up already exists in the superclass as an abstract method, make it concrete with the common behaviour 48
  • 49. When you have 2 classes with similar features PrintServer FileServer FileserverPrintserver Outputserver Dealing with Generalisation:
 3. Extract Superclass 49
  • 50. Small refactorings (de)composing methods [9 refactorings] moving features between objects [8 refactorings] organizing data [16 refactorings] simplifying conditional expressions [8 refactorings] dealing with generalisation [12 refactorings] simplifying method calls [15 refactorings] 50
  • 51. Small Refactorings :
 simplifying method calls 1. Rename method 2. Add parameter 3. Remove parameter 4. Separate query from modifier 5. Parameterize method 6. Replace parameter with method 7. Replace parameter with explicit methods 8. Preserve whole object 9. Introduce parameter object 10. Remove setting method 11. Hide method 12. Replace constructor with factory method 13. Encapsulate downcast 14. Replace error code with exception 15. Replace exception with test 51
  • 52. Simplifying method calls :
 9. Introduce Parameter Object Group parameters that belong together in a separate object Customer amountInvoicedIn(from:Date,to:Date) amountReceivedIn(from:Date,to:Date) amountOverdueIn(from:Date,to:Date) Customer amountInvoicedIn(r:DateRange) amountReceivedIn(r:DateRange) amountOverdueIn(r:DateRange) DataRange from : Date to : Date 52
  • 53. Simplifying method calls:
 14. Replace Error Code with Exception What? When a method returns a special code to indicate an error, throw an exception instead Why? Clearly separate normal processing from error processing Example: int withdraw(int amount) { if (amount > balance) return -1 else {balance -= amount; return 0} } void withdraw(int amount) throws BalanceException { if (amount > balance) throw new BalanceException(); balance -= amount; } 53
  • 54. Categories of refactorings (according to [Fowler2000]) Small refactorings (de)composing methods [9] moving features between objects [8] organizing data [16] simplifying conditional expressions [8] dealing with generalisation [12] simplifying method calls [15] Big refactorings Tease apart inheritance Extract hierarchy Convert procedural design to objects Separate domain from presentation 54
  • 55. Big refactorings Require a large amount of time (> 1 month) Require a degree of agreement among the development team No instant satisfaction, no visible progress 55
  • 56. Big Refactorings 1. Tease apart inheritance 2. Extract hierarchy 3. Convert procedural design to objects 4. Separate domain from presentation
  • 57. Big refactorings:
 1. Tease apart inheritance Problem A tangled inheritance hierarchy that is doing 2 jobs at once Solution Create 2 separate hierarchies and use delegation to invoke one from the other 57
  • 58. Big refactorings:
 1. Tease apart inheritance Approach Identify the different jobs done by the hierarchy. Extract least important job into a separate hierarchy. Use extract class to create common parent of new hierarchy. Create appropriate subclasses. Use move method to move part of the behaviour from the old hierarchy to the new one. 58
  • 59. Big refactorings:
 1. Tease apart inheritance 59 Window FullXWin FullMSWin IconXWin Full Iconised IconMSWin WindowImpl FullXWin Window IconisedMSWin 1
  • 60. Big refactorings:
 1. Tease apart inheritance Related design patterns Bridge decouples an abstraction from its implementation so that the two can vary independently Strategy / Visitor / Iterator / State 60
  • 61. Big refactorings:
 2. Extract hierarchy Problem An overly-complex class that is doing too much work, at least in part through many conditional statements. Solution Turn class into a hierarchy where each subclass represents a special case. 61
  • 62. Big refactorings:
 2. Extract hierarchy Approach Create a subclass for each special case. Use one of the following refactorings to return the appropriate subclass for each variation: replace constructor with factory method replace type code with subclasses replace type code with state/strategy Take methods with conditional logic and apply: replace conditional with polymorphism 62
  • 63. Calculating electricity bills. Lots of conditional logic needed to cover many different cases: different charges for summer/winter different tax rates different billing plans for personal / business / government / … reduced rates for persons with
 disabilities or social security Customer Billing Scheme Big refactorings:
 2. Extract hierarchy (example) 63
  • 64. Big refactorings:
 3. Convert procedural design
 into objects Problem You have code written in a procedural style. Solution Turn the data records into objects, break up the behaviour, and move the behaviour to the objects. Smaller refactorings used extract method, move method, … 64
  • 65. Big refactorings:
 4. Separate domain
 from presentation Goal Change a two-tier design (user interface/database) into a a three-tier one (UI/business logic/database). Solution Separate domain logic into separate domain classes. Smaller refactorings used extract method, move method/field, duplicate observed data, … 65
  • 66. C. REFACTORING TOOLS LINGI2252 – PROF. KIM MENS *
  • 67. CODE REFACTORING – REFACTORING TOOLS AUTOMATED CODE REFACTORING TOOLS Available for all major programming languages
 (and OO programming languages in particular) Java : IntelliJ IDEA, Eclipse, NetBeans, JDeveloper, … JavaScript : WebStorm, Eclipse, … C++ : VisualStudio, Eclipse, … ObjectiveC and SWIFT : XCode .NET : VisualStudio Smalltalk, PHP, Ruby, Python, C#, Delphi, … 67
  • 68. CODE REFACTORING – REFACTORING TOOLS LIMITATIONS OF MOST REFACTORING TOOLS Only support for primitive refactorings class refactorings add (sub)class to hierarchy, rename class, remove class method refactorings add to class, rename, remove, push down, pull up, add parameter, move to component, extract code variable refactorings add to class, rename, remove, push down, pull up, create accessors, abstract variable Often no support for higher-level refactorings 68
  • 69. CODE REFACTORING – REFACTORING TOOLS REFACTORING IN ECLIPSE The refactoring tool in Eclipse supports a number of transformations described in Martin Fowler's book Refactoring can be accessed via the Refactor menu. Refactoring commands are also available from the context menus in many views or appear as quick assists.
  • 70. CODE REFACTORING – REFACTORING TOOLS SUPPORTED REFACTORING ACTIONS IN ECLIPSE (2016) Rename, Move, Change Method Signature Extract Method, Extract Local Variable, Extract Constant Inline, Move Type to New File, Use Supertype Where Possible Convert Anonymous Class to Nested, Convert Local Variable to Field Extract Superclass, Extract Interface, Extract Class Push Down, Pull Up, Encapsulate Field Introduce Parameter Object, Introduce Indirection Introduce Factory, Introduce Parameter Generalize Declared Type , Infer Generic Type Arguments (and more)
  • 71. CODE REFACTORING – REFACTORING TOOLS 71
  • 72. CODE REFACTORING – REFACTORING TOOLS 72
  • 73. CODE REFACTORING – REFACTORING TOOLS 73
  • 74. D. WORDS OF WARNING LINGI2252 – PROF. KIM MENS *
  • 75. CODE REFACTORING – WORDS OF WARNING A WORD OF WARNING (1) Know what you are doing If not applied well, refactoring may decrease quality rather than improve it 75
  • 76. CODE REFACTORING – WORDS OF WARNING A WORD OF WARNING (1) “Bad smells” are symptoms that something is wrong Refactoring are supposed to remove “bad smells” PhoneNumber areaCode number getPhoneNumber 1 Person name officeAreaCode officeNumber homeAreaCode homeNumber getOfficePhone getHomPhone Person name getOfficePhone getHomePhone phone 1 EXTRACT
 CLASS SMELLS LIKE A TOO “LARGE CLASS” SMELLS BETTER NOW… 76
  • 77. CODE REFACTORING – WORDS OF WARNING A WORD OF WARNING (1) Refactoring should not introduce new smells HumanBeing Person name getOfficePhone getHomePhone EXTRACT
 SUPERCLASS Person name getOfficePhone getHomePhone SMELLS LIKE A TOO ABSTRACT CLASS 77
  • 78. CODE REFACTORING – WORDS OF WARNING NEXT SESSION: INTRODUCTION TO “BAD SMELLS” Bad code smells indicate that your code is ripe for refactoring Refactoring is about how to change code Bad smells are about when to modify it 78
  • 79. CODE REFACTORING – WORDS OF WARNING A WORD OF WARNING (2) Independently applied refactorings can introduce subtle merge conflicts 79 Bank Account Loan handles Company Agency Account Loan handles Bank Company represents Bank Account Loan handles Company Safe EXTRACT
 CLASS CREATE SUBCLASS REFACTORING CONFLICT : In the new version, Safe should not be handled by Bank, but by Agency
  • 80.
  • 81. CODE REFACTORING POSSIBLE QUESTIONS ▸ Give a definition of refactoring in your own words
 and illustrate it with a concrete example of a refactoring. ▸ Explain why you should refactor. ▸ Explain when (= at what moment) refactoring should (or should not) be performed. ▸ Like refactoring, performance optimisation does not usually change the behaviour of code (other than its speed); it only alters the internal structure. So how does it differ from refactoring? ▸ Explain and illustrate one of the following refactorings in detail: ▸ Extract Method, Move Method, Extract Class, Replace Type Code with Subclass, Replace Subclass with Fields, Pull Up Method, Introduce Parameter Object ▸ Give a concrete example of how a refactoring could accidentally reduce quality. ▸ Give a concrete example of how to independently applied refactorings could accidentally introduce a subtle merge conflict.