>> Module 01 / Day 14 / Lecture

Refactor: Spaghetti → Clean

Day 14 of a 40-day journey
The code already works. Today you make it readable — same output, better shape.
Lecture
75 min · 09:00–10:15
Lab
60 min · Clean the Spaghetti
Module
M1 · Python Foundations
DAY 14 / 40
>> Today's roadmap

A combine day, a different goal

  1. What "spaghetti code" actually is
  2. The four smells — repetition, long blocks, unclear names, magic numbers
  3. The refactor recipe — extract, name, replace, re-run
  4. A before/after worked example
  5. Lab — clean the spaghetti without changing its output
>> The hook

"It works… but I'm scared to touch it."

Spaghetti code is code that runs correctly but is tangled — one long strand where everything is connected to everything, copy-pasted and hard to follow. You can't change one part without fear of breaking another.

Refactoring = changing the shape of code while keeping its behaviour identical. Same output, every time. We improve how it reads, not what it does.
>> 01 / 04 · Diagnosis

Four code smells to sniff out

SMELL 1
Repetition

The same lines copy-pasted with tiny changes. Fix one bug and you must fix it everywhere.

SMELL 2
Long top-level blocks

One giant flat script with no functions. Nothing has a name; nothing can be reused.

SMELL 3
Unclear names

n, a, t, av — you have to decode them. Names should explain themselves.

SMELL 4
Magic numbers

Bare numbers like 35 or 75 with no name. What do they mean? Give them one.

>> What spaghetti looks like

All four smells in one block

report_spaghetti.py
# student 1
n = "Aarav"; a = 40; b = 55; c = 70   # unclear names
t = a + b + c
av = t / 3                              # magic number 3
print("Average: " + str(round(av, 2)))
if av < 35: ...                        # magic numbers 35, 75

# student 2  ← the SAME block, copy-pasted
n = "Diya"; a = 30; b = 28; c = 33
# ... and again for student 3 (repetition!)
>> 02 / 04 · The cure

The refactor recipe

  1. Extract a function — take the repeated block and wrap it in def.
  2. Name it well — the parts that change become parameters: print_report(name, m1, m2, m3).
  3. Replace repetition with a call — delete the copies, call the function instead.
  4. Name the magic numbers — PASS_MARK = 35 once, used everywhere.
  5. Re-run & compare — output must be identical. If it changed, you broke something.
>> Worked example · extract a function

Before → After

before.py
# copy-pasted 3 times
n = "Aarav"
a = 40; b = 55; c = 70
t = a + b + c
av = t / 3
print("Name: " + n)
print("Average: " + str(round(av, 2)))
# ...then ALL of it again, twice
after.py
SUBJECTS = 3

def print_report(name, m1, m2, m3):
    total = m1 + m2 + m3
    average = total / SUBJECTS
    print("Name: " + name)
    print("Average: " + str(round(average, 2)))

print_report("Aarav", 40, 55, 70)
>> 03 / 04 · Why this is safe

Same output = you didn't break it

Refactoring feels risky, but it has a built-in safety net: the program's output is your test. Capture the output before you start. After every small change, run it and compare.

the_safety_loop.txt
# 1. run the messy version, save the output  (your target)
# 2. make ONE small change
# 3. run again — does the output still match?
#       same  → keep going
#       diff  → undo that last change, you broke behaviour
>> 04 / 04 · Common failures

Two ways refactoring goes wrong

MISTAKE 1
Changing behaviour

"While I'm here, let me fix the formatting to 55.00…" — and now the output differs. That's a separate task. Today: keep output byte-for-byte identical.

MISTAKE 2
Over-engineering

Don't add five layers of helpers for three students. One well-named function is enough. Clean ≠ clever. Stop when it reads clearly.

>> 11:00 – 12:00 · Lab

Today's lab — Clean the Spaghetti

THE STARTER
A working report card

starter.py prints a report for three students — correctly — but the same block is copy-pasted three times, with magic numbers and one-letter names.

YOUR JOB
Refactor, don't rewrite

Extract print_report(...), name the constants, call it three times. Follow the # TODO: markers. Output must stay identical.

>> End of Day 14

What you can now do

  • ✓ Spot the four smells: repetition, long blocks, unclear names, magic numbers.
  • ✓ Extract a well-named function and replace copy-paste with a call.
  • ✓ Refactor safely — improve the shape while keeping the output identical.
01 / 11
←/→ navigate   F fullscreen   Ctrl/⌘+P save as PDF