Refactoring: Better Structure, Same Behaviour

Code that works is rarely finished. As features pile up, functions grow long, logic is copied between files and names stop matching what variables hold. There is a disciplined way to clean this up without breaking anything. You use it every time you modify code written earlier, and it is the clean-up step that follows each passing test in test-driven development.

What counts as a refactoring

Refactoring is a change to the internal structure of code that leaves its observable behaviour unchanged. For every input, the program returns the same results, raises the same errors and produces the same side effects, such as file writes or printed output. The purpose is code that is easier to read and cheaper to change next time. If a change alters what the program does for any input, it is not a refactoring, even when it also tidies the code.


A refactoring is usually prompted by a code smell, a surface feature of code that suggests a deeper design problem. A smell is a reason to look, not proof of a flaw: a long function can be perfectly clear, and two similar blocks may be about to diverge for good reasons.


Most refactorings have standard names, so a team can say exactly what was done:


Smell

Typical refactoring

What changes

Long function

Extract Method

A fragment becomes a named function called from the original spot

Duplicated code

Extract Method, then call it from each copy

One definition replaces several copies

Unclear name

Rename

The identifier and every reference to it

Magic number

Replace Magic Number with Named Constant

A literal such as 0.13 becomes TAX_RATE

Method uses another class's data more than its own

Move Method

The method moves and its callers are updated

Trivial function that adds nothing

Inline Method

Calls are replaced by the function body


Each refactoring has an inverse. Inline Method undoes Extract Method, so refactoring is not a march towards ever more functions; it is choosing the structure that reads best now.



Working in small, tested steps

Because behaviour must stay the same, you need a fast way to check it. That check is an automated regression test suite. If the code has no tests, first write characterization tests that record what it currently does, including any odd outputs, before you touch it.


Then work in a loop: make one small change, run the tests, and commit if they pass. If they fail, undo the step instead of debugging a large edit, and try a smaller one. Many IDE tools perform Rename and Extract Method automatically, which removes typing errors but not the need to test.


A loop of three boxes, make one small change, run the tests and commit the step, with a failure path from the tests back to the first box.


Public names need extra care, because callers outside your code base cannot be updated in one commit. Add the new name, keep the old one delegating to it until every caller has moved, and only then delete it.



Measuring the effect

Readability is the real goal, but a simple metric shows how refactoring redistributes logic. McCabe's cyclomatic complexity of a single function with dd decision points is


M=d+1M = d + 1


Count each if, elif, for and while as one decision point; else adds none because it is not a new test. Some tools also count every and and or, so check your tool's convention; the examples here contain none.


Example: A report function contains six if statements, so M=6+1=7M = 6 + 1 = 7. Extract three of the checks into a helper. The helper has M=3+1=4M = 3 + 1 = 4, and the original keeps three checks, so it also has M=4M = 4. In this extraction from a single location, the code still contains six decision points in total, split so each function has fewer paths to read and test.


Preserving behaviour does not require preserving decision counts. For example, consolidating duplicated conditional blocks into one helper can reduce the total number of decision points in the code while keeping the same observable behaviour.

What to remember

  • Refactoring changes structure, never observable behaviour.
  • Code smells such as long functions, duplication and magic numbers point to where refactoring may help.
  • Use named refactorings such as Extract Method, Rename, Move Method and Inline Method, one small step at a time.
  • Run the tests after every step, and write characterization tests first if none exist.
  • Keep bug fixes and new features in commits separate from refactorings.
  • Per function, M=d+1M = d + 1. The illustrated extraction redistributes six decision points without changing their total; refactoring in general need not preserve decision counts.

Example: Refactoring a shipping-cost function

A small online shop calculates shipping with the function below. Costs are in dollars and weights in kilograms. Count each if as one decision point; else adds none.


Python
def shipping_cost(weight_kg, express, country):
    if weight_kg <= 0:
        raise ValueError("weight must be positive")
    if weight_kg > 30:
        raise ValueError("too heavy")
    if country == "CA":
        cost = 5.00 + 1.20 * weight_kg
    else:
        cost = 9.00 + 2.50 * weight_kg
    if express:
        cost = cost * 1.5
    return round(cost, 2)


a) Find the cyclomatic complexity MM of the original shipping_cost.


List the tests the function makes: weight_kg <= 0, weight_kg > 30, country == "CA" and express. The else is only the false branch of the country test, so it adds nothing. The number of decision points is d = ________.


M=d+1=4+1=5M = d + 1 = 4 + 1 = 5


The original function has M=5M = 5.


b) A developer applies Extract Method twice and Replace Magic Number with Named Constant once, giving the code below. Find MM for each of the three functions and compare the total number of decision points with part a).


Python
EXPRESS_MULTIPLIER = 1.5

def validate_weight(weight_kg):
    if weight_kg <= 0:
        raise ValueError("weight must be positive")
    if weight_kg > 30:
        raise ValueError("too heavy")

def base_cost(weight_kg, country):
    if country == "CA":
        return 5.00 + 1.20 * weight_kg
    return 9.00 + 2.50 * weight_kg

def shipping_cost(weight_kg, express, country):
    validate_weight(weight_kg)
    cost = base_cost(weight_kg, country)
    if express:
        cost = cost * EXPRESS_MULTIPLIER
    return round(cost, 2)


validate_weight keeps both range checks, so it has ________ decision points and M=3M = 3.


base_cost has ________ decision point, the country test. The final return plays the role of the old else, so M=2M = 2.


shipping_cost now keeps only the express test, which is ________ decision point, so M=2M = 2.


total d=2+1+1=4\text{total } d = 2 + 1 + 1 = 4


The total is still four, the same as in part a): the decisions moved and none disappeared. The largest complexity of any single function dropped from 5 to 3, and each piece can now be read and tested on its own. The three functions have M=3M = 3, M=2M = 2 and M=2M = 2.


c) The team's tests check that shipping_cost(12, True, "CA") returns 29.10 and shipping_cost(4, False, "US") returns 19.00. Show that the refactored code passes both tests. Then suppose a teammate also changed EXPRESS_MULTIPLIER to 1.4 in the same commit. Does the first test still pass, and is that commit still a refactoring?


First test: the base cost for 12 kg to Canada is 5.00 + 1.20 × 12 = ________ dollars, and express multiplies it by 1.5:


19.40×1.5=29.1019.40 \times 1.5 = 29.10


That matches the expected value. Second test: 9.00 + 2.50 × 4 = 19.00 dollars with no express surcharge, which also matches. The refactored code passes both tests.


With the multiplier at 1.4, the first test gives 19.40 × 1.4 = ________ dollars instead of 29.10, so the test fails. The commit changes what the program returns, so it is a behaviour change, not a refactoring. Split it: commit the refactoring on its own with the tests passing, then change the multiplier in a separate commit and update the expected test value deliberately.

Match each software-maintenance term with the description that fits it. Each description is used exactly once, so read all of them before you commit to a match.

Match each term
A.

A surface symptom, such as a very long function, that hints at a deeper design problem

B.

An identifier that replaces an unexplained literal such as 0.13 inside a calculation

C.

A test written to record what existing code currently does before anyone changes it

D.

Turning a fragment of a function into a new named function and calling it from the original spot

E.

A structural change to code that keeps every observable output, error and side effect the same

F.

Replacing calls to a trivial function with its body and then deleting that function

Characterization test

Refactoring

Code smell

Named constant

Inline Method

Extract Method

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A reservation service uses the Python function below. The parameters active, requested, and available are a Boolean and two nonnegative integers, respectively.


Python
def reserve(active, requested, available):
    if active:
        if requested <= available:
            return "reserved"
    return "rejected"


A developer wants to replace the nesting with a guard clause, an early return that handles a case before the remaining code continues. The new function will reject unsuitable requests first, then return "reserved".


Complete the behavior-preserving plan: combine not active and requested > available using Python's operator. When active is True and requested == available, the returned string must be .

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A team's change log lists five edits to a payroll module. Which of them are refactorings in the strict sense, meaning the module's observable behaviour is unchanged for every input? Select all that apply.

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice