Code Cleanup Tips I Wish Someone Had Taught Me Years Back
Sigh. Just spent my entire Monday hunting down a CSS bug that I definitely caused myself. Turns out I was using the same class name on two different elements – classic sleep-deprived me from last month coming back to cause problems for current me.
Look, I'm not here to preach about "code perfection" or whatever. But after 10+ years of building frontends and watching projects go from "beautiful new codebase" to "nightmare no one wants to touch," I've realized clean code isn't about impressing your peers. It's about not hating your life when you have to change something six months from now.
So, let me share a few things I've picked up. These aren't theoretical concepts from a textbook – they're lessons learned through frustration, caffeine, and missed weekend plans.
Name Things Like A Normal Human Being Would
OK so this is embarrassing but here's actual code I wrote circa 2015:
const p = fetch('/api/products');
p.then(r => {
if(r.ok) {
r.json().then(d => {
const f = d.filter(i => i.c === true);
updateUI(f);
});
}
});
What does any of that mean? No idea. I clearly thought I was being clever with short variable names. My coworkers probably wanted to quit the project.
Here's how I'd write it now:
const productsPromise = fetch('/api/products');
productsPromise.then(response => {
if(response.ok) {
response.json().then(products => {
const featuredProducts = products.filter(item => item.isFeatured === true);
updateProductGrid(featuredProducts);
});
}
});
Yes, it takes more space. But I can actually understand it when I'm exhausted, the deadline's tomorrow, and I'm trying to figure out why nothing's showing up on the page.
Same thing happens with CSS too:
/* From my "I'm so clever" phase */
.cnt {
display: flex;
}
.s-bar {
width: 30%;
}
.m-cnt {
width: 70%;
}
Now I'm over here like:
/* From my "I don't want to regret this later" phase */
.page-container {
display: flex;
}
.sidebar {
width: 30%;
}
.main-content {
width: 70%;
}
Trust me, when a client emails at 4:30pm saying "can we move that THING over to the right a bit more?", you'll know exactly which "THING" they're talking about.
Pick A Style And Stick With It, Please
I joined a six-person project last fall and within a week discovered we had multiple ways to do literally everything:
- One guy used camelCase, another used snake_case
- Three different date formatting functions spread across the app
- Some files were tabs, others were spaces (this started an actual argument)
- API errors handled differently in every single component
My brain was fried just trying to remember "how are we supposed to do X in THIS file?" Let me save you the headache – pick something and stick with it. I don't even care what you pick. Just be consistent.
Seriously, make a firm decision about everything – how you name files, where you put functions, whether you use single or double quotes – and then STICK WITH IT. The amount of mental energy you'll save is incredible.
I once spent an entire day refactoring a codebase just to standardize how we formatted prices. We had:
// In ProductCard.jsx
function formatPrice(price) {
return '$' + price.toFixed(2);
}
// In Cart.jsx
function formatCost(cost) {
return '$' + Number(cost).toFixed(2);
}
// In Checkout.jsx
const formatTotal = (val) => `$${parseFloat(val).toFixed(2)}`;
Like... we're all on the same team, right? Create a formatters.js file and use the same function everywhere. Then when the client inevitably says "we need to change how prices are displayed," you'll only need to change it in one place.
Comments: Like Notes You Leave Your Future Tired Self
I used to think comments were for beginners. "My code is self-explanatory," I'd proudly declare while writing the most obscure code imaginable.
Now I write comments like I'm leaving instructions for myself after a long day. Because that's basically who's going to be maintaining this code in the future: me, tired, frustrated, and possibly not in the most optimal state of mind.
// Terrible or non-existent comment
.header { margin-top: 267px; }
// Actually helpful comment
// This specific 267px margin aligns the header with the bottom of the
// hero image. If the marketing team changes the hero, this will break.
// Sorry in advance if you're fixing this at midnight before launch.
.header { margin-top: 267px; }
Last month I found a comment I wrote to myself two years ago that said "Don't touch this calculation – it compensates for a weird iOS Safari bug where..." and it saved me from breaking our entire checkout flow during a redesign.
My most valuable comments usually start with:
- "This is not ideal but..."
- "CAUTION: This will break if..."
- "Dear future me, I apologize about..."
- "Unusual edge case: ..."
One Component, One Job
Early in my career, I made these monster 800-line React components that did EVERYTHING:
- Fetched data from three different APIs
- Managed a form with 20 fields
- Handled validation logic
- Processed payments
- Controlled a complex animation sequence
- Formatted dates and currencies
- Maintained a mini-database of state
Then I'd be surprised – truly surprised – when I couldn't reuse any of it for a similar feature. Or when a tiny change would break the whole thing in mysterious ways.
My "Is This Component Doing Too Much?" Checklist
If my component is doing more than 2-3 of these, I break it up:
- Data fetching (move to a custom hook)
- Complex calculations (move to utility functions)
- Business logic (move to a service layer)
- Heavy state management (move to context or store)
- Handling lots of events (simplify or extract)
- Rendering complex UI (split into sub-components)
Now my components are way smaller. I can actually wrap my head around what they're doing. And when someone asks, "can we reuse this but slightly differently?" I don't get immediately stressed.
The "Where Does This Go?" Test
If I have to think for more than 5 seconds about where a new piece of code should live, my folder structure needs work.
One project I inherited had:
/components
/pages
/utils
/hooks
/context
/services
/constants
/types
/styles
/assets
/lib
/helpers
/config
/api
/state
/wrappers
I spent 10 minutes trying to figure out where to put a function that formatted phone numbers. Is it a util? A helper? A formatter? Should it be part of a service? WHY ARE THERE SO MANY FOLDERS?
I've gotten very strict about this. Now I aim for:
/components - UI stuff grouped by feature
/hooks - React hooks that share logic
/api - API-related code
/utils - Helper functions, formatters, etc.
/assets - Images, fonts, etc.
/styles - Global styles
Done. If I can't quickly decide where something goes, I've probably made things too complicated.
Neither Too Clean Nor Too Messy
There's this perfect middle zone I'm always trying to hit between "barely functioning code that technically works" and "over-engineered masterpiece that took 3x as long as it should have."
In my 20s, I wrote chaotic code that somehow worked for demo day but created weeks of painful cleanup after. Then I overcompensated and started building these elaborate, perfect systems for features that ended up getting cut two weeks later.
Now I try to write code that's:
- Clean enough that I can debug it when it breaks
- Organized enough that others can understand it
- Flexible enough to handle the inevitable requirement changes
- But not so over-architected that it takes forever to build
Some stuff IS worth doing right from the start:
- Using meaningful variable/function names
- Breaking up giant components into logical pieces
- Adding comments for non-obvious code
- Setting up proper typing if you're using TypeScript
But I've stopped building elaborate systems for problems I don't have yet. That "what if we need to support 10 different languages and 5 different themes in the future?" thinking can be a huge time-waster if you're not careful.
Readable > Clever (Every Single Time)
I used to think being a "good" programmer meant writing code that looked like a genius math professor wrote it. The more compact and clever, the better!
Then I watched a colleague spend half a day trying to debug this masterpiece I wrote:
// My "look how smart I am" code
const getFullName = data => ((data || {}).user || {}).profile ?
`${data.user.profile.firstName || ''} ${data.user.profile.lastName || ''}`.trim() : '';
Now I'm a big fan of straightforward, obvious code:
// My "I want to rest well at night" code
const getFullName = (data) => {
if (!data || !data.user || !data.user.profile) {
return '';
}
const { firstName = '', lastName = '' } = data.user.profile;
return `${firstName} ${lastName}`.trim();
};
The second one takes a few more lines, but I can actually figure out what's happening when I revisit this code at 5pm on a Friday six months from now.
Actual Results
I've seen real benefits from this stuff – not just theoretical "code quality" concepts, but actual time and money saved:
- On my last team, new developers became productive in days instead of weeks
- We cut our average bug fix time in half
- Nobody panicked when asked to modify old features
- We stopped having "let's just rewrite the whole thing" conversations
My last project started with a mess, and we gradually cleaned it up. By the end, we were shipping features literally twice as fast as at the beginning. Not because we got smarter, but because we weren't fighting our own code anymore.
Baby Steps
Nobody's saying you have to convert your entire codebase overnight. Pick something small and fix it today.
Maybe:
- Rename some cryptic variables in a function you touch often
- Extract a helper that's duplicated in multiple places
- Add a few crucial comments to that weird workaround everyone keeps breaking
- Split one massive component into two more focused ones
It's like compound interest for your codebase. Small improvements add up fast, and suddenly you're not dreading every new feature request.
What clean code trick has helped you the most? Let me know – I'm always looking to add to my collection of "things I learned the hard way so you don't have to."
Now go forth and name your variables properly!
- The Web Utility Labs Team
P.S. If you're looking for a good tool to help format your code consistently, check out our Code Snippet Cleaner & Formatter – no more arguments about tabs vs. spaces!
Comments
Post a Comment