Skip to content

How do I write clean code that other people can actually read?

My code works but when I come back a month later I can't follow it. What are the habits that make code readable?
115
1 answers4K views

1 Answer

Accepted answer

RNRahul N.2.1K XP1mo ago
Clean code is mostly naming and size. If you only changed two habits — name things accurately, and keep functions small enough to hold in your head — your code would jump most of the way to readable, before any principle or pattern is involved. Naming, which is where the biggest gains are: - Name what it is, not what type it is. `activeUsers` not `arr2`. `daysUntilExpiry` not `d`. - Booleans should read as questions: `isLoading`, `hasPermission`, `canEdit`. Then `if (hasPermission)` reads like English. - Functions should be verbs describing the effect: `calculateTotal`, `sendWelcomeEmail`, `validateAddress`. - Avoid abbreviations that only make sense to you today. Typing eight more characters costs nothing; decoding `usrDtLst` in six months costs real time. - If a name needs a comment to explain it, the name is wrong. Rename instead of commenting. Size and structure: - One function, one job. If you're writing 'and' in the description of what it does, split it. Functions that fit on a screen without scrolling can be understood as a unit. - Reduce nesting with early returns. Three levels of `if` inside each other is much harder to follow than guard clauses that handle the exceptional cases first and return. - Keep related things close together. A variable declared forty lines before its use forces the reader to hold it in memory. Comments — the rule that surprises people: comment *why*, not *what*. `// increment counter` above `counter++` is noise. `// The API returns dates in UTC but the report is read in IST, so we shift here` is genuinely valuable, because the code cannot express that reasoning. If you feel the urge to explain *what* a block does, it's usually a sign the block should be an obviously named function instead. Consistency over personal preference: match the style of the codebase you're in, even where you'd do it differently. A codebase with one consistent mediocre convention is easier to work in than one with five excellent conflicting ones. Use a formatter (Prettier or your language's equivalent) so nobody spends attention on spacing. The test that works better than any checklist: read your code out loud, or explain it line by line to someone. Anywhere you have to say 'and this bit is basically…' is a spot that needs a better name or a smaller function. Alternatively, come back to it deliberately after a week — you already discovered that this reveals the problems, so use it as a review step rather than an unpleasant surprise.
87

Know the answer?

Join Nobink to answer, vote and build your reputation.