KEMBAR78
Refactoring 1 | PDF | Computer Science | Systems Architecture
0% found this document useful (0 votes)
11 views44 pages

Refactoring 1

Refactoring is a structured process aimed at improving code quality while preserving its external behavior. It involves techniques to evolve software design incrementally as requirements change, with benefits including reduced code size and improved maintainability. The document also outlines various types of refactoring, identifies 'bad smells' in code, and emphasizes the importance of refactoring for better understanding and faster programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views44 pages

Refactoring 1

Refactoring is a structured process aimed at improving code quality while preserving its external behavior. It involves techniques to evolve software design incrementally as requirements change, with benefits including reduced code size and improved maintainability. The document also outlines various types of refactoring, identifies 'bad smells' in code, and emphasizes the importance of refactoring for better understanding and faster programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Lecture # 1

Refactoring
‫اَللﱣ ُه ﱠم فَ ِقّ ْهنِا فِى ال ِ ّد ي ِْن‬

‫اے ﷲ! ہميں دين کی سمجه عطا فرما۔‬


O Allah! Grant us understanding of Deen.

(Sahih Al-Bukhari)
What is Refactoring?
Refactoring is a disciplined process of applying structural
transformations in the code such that the program is
improved in terms of quality and its external behavior is
preserved.

Badly Written Improved


Software Refactoring
Software
Refactoring in General
 Opdyke (1992)
 Presented preconditions for twenty-three primitive refactorings.
 Definition of scope of refactoring involving a public variable is
limited to the class which contains it and its subclasses.
 Roberts (1999)
 extended the definition of refactoring by adding postcondition
assertions.
 Fowler’s refactoring catalog (1999)
 Consists of 72 refactoring guidelines in natural language.
 Consists of both low and high level refactorings, where bigger
refactorings use smaller refactorings to complete the process.
Fowler’s Catalogue
 Fowler et al.‘s catalog on Refactoring
 22 Bad smells
 72 refactorings
 Overview
 Mechanics
 Examples

 Non-formal presentation –widely adopted and used


 Most comprehensive text on refactoring available
Refactoring should include...

• Evaluation of its preconditions


1

• Execution of its mechanics


2

• Execution of corrective actions


3

• Verification
4
Program Properties and Behavior
Preservation

Semantic
Inheritance
Equivalence

Type
Compatibili
Scope ty

Rules for behavior Preservation


Why is Refactoring Useful?
 The idea behind refactoring is to acknowledge
that it will be difficult to get a design right the
first time
 and as a program’s requirements change, the design
may need to change
 refactoring provides techniques for evolving the
design in small incremental steps
 Benefits
 Often code size is reduced after a refactoring
 Confusing structures are transformed into simpler
structures which are easier to maintain and
understand

11
Types of Refactoring (based on process)
 Floss refactoring:
 Small.
 Frequently performed
 Mixed with some other tasks(it’s not an exclusive task to refactor).
 Keeps code healthy.
 Perceived as the best practice.
 Difficult to separate the impact of refactoring process from the
other task
 Root canal refactoring:
 Big.
 Not frequent.
 It is performed as just refactoring.
 Corrective process.
 Perceived as an emergency procedure.
 Easy to verify the correctness of refactoring
Types of Refactoring (based on size)
 Primitive Refactoring- Small, atomic refactorings
 Change method name
 Create method etc.
 Composite Refactoring –These composite
refactorings are usually defined as a sequence of
primitive refactorings as well as composite
refactorings, and reflect more complex behaviour-
preserving transformations
 Extract method
 Move method
 Pull up method
Types of Refactoring (based on impact)
 Refactoring inside method body
 Limited scope
 Clients outside method body not impacted
 Replace temp with query
 Substitute Algorithm
 Extract method
 Refactoring impact the public interface for the clients
 Wide scope
 Any change in the method signature
 Moving a method/ field to another class
 Extracting class
A (Very) Simple Example
Consolidate Duplicate Conditional Fragments

if (isSpecialDeal()) {
if (isSpecialDeal())
total = price * 0.95;
total = price * 0.95;
send ();
else
} total = price * 0.98;
else {
total = price * 0.98; send ();
send ();
}

15
A (Very) Simple Example
Better Still

if (isSpecialDeal())
if (isSpecialDeal())
factor = 0.95;
total = price * 0.95;
else
else
factor = 0.98;
total = price * 0.98;
total = price * factor;
send ();
send ();

16
Why should you refactor?
 Refactoring improves the design of software without
refactoring, a design will “decay” as people make changes
to a software system
 Refactoring makes software easier to understand because
structure is improved, duplicated code is eliminated, etc.
 Refactoring helps you find bugs
 Refactoring promotes a deep understanding of the code at
hand, and this understanding aids the programmer in
finding bugs and anticipating potential bugs
 Refactoring helps you program faster because a good
design enables progress

17
Refactoring versus Rewriting
 Code has to work mostly correctly before you refactor.
 If the current code just does not work, do not refactor.
Rewrite instead!

18
Optimization versus Refactoring
 The purpose of refactoring is to make software easier to
understand and modify
 Performance optimizations often involve making code
harder to understand (but faster!)

19
Optimization versus Refactoring

for (i=0; i < N; i++) if (cond1) {

{ for (i=0; i < N; i++) {


//1…
// condition does not // xyz
// change inside the }
else if (cond2) {
// loop for (i=0; i < N; i++) {
//2…
// xyz
if (cond1) {//1…} }
else if (cond2) {//2…} else {
for (i=0; i < N; i++) {
else {//3…} //3…
// xyz // xyz
}
20 } }
Optimization versus Refactoring

There is no apriori reason to believe that


refactored code is "more optimized" in
terms of resources consumed during
execution;
Refactoring is really about improving code
maintainability.
Often more maintainable code is less
resource efficient than highly-tuned code.
21
Anyone can write code that
computers can understand,
good programmers write code
that humans can understand!

22
Refactoring: Where to Start?
 How do you identify code that needs to be refactored?

“Bad Smells” in
Code

23
24
Identifying bad smells

25
Duplicated Code
If the same code structure is repeated. It is bad because if
you modify one instance of duplicated code but not the others,
you (may) have introduced a bug!

 Extract Method - gather duplicated code


Simplest – duplication in the same class.
 Pull Up Method - move to a common parent
In sibling classes. Extract method + Pull Up Method.
 Form Template Method - gather similar parts, leaving holes.
Similar but not equal code in sibling classes.
 Substitute Algorithm - choose the clearer algorithm
 Extract class - create a new class with the duplicated code.
For duplication in unrelated classes.
27
Long Method

If the body of a method is over a page (choose your page size) .


Long methods are more difficult to understand; performance concerns
with respect to lots of short methods are largely obsolete

 Extract Method - extract related behavior. The need for


comments is a good heuristic.
 Replace Temp with Query - remove temporaries when they
obscure meaning.
 Might enable extract method.
 Introduce Parameter Object / Preserve Whole Object - slim down
parameter lists by making them into objects.
 Extract Method might lead to long parameter lists.
 Replace Method with Method Object – If still too many
parameters. Heavy machinery.
 Decompose Conditionals - conditional and loops can be moved to
their own methods
Extract Method
Breaking a Method
int minimum (int a[ ], int from, int
void swap (int &x, int &y)
to)
{
{
int temp = x;
int min = from;
x = y;
for (int i = from; i <= to; i++)
y = temp;
if (a[i] < a[min]) min = i;
}
return min;
}
for (i=0; i < N-1; i++) {
min = i;
for (j = i; j < N; j++) for (i=0; i < N-1; i++) {
if (a[j] < a[min]) min = j; min = minimum (a, i, N-
temp = a[i]; 1);
a[i] = a[min]; swap(a[i], a[min]);
a[min] = temp; }
}
30
Large Class

If a class is doing too much: has too many variables or too


many methods. Large classes try to do too much, which
reduces cohesion

 Extract Class - to bundle variables or methods.


 Extract Subclass – A class has features that are used only by
some instances.
 Extract interface – determine how clients use the class. Provide
ideas on breaking the class.
 Duplicate Observed Class – For a presentation class that
includes domain functionality. Move functionality to a domain
object. Set up an Observer.
Extract Class
Extract subclass
Long Parameter List

A method does not need many parameters, only enough to be able to


retrieve what it needs. Long parameter lists are hard to understand
and maintain.They can become inconsistent.
The clue – pass objects: Use objects for packing data.
Penalty – might increase dependency among objects.

 Replace Parameter with Method - parameters result from a method


call on a reachable object  remove the parameters; let the object
invoke the method.
 Preserve Whole Object – replace parameters that result from an
object by the object itself.
 Introduce Parameter Object - turn several parameters into an object.
Preserve whole object
Replace parameter with method
Divergent Change

1. If you find yourself repeatedly changing the same class for


different requirement variations – then there is probably
something wrong with it.
2. A class should react to a single kind of variation – cohesion
principle.
3. Deals with cohesion; symptom: one type of change requires
changing one subset of methods; another type of change
requires changing another subset

 Extract Class - group functionality commonly changed into a


class
Shotgun Surgery
1. If you find yourself making a lot of small changes for
each desired change.
2. Small changes are hard to maintain. a change requires
lots of little changes in a lot of different classes

Opposite of divergent change. Ideal:


common changes  classes is a 1:1 relationships.

 Move Method/Field - pull all the changes into a single class


(existing or new).
 Inline Class - group a bunch of behaviors together in an
existing class (might imply divergent change).
Move method
Inline Class
Feature Envy

1. A method requires lots of information from some other


class (move it closer!)
2. If a method seems more interested in a class other than the
class it actually is in – move it to where it belongs.
3. Strategy and Visitor break this rule – separate behavior from
the data it works on. Answer the Divergent Change smell.

 Move Method - move the method to the desired class.


 Extract Method + Move Method - if only part of the method
shows the symptoms Or if the method uses data from
several classes.
Pull up method
Form Template Method
Push Down Method

You might also like