JavaScript
Refactoring
Learn to transform messy, duplicated code into clean, maintainable functions by extracting patterns, eliminating repetition, and improving clarity.
What Is Refactoring?
Refactoring is the process of restructuring existing code without changing what it does. The program's inputs and outputs stay exactly the same: only the internal structure improves.
Refactoring targets three things: duplication (repeated code), complexity (hard-to-follow logic), and poor naming (unclear variable and function names).
Why Does Refactoring Matter?
Recognizing Code Smells
A code smell is a surface-level indicator that something deeper may be wrong. Smells do not mean the code is broken: they signal it could be better structured.
The DRY Principle
DRY stands for Don't Repeat Yourself. Every piece of knowledge in your code should have a single, authoritative source. If you copy-paste logic, you create multiple places that must stay in sync.
Refactoring vs Rewriting
| Refactoring | Rewriting | |
|---|---|---|
| Behavior changes? | No | Yes |
| Step size | Small, incremental | Large, all-at-once |
| Risk level | Low | High |
| Tests still pass? | Always | Often need new tests |
| Goal | Improve structure | Replace functionality |
How to Refactor Step by Step
Example 1: Extract Function
Example 2: Rename for Clarity
Example 3: Replace Magic Numbers
Example 4: Simplify Conditionals
The Refactoring Cycle
Technique: Extract Function
Extract Function is the most common refactoring move. When you see a block of code that does one specific thing, pull it into its own named function.
calculateTotal, formatDate, validateEmail.Example 5: Loop to Higher-Order Function
Common Mistakes
Refactoring Techniques Summary
| Technique | When to Use | Result |
|---|---|---|
| Extract Function | Repeated code blocks | One reusable function |
| Rename Variable | Unclear names (a, x, tmp) | Self-documenting code |
| Replace Magic Number | Hard-coded literals | Named constant |
| Simplify Conditional | Long if-else chains | Lookup object or map |
| Replace Loop | Manual for-loop patterns | filter / map / reduce |
Question 1 of 5
What is the primary goal of refactoring?
Question 2 of 5
Code A:
function greetMorning(name) {
console.log("Good morning, " + name + "!");
}
function greetEvening(name) {
console.log("Good evening, " + name + "!");
}
Code B:
function greet(timeOfDay, name) {
console.log("Good " + timeOfDay + ", " + name + "!");
}
Which refactoring technique was applied to transform Code A into Code B?
Question 3 of 5
What does the acronym DRY stand for in software development?
Question 4 of 5
function applyDiscount(price) {
return price - price * 0.15;
}
function applyTax(price) {
return price + price * 0.08;
}
The numbers 0.15 and 0.08 in this code are examples of which code smell?
DISCOUNT_RATE and TAX_RATE.Question 5 of 5
When is the safest time to refactor code?