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 · code from the UI package should be moved out 

Clone · re-organize using the diagram · start with Zoo, Animal and Stall · finally work on Receptionist

D3: Refactoring

The End - Thank You!

Made with Slides.com