Module 3 Lesson 10: Refactoring Code
The art of cleaning up your code. Learn how to identify 'code smells' and rewrite your logic to be more readable without changing how it works.
Module 3 Lesson 10: Refactoring Code
You've built a program. It works. The users are happy. But when you look at the code, it's a mess. There are long functions, confusing names, and duplicated logic. This is where Refactoring comes in. Refactoring is the process of restructuring existing computer code without changing its external behavior.
Lesson Overview
In this lesson, we will cover:
- The Definition: What is refactoring and why do it?
- Common "Code Smells": Recognizing when code needs cleaning.
- The Refactoring Toolkit: Renaming, extracting, and simplifying.
- The Golden Rule: Never refactor code that doesn't have tests (or that isn't working yet!).
1. What is Refactoring?
Think of refactoring like editing a book. You aren't changing the story—you're just fixing the grammar, breaking long paragraphs into short ones, and making the language more beautiful so the reader (the next programmer) has a better experience.
2. Recognizing "Code Smells"
A "Code Smell" is a hint that something might be wrong with your code's structure.
- Duplicate Code: You see the same lines in multiple places.
- Long Functions: A function that is more than 20-30 lines long.
- Vague Names: Variables named
data,x, oritem_1that don't explain what they are. - Deep Nesting: An
ifinside aforinside anifinside awhile.
3. The Refactoring Toolkit
A. Extracting a Function
If a function is doing two things, take the second thing and move it to its own function.
B. Renaming Variables
Change d to days_since_last_login. It adds zero "cost" to the computer but saves hours for the humans.
C. Replacing "Magic Numbers"
Instead of if status == 5:, create a variable SUCCESS_CODE = 5 and use if status == SUCCESS_CODE:.
4. An Example Refactor
Before Refactor:
def p(l):
for x in l:
if x > 100:
print(x * 1.05)
After Refactor:
TAX_RATE = 1.05
MIN_PRICE_FOR_TAX = 100
def print_taxed_prices(price_list):
for price in price_list:
if price > MIN_PRICE_FOR_TAX:
taxed_price = price * TAX_RATE
print(f"Total with tax: ${taxed_price:.2f}")
# Much better!
Practice Exercise: The Messy Calculator Refactor
Copy this messy code and refactor it based on the principles above:
- Add meaningful names.
- Extract the math into its own function.
- Add a docstring.
# MESSY CODE
def calc(a, b, c):
if c == "add":
print(a + b)
elif c == "sub":
print(a - b)
calc(10, 5, "add")
Quick Knowledge Check
- Does refactoring change the way a program works?
- What is a "Code Smell"?
- Why is deep nesting (many indented loops/ifs) considered bad?
- Name one benefit of renaming a variable from
xto something descriptive.
Key Takeaways
- Refactoring is about code quality, not new features.
- Identify code smells like duplication and long functions.
- The goal is to make code more readable and maintainable.
- Always ensure your code is working before you start refactoring.
What’s Next?
We’ve covered everything in Module 3! It’s time to put your modular skills to the test with our Hands-on Projects where we'll build a complete Utility Library!