Refactoring Techniques
Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior. Its goal is to clean up code that "smells" and make it easier to maintain and extend.
1. The Red-Green-Refactor Cycle
Refactoring is often associated with Test-Driven Development (TDD):
- Red: Write a failing test.
- Green: Make it pass (even if the code is messy).
- Refactor: Clean up the code while keeping the tests green.
2. Common Techniques
Extract Method
The most common technique. If you have a code block that can be grouped together, move it into a separate function with a descriptive name.
- Why: Improves readability and reduces duplication.
Rename Variable / Method
Names should reveal intent. If you need a comment to explain what a variable does, try renaming it instead.
- Bad:
let d; // elapsed time in days - Good:
let elapsedTimeInDays;
Inline Method
The opposite of Extract Method. If a method's body is as clear as its name, or it's just a simple delegation, replace the call with the method body.
Move Method
If a method uses data from another class more than its own, it probably belongs in that other class. This reduces coupling (specifically "Feature Envy").
Replace Magic Numbers with Constants
Replace literal numbers (like 86400) with named constants (like SECONDS_IN_A_DAY).
3. Code Smells (When to Refactor)
"Code Smells" are indicators that something might be wrong.
- Long Method: A function contains too many lines of code.
- Large Class: A class tries to do too much (God Object).
- Duplicated Code: The same structure appears in multiple places (DRY principle violation).
- Feature Envy: A method seems more interested in a class other than the one it actually is in.
4. Safety First
Never refactor without tests. Refactoring changes the structure, and without a safety net of unit tests, you risk breaking the application logic.
programming/technical-debt programming/software-testing-basics programming/code-review-best-practices