Clean Code and Naming
Clean code is code that other people, and you in six months, can read and change without fear. Good names and small, focused units do most of the work.
Naming
A good name tells the reader what something is or does, without a comment.
- Reveal intent.
daysUntilExpirybeatsd.isEligiblebeatsflag. - Be specific.
customerEmailbeatsdata. Avoid vague words such astemp,stuff,managerandhandle. - Use nouns for things and verbs for actions:
invoice,calculateTotal(). - Name booleans as questions:
isActive,hasAccess. - Follow the conventions of your language and team (
snake_case,camelCase,PascalCase). Consistency matters more than which one you pick. - Give magic numbers a name:
MAX_LOGIN_ATTEMPTS = 5. Spell out abbreviations nobody would guess.
Structure
- Give each function one job. If you need “and” to describe it, consider splitting it.
- Keep functions short enough to see at once, with few parameters.
- Avoid deep nesting. Early returns for the error cases keep the main path flat.
- Remove duplication, but wait until the pattern is clear. Copy-pasted logic gets fixed in one place and forgotten in another, yet forcing two things that merely look alike into one abstraction causes its own trouble.
- Keep related code together and unrelated code apart. See Modularity, Coupling, and Cohesion.
Comments
Comments should explain why, not repeat what the code says. If a comment is needed to explain what a block does, try a better name or a small function first. Outdated comments are worse than none.
# Python: before
def calc(l, r):
if l > 0:
if r < 100:
return l * r * 0.2
return 0
# after
VAT_RATE = 0.2
def price_with_vat(quantity, unit_price):
if quantity <= 0 or unit_price >= 100:
return 0
return quantity * unit_price * VAT_RATE
Formatters, refactoring and pull requests
- Use a formatter and a linter so style discussions are settled by the tool before review.
- Improve code in small steps and keep behaviour unchanged; see Refactoring Basics. Tests give you the confidence to do so (Unit Testing).
- Leave code a little better than you found it, but do not mix large cleanups with feature changes in one pull request.
Try it
Take a function of 20 or more lines from a project you work on. Rename its variables so that a colleague could follow it without comments, extract one chunk into a well-named function, and check that the tests still pass.
Common mistakes
- Vague names such as data, temp or flag.
- Merging two things into one abstraction just because they look alike.
- Leaving outdated comments in place.
- Mixing large cleanups with feature changes in one pull request.
Check yourself
- How would you rename a boolean called flag, and why?
- When is a comment better than a clearer name or a small function?
- Why should a cleanup not share a pull request with a feature change?