Refactoring in
C++
Learn to transform working code into cleaner, more maintainable code by reducing duplication and improving clarity: without changing behavior.
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.
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.
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.
x, tmp, data2The DRY Principle
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
How to Refactor Safely
Example: Before Refactoring
Example: After Refactoring
Example: Magic Numbers
Example: Simplify Conditionals
The Refactoring Workflow
Common Mistakes
processData is barely better than doStuff. Be specific about what the function does.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
Function A:
double tax(double p) {
return p * 0.08;
}
double total(double p) {
return p + p * 0.08;
}
Which refactoring technique best addresses the duplication in this code?
p * 0.08 appears in both functions. Since tax() already computes it, total() should call return p + tax(p);. Renaming p and naming the constant are also good ideas, but the primary duplication fix is reusing the extracted function.Question 3 of 5
You want to refactor a large function. What should you do first?
Question 4 of 5
Code snippet:
if (age >= 18) {
if (hasLicense) {
if (hasInsurance) {
return "Approved";
} else {
return "Need insurance";
}
} else {
return "Need license";
}
} else {
return "Too young";
}
Which technique best simplifies this deeply nested conditional?
if (age < 18) return "Too young"; then if (!hasLicense) return "Need license"; and so on, leaving "Approved" at the end.Question 5 of 5
A student extracts a helper function that is only called once in the entire codebase. Is this good refactoring?