CPSC 210

D3: Refactoring

Slides designed by Felix Grund, based on Paul Carter’s slides

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

  • 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)

Improving code structure without changing functionality

Pod Activity (Do in Groups of 3-5)

When refactoring, why can't we just update/alter the functionality at the same time?

Refactoring

Improving code structure without changing functionality

Fully working code base with tests!

Tests keep passing!

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!

D3: Refactoring

By firas_moosvi

D3: Refactoring

  • 91