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
  1. What lines to pull out from each method?
  2. What to pass into the method when called from each method?
  3. 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