๐ฆ Day 6: Debugging and Refactoring with Copilot
๐ฏ Goal:
Learn how to use Copilot to help:
- Fix bugs
- Improve slow or messy code
- Refactor long functions into clean parts
๐ง What Copilot Can Do Today:
✅ Suggest fixes for errors ✅ Rewrite old code in a better way ✅ Add comments and structure ✅ Offer unit tests (with Copilot Labs)
๐ง Step 1: Use Copilot to Fix Code
Paste this buggy code and let Copilot help fix it:
❌ Buggy Python:
def divide_numbers(a, b):
return a / b
print(divide_numbers(5, 0))
➡ Prompt Copilot:
# Fix divide by zero error
✅ Suggests:
def divide_numbers(a, b):
if b == 0:
return "Cannot divide by zero"
return a / b
๐ง Step 2: Refactor Long Functions
Paste this:
# Calculate total price including tax and discount
def calculate(price, tax, discount):
total = price + (price * tax)
total = total - (total * discount)
return total
➡ Prompt:
# Break this into smaller helper functions
Copilot may split logic like:
def apply_tax(price, tax):
return price + (price * tax)
def apply_discount(price, discount):
return price - (price * discount)
def calculate(price, tax, discount):
taxed = apply_tax(price, tax)
return apply_discount(taxed, discount)
๐ง Step 3: Let Copilot Suggest Test Cases
Prompt:
# Write unit tests for calculate() using unittest
Copilot suggests:
import unittest
class TestCalculate(unittest.TestCase):
def test_price_with_tax_and_discount(self):
self.assertAlmostEqual(calculate(100, 0.1, 0.2), 88.0)
๐งช Suggested Practice Tasks
Paste the following and let Copilot help fix or improve:
๐น Fix the logic
# Check if a number is prime
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
Prompt: # Fix for edge cases like n=1
๐น Refactor this messy JS code
function greet(user) {
if (user != null && user.name != null && user.name !== '') {
console.log("Hello " + user.name);
} else {
console.log("Hello Guest");
}
}
Prompt: // Refactor using optional chaining and cleaner logic
✅ Summary of Day 6
| What You Did | How Copilot Helped |
|---|---|
| Fixed buggy code | Added conditions and error handling |
| Refactored long logic | Split into helper functions |
| Added test cases | Suggested unittest or describe() tests |
Tags:
GitHub Copilot