4.5.19Software Engineering

Refactoring — code smells, common refactorings (extract method, rename, etc.)

2,065 words9 min readdifficulty · medium3 backlinks

WHAT is refactoring?

WHY do we refactor?

  • WHY 1 — Cost of change: Software is read ~10x more than it's written. Messy code makes every future change slower and riskier.
  • WHY 2 — Compounding: Small messes pile up into "technical debt." Refactoring pays the debt down before interest (bugs, slowdowns) crushes you.
  • WHY 3 — Safety: A clean structure makes bugs visible and changes local.

HOW do we refactor safely? (the loop)

The golden rule: never refactor without tests.

  1. Make sure a passing test suite covers the code.
  2. Make one tiny change.
  3. Run tests. Green? Keep it. Red? Undo immediately.
  4. Commit.
  5. Repeat.

Figure — Refactoring — code smells, common refactorings (extract method, rename, etc.)

The Common Code Smells (catalogue)


The Common Refactorings

1. Extract Method

2. Rename (Variable / Method)

3. Introduce Explaining Variable

4. Replace Magic Number with Named Constant

5. Extract Class (fixing God Object / Data Clumps)



Recall Feynman: explain it to a 12-year-old

Imagine your LEGO castle works great, but inside it's a tangled mess — bricks crammed in random spots. Refactoring is carefully rearranging the bricks so the castle looks exactly the same from outside, but inside it's neat and easy to add a new tower later. You move one brick at a time and check the castle still stands after each move (those checks are "tests"). A code smell is like a weird wobble that warns you something inside is messy — even if the castle hasn't fallen yet.


Flashcards

What is the defining property of a refactoring?
It is behaviour-preserving — external behaviour stays identical while internal structure improves.
What is a code smell (and is it a bug)?
A surface symptom hinting at a deeper design problem; NOT a bug — the code may work fine.
Why must you have passing tests before refactoring?
Tests are your proxy for behaviour; without them you can't prove the change preserved behaviour, which is the very definition of refactoring.
State the refactoring safety loop.
Cover with tests → make one tiny change → run tests → green keep / red revert → commit → repeat.
What smell does Extract Method primarily fix?
Long Method (and enables reuse / independent testing).
Why is Rename considered high-value despite being cheap?
Good names reveal intent and act as documentation that never goes stale.
Name the smell: same group of variables always passed together.
Data Clumps (fix: Extract Class / introduce an object).
Name the smell: one change forces edits across many files.
Shotgun Surgery.
Why separate refactoring and feature changes into different commits?
So a failing test points unambiguously to one kind of change; mixing them makes failures undiagnosable.
What is the Rule of Three for duplication?
Duplicate once is OK, twice wince; on the third occurrence, refactor to remove duplication.
What is Feature Envy?
A method that uses another class's data more than its own — move it closer to the data.
What does Replace Magic Number with Named Constant achieve?
Single source of truth and explicit meaning for an otherwise unexplained literal.

Connections

  • Unit Testing — the safety net that enables refactoring.
  • Technical Debt — what refactoring pays down.
  • Clean Code / Naming Conventions — principles behind Rename & Extract.
  • Design Patterns — refactorings are often toward a pattern.
  • Cyclomatic Complexity — a metric that flags Long Method / God Object smells.
  • DRY Principle — directly motivates removing Duplicated Code.
  • Single Responsibility Principle — the cure for God Object / Large Class.

Concept Map

defined by

triggered by

requires

done via

checks

reduces

yields

hints at

fixed by

fixed by

fixed by

verified by

Refactoring

Behaviour preserving

Code smell

Test suite

Safe loop tiny steps

Lower cost of change

Technical debt

Extract Method

Rename

Long Method smell

Duplicated Code smell

Magic Numbers smell

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Refactoring ka matlab hai code ko andar se saaf-suthra banana, bina uske bahar ka behaviour badle. Yaani input do toh output exactly wahi aaye jo pehle aata tha — bas code padhne, samajhne aur future me change karne me aasaan ho jaaye. Socho ek messy kamra hai jo kaam toh karta hai, par usme cheezein dhundhna mushkil. Refactoring matlab kamra organize karna, kuch fenkna nahi.

Code smell ek warning sign hai — koi bug nahi, par ishaara hai ki design me kahin gadbad hai. Jaise Long Method (ek function bohot saara kaam kar raha), Duplicated Code (same logic copy-paste), Magic Number (0.0825 jaisa number bina explanation ke), God Object (ek class sab kuch sambhal rahi). In smells ko theek karne ke liye chhote-chhote refactorings hote hain: Extract Method (ek logic ko alag named function me daalo), Rename (variable/function ko meaningful naam do — ye sabse sasta aur powerful hai), Named Constant (magic number ko TAX_RATE bana do).

Sabse important rule: tests ke bina kabhi refactor mat karo. Pehle passing tests rakho, fir ek chhota change karo, fir test chalao — green hai toh rakho, red hua toh turant revert karo. Tests hi tumhara proof hain ki behaviour same raha. Aur ek aur cheez yaad rakho — refactoring aur naya feature add karna alag-alag commits me karo; mix karoge toh test fail hone par pata hi nahi chalega ki kis cheez ne toda. "Rule of Three": ek baar copy theek, doosri baar kharoch, teesri baar refactor.

Go deeper — visual, from zero

Test yourself — Software Engineering

Connections