CPSC 210
D3: Refactoring
馃崉聽馃悩聽馃聽馃悷聽馃悕聽馃聽馃惛 馃馃尦聽馃尭聽馃崜聽馃聽馃崕聽馃馃尶
Learning Goals
- To improve the design of an existing code base through refactoring
- To improve coupling聽by abstracting duplicated code into methods
- To improve cohesion by splitting up classes
Cohesion (SRP): High = Good
Coupling: Low = Good
Refactoring
Improving code structure without changing functionality
Fully working code base with tests!
Tests keep passing!
Refactoring (2)
- When we refactor聽code...
- we do not change the functionality of the code
- we want to improve the structure of the code
- We want to improve code structure by...
- reducing repetitive code
- reducing coupling
- increasing cohesion (SRP)
Real-World Example
...from a tool that you all know and love...
Lecture Ticket
- Duplication between the two methods!
- We want to refactor and extract a helper method
- What lines to pull out from each method?
- What to pass into the method when called from each method?
- What is the return type of the helper method?
public class LittleClass {
public int doThingOne() {
int numTimes = 6;
int multiplier = 5;
numTimes += 1;
for (int i = 0; i < numTimes; i++) {
System.out.println(multiplier * i);
}
return numTimes;
}
public void doThingTwo() {
int occurrences = 3;
int timeser = 10;
System.out.println("Doing thing two");
for (int i = 0; i < occurrences; i++) {
System.out.println(timeser * i);
}
System.out.println("Doing thing two");
}
}
Lecture Lab
Run the code 路 adapt the test suite 路 add new test suites 路 improve the code
Clone 路聽re-organize using the diagram 路 start with Zoo, Animal and Stall 路 finally work on Receptionist
stall: Stall
D3: Refactoring
The End - Thank You!
CPSC210 - D3: Refactoring
By Steven Wolfman
CPSC210 - D3: Refactoring
- 14