- Forward


Refactoring
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Getting Started
Back SMYC Forward
  • Refactoring Defined:
    • Changing code without changing its external behavior
  • Purpose of Refactoring:
    • Improve the structure, presentation, or performance of code (i.e., non-functional properties)
Before Refactoring Can/Should Occur
Back SMYC Forward
  • Existing Code:
    • There must be existing code
  • Existing Tests:
    • The only way to ensure that the behavior isn't changed is to have an existing test suite and perform regression testing
When is Refactoring Needed?
Back SMYC Forward
  • Duplication:
    • Duplicate sequences of statements (suggesting the need for a loop, method/function, super class, etc...)
    • Duplicate expressions (suggesting the need for a function/method)
    • Duplicate manipulations or declarations of variables (suggesting the need for a collection or structure)
    • Duplicate data (suggesting the need to combine/eliminate data structures)
When is Refactoring Needed? (cont.)
Back SMYC Forward
  • Lack of Clarity:
    • Badly named variables, functions/methods, classes, etc...
    • Awkward control structures
    • Lack of comments
  • Other Defects (a.k.a. Code Smells):
    • Comments that duplicate code
    • Tight coupling
    • Lack of information hiding
    • Low cohesion
    • Bloated (large) and/or lazy (small) classes
    • Long methods
Examples of Refactorings to Improve Clarity
Back SMYC Forward
  • Introduce Explanatory (Intermediate) Variables:
    • Long expressions can be difficult to understand and debug
    •         // Original Code
              if ( 0 <= (b*b - 4*a*c)) { ... }
      
              // Refactored Code
              boolean hasRoots = ( 0 <= (b*b - 4*a*c));
              if (hasRoots) { ... }
              
  • Extract Sub-Program:
    • Break a long program or a program that has multiple easily described steps into multiple sub-programs
The Refactoring Process
Back SMYC Forward
  1. Test the existing code.
  2. Identify a refactoring.
  3. Make a small change that gets the code closer to the desired code.
  4. Run regression tests and debug if necessary.
  5. If the refactoring is not complete, go to step 3.
  6. If the code needs further refactoring, go to step 2.
Other Kinds of Improvements (i.e., Functional Improvements)
Back SMYC Forward
  • Improved Ease of Use:
    • Minor changes that make code easier to use (e.g., overloaded methods, convenience methods)
  • Generalization:
    • Modifications that make the code applicable in a wider variety of situations (e.g., a wider range of parameter values, more types of parameters)
  • Increased Functionality:
    • Adding capabilities (e.g., additional methods)
There's Always More to Learn
Back -