Refactoring is the process of restructuring existing code without changing what it does. The program behaves exactly the same before and after — the difference is in how the code is organised.
Why Refactor#
Code that works isn’t always code that’s easy to read, change, or extend. As programs grow, a structure that made sense early on can become cluttered and hard to follow. Refactoring is how you keep the code clean as it evolves.
Common reasons to refactor:
- A single file has grown too long and is hard to navigate
- The same logic is repeated in multiple places
- A piece of code is doing too many unrelated things
- You want to introduce a new pattern — like object-oriented programming — without breaking what already works
What Stays the Same#
The program’s output and behaviour must not change during a refactor. If the game printed “You win!” before, it must still print “You win!” after. If something breaks, it was a bug introduced during the refactor — not the refactor itself.
This is what makes refactoring different from rewriting. A rewrite changes what the code does. A refactor changes how it’s structured.
A Simple Example#
Moving code from one file into a class is a common refactor. The logic is identical — it just lives in a better place.
Before: all game logic in Program.cs.
After: game logic moved into OddsAndEvens.cs, inside an OddsAndEvens class.
Same behaviour. Better organisation.
Common Mistakes#
Changing behaviour during a refactor It’s easy to accidentally rename a variable, reorder a condition, or adjust a value while restructuring. The safest approach is to make the structural change first, verify the program still works, and only then make any logic changes.
Refactoring and adding features at the same time Mixing a refactor with new functionality makes it hard to tell what caused a problem if something breaks. Refactor first, commit the change, then add the new feature separately.
Skipping verification after refactoring After moving code, always run the program and check it still behaves correctly. A refactor that isn’t verified is just a guess that nothing broke.
Resources#
- Refactoring (external link) — Wikipedia
- Refactoring by Martin Fowler (external link) — the definitive reference on the topic