01 / 20

Refactoring in
C++

Learn to transform working code into cleaner, more maintainable code by reducing duplication and improving clarity: without changing behavior.

C++ Software Design

What Is Refactoring?

Refactoring is the process of restructuring existing code without changing its observable behavior. The program still does the same thing: it just does it with cleaner structure, less duplication, and more readable logic.

✓ Same Output
Tests pass before and after
✓ Better Structure
Easier to read and extend
✓ Less Duplication
One source of truth for logic

Why Refactor Your Code?

As projects grow, code that once worked fine becomes harder to understand, modify, and debug. Refactoring fights technical debt: the hidden cost of shortcuts and duplicated logic.

1
Readability: Other developers (and future you) can understand the code faster.
2
Maintainability: Bug fixes and feature additions require changes in fewer places.
3
Testability: Smaller, focused functions are easier to test individually.
4
Extensibility: Clean code is easier to extend with new features.

Recognizing Code Smells

A code smell is a surface-level indicator that something deeper may be wrong. Smells don't mean the code is broken: they mean it could be better.

Duplicated Code
Same logic appears in multiple places
Long Functions
A function does too many things at once
Magic Numbers
Hard-coded values with no explanation
Poor Names
Variables like x, tmp, data2

The DRY Principle

WET Code "Write Everything Twice" calcArea(w, h) { return w*h; } getArea(w, h) { return w*h; } areaOf(w, h) { return w*h; } DRY Code "Don't Repeat Yourself" calcArea(w, h) { return w*h; } Single source of truth

Refactoring vs Rewriting

Refactoring Rewriting
Behavior Preserved May change
Scope Small, incremental steps Large, all-at-once replacement
Risk Low High
Tests Run after each step Run only at the end
Goal Improve structure Replace implementation

Core Techniques

Extract Function
Pull repeated logic into a named function
Rename Variable
Replace cryptic names with descriptive ones
Replace Magic Number
Use named constants instead of raw literals
Simplify Conditional
Reduce nested if/else into clear guard clauses
Inline Variable
Remove variables that add no clarity
Remove Dead Code
Delete code that is never executed

How to Refactor Safely

1
Ensure tests exist. Before touching anything, verify you have tests that confirm current behavior.
2
Identify the smell. Spot the specific problem: duplication, long function, bad name, magic number.
3
Apply one technique. Make the smallest change that addresses the smell.
4
Run tests. Confirm nothing broke. If tests fail, undo immediately.
5
Repeat. Look for the next smell and refactor again.

Example: Before Refactoring

BEFORE: Duplicated logic
void printStudentReport(const Student& s) { // Calculate GPA double total = 0; for (int i = 0; i < s.numCourses; i++) { total += s.grades[i]; } double gpa = total / s.numCourses; cout << "GPA: " << gpa << endl; } void printHonorRoll(const Student& s) { // Calculate GPA (again!) double total = 0; for (int i = 0; i < s.numCourses; i++) { total += s.grades[i]; } double gpa = total / s.numCourses; if (gpa >= 3.5) cout << s.name << " is on honor roll"; }

Example: After Refactoring

AFTER: Extracted function
double calculateGPA(const Student& s) { double total = 0; for (int i = 0; i < s.numCourses; i++) { total += s.grades[i]; } return total / s.numCourses; } void printStudentReport(const Student& s) { cout << "GPA: " << calculateGPA(s) << endl; } void printHonorRoll(const Student& s) { if (calculateGPA(s) >= 3.5) cout << s.name << " is on honor roll"; }

Example: Magic Numbers

BEFORE: Hard-coded values
double calculateShipping(double weight) { if (weight > 50) { return weight * 0.75 + 9.99; } return weight * 0.50 + 4.99; }
↓
AFTER: Named constants
const double HEAVY_THRESHOLD = 50.0; const double HEAVY_RATE = 0.75; const double HEAVY_BASE_FEE = 9.99; const double STANDARD_RATE = 0.50; const double STANDARD_BASE_FEE = 4.99; double calculateShipping(double weight) { if (weight > HEAVY_THRESHOLD) { return weight * HEAVY_RATE + HEAVY_BASE_FEE; } return weight * STANDARD_RATE + STANDARD_BASE_FEE; }

Example: Simplify Conditionals

BEFORE: Deeply nested logic
string getDiscount(const Customer& c) { if (c.isActive) { if (c.yearsAsMember > 5) { if (c.totalSpent > 1000) { return "Gold"; } else { return "Silver"; } } else { return "Bronze"; } } return "None"; }
↓
AFTER: Guard clauses
string getDiscount(const Customer& c) { if (!c.isActive) return "None"; if (c.yearsAsMember <= 5) return "Bronze"; if (c.totalSpent <= 1000) return "Silver"; return "Gold"; }

The Refactoring Workflow

1. Run Tests All pass? Proceed 2. Spot Smell Identify the problem 3. Refactor One small change 4. Run Tests Again Behavior unchanged? Pass? Yes No Undo Change Try a different approach Commit and Repeat Tackle next smell Next smell or ship it

Common Mistakes

✕ Refactoring Without Tests
If you have no tests, you can't confirm behavior is preserved. Write tests first.
✕ Too Many Changes at Once
Making five refactoring moves before testing makes it impossible to isolate which one broke things.
✕ Renaming Without Context
Choosing names like processData is barely better than doStuff. Be specific about what the function does.
✕ Over-Abstracting
Extracting a function used only once can make code harder to follow. Refactor when duplication or complexity is real.
✕ Mixing Refactoring with Features
Adding new functionality and refactoring in the same step makes bugs hard to track. Keep them separate.

Refactoring Cheat Sheet

Code Smell Technique Result
Duplicated logic Extract Function Single source of truth
Cryptic names Rename Variable/Function Self-documenting code
Magic numbers Replace with Named Constant Readable intent
Deep nesting Guard Clauses Flat, linear flow
Long function Extract + Compose Small, testable units
Dead code Delete It Less noise

Question 1 of 5

What is the primary goal of refactoring?

Question 2 of 5

Which refactoring technique best addresses the duplication in this code?

Question 3 of 5

You want to refactor a large function. What should you do first?

Question 4 of 5

Which technique best simplifies this deeply nested conditional?

Question 5 of 5

A student extracts a helper function that is only called once in the entire codebase. Is this good refactoring?