Refactoring 101: When to Rewrite vs. When to Patch
Refactoring 101: When to Rewrite vs. When to Patch
Today's update involved a major refactor: I ripped out a heavy Javascript animation library (framer-motion) and replaced it with lightweight CSS (Cascading Style Sheets).
It’s a classic dilemma every developer faces: "Should I patch this code, or should I rewrite it?"
I all have the urge to rewrite. I look at code I wrote six months ago and cringe. But rewriting is dangerous. It takes time, it introduces new bugs, and it delivers zero new features to the user initially.
The Rule of Three
I use a simple heuristic called the "Rule of Three" to decide when to refactor:
- First time: Write the code to get the job done. It might be ugly, but it works.
- Second time: You need to change it or fix a bug. You copy-paste or patch it. It's getting messy.
- Third time: If you have to touch that file a third time, Refactor.
In the case of my animation library, it was causing performance issues specifically called Cumulative Layout Shift (CLS). This is when the page jumps around while loading, which hurts my SEO score. It wasn't just "ugly code"—it was impacting the business metrics. That is a valid reason to rewrite.
Refactoring isn't about perfection; it's about maintainability. If the code is ugly but works and you never have to touch it, leave it alone. If it's a constant source of friction, burn it down and build it again.
Best,
Gerasimos Makris Founder of g-makris.com AI Web Developer | Double Master's in MBA & FinTech and Blockchain
Tech Glossary & Concepts
- Refactoring: The process of restructuring existing computer code—changing the factoring—without changing its external behavior. It improves nonfunctional attributes of the software (cleaner code, faster performance).
- CLS (Cumulative Layout Shift): A metric that measures visual stability. If elements on a webpage move around while the page is loading, it creates a bad user experience and lowers your Google ranking.
- SEO (Search Engine Optimization): The practice of optimizing a website so it ranks higher in search engine results (like Google).
- Heuristic: A practical method for solving a problem that isn't guaranteed to be perfect, but is sufficient for the immediate goals (a "rule of thumb").
Gerasimos Makris is an AI Web Developer with a background in FinTech operations. He specializes in building secure, scalable web applications that solve real-world financial problems. When he's not coding, he enjoys exploring the intersection of technology, finance, and business strategy.