Re Factoring
Re Factoring
UML to Code
• Model to code
• Model space
• Source code space
Refactoring
Model
transformation
Reverse Another
engineering Program
System Model
(in UML)
Model space Source code space
Model Transformation Example
Class model before transformation:
User LeagueOwner
-email:String -maxNumLeagues:int
+getEmail():String +getMaxNumLeagues():int
+setEmail(e:String) +setNaxNumLeagues(n:int)
+notify(msg:String)
• Refactoring is:
• restructuring (rearranging) code...
• ...in a series of small, semantics-preserving
transformations (i.e. the code keeps working)...
• ...in order to make the code easier to maintain and
modify
• Refactoring is not just any old restructuring
• You need to keep the code working
• You need small steps that preserve semantics
• You need to have unit tests to prove the code works
• There are numerous well-known refactoring
techniques
• You should be at least somewhat familiar with these
before inventing your own
8
When to refactor
9
Example 1: switch statements
10
Example 1, continued
• class Animal {
final int MAMMAL = 0, BIRD = 1, REPTILE = 2;
int myKind; // set in constructor
...
String getSkin() {
switch (myKind) {
case MAMMAL: return "hair";
case BIRD: return "feathers";
case REPTILE: return "scales";
default: return “skin";
}
}
}
11
Example 1, improved
• class Animal {
String getSkin() { return “skin"; }
}
class Mammal extends Animal {
String getSkin() { return "hair"; }
}
class Bird extends Animal {
String getSkin() { return "feathers"; }
}
class Reptile extends Animal {
String getSkin() { return "scales"; }
}
12
How is this an improvement?
13
Bad Smell Examples
14
Extract Method Refactoring Example
Void readStudentDetails() { … }
16
Encapsulate Field Example
class Student {
Public Vector marks,
}
class Student {
protected Vector marks;
Vector getMarks(){
return marks;
}
}
17
Parameterize Method Example
class Handling{
public void handlePut() { }
public void handleGet() { }
}
class Handling{
public void handle(ServiceType st) {
...
}
}
18
Replace a Constant Number with Symbolic
Constant
double potentialEnergy(double mass, double
height) {
return mass * height * 9.81;
}
20