I've learned the hard way:
fancy code looks cool but crumbles fast.
Simple code? It grows with you.
This guide is my "house style" for clean code—think of it as a friendly checklist. It's for anyone building apps, from juniors to pros.
No jargon overload; just practical tips.
Use it, tweak it, and watch your projects hum.
Let's dive in.Why Bother with Clean Code?
For JavaScript/TypeScript (Front-End Stuff)
No jargon overload; just practical tips.
Use it, tweak it, and watch your projects hum.
Let's dive in.Why Bother with Clean Code?
- It Saves Time: Clear names and short functions mean fewer bugs and quicker fixes.
- Teams Thrive: When everyone follows the same rules, handoffs are smooth—no "What does this do?" emails.
- Future-Proofs Your Work: Code from last year still makes sense, even if you're the one who wrote it.
- My Tip: Start small. Pick one rule (like better names) and apply it today. You'll see the difference.
- Clarity Beats Clever: Choose names you'd get in six months. If it needs a long explanation, rename it.
- One Job Per Spot: Each function or file handles one thing. No multitaskers.
- Keep It Small: Aim for under 100 lines per file. Short functions, few inputs (three max—use bundles otherwise).
- Block Bad Data Early: Use types or checks to stop wrong info from sneaking in.
- Scream When Wrong: Catch errors fast with clear messages. Log them smartly, never hide them.
- Safe and Repeatable: Make actions that can retry without mess-ups, like a button that works twice.
For JavaScript/TypeScript (Front-End Stuff)
- Files and folders: Use dashes, like job-review-modal.tsx.
- Variables and functions: Camel case, like autoAcceptAt or refreshAccessToken().
- Components and types: Capitals, like JobReviewModal or type GeoRule = 'us_pr' | 'us_pr_ca'.
- Yes/No flags: Start with "is," "has," "can," like isApproved.
- Custom hooks: "use" plus action, like useLazyAutoAccept().
- Events: Dot style, like jobs.filtered_by_geo.
- Modules and functions: Underscores, like create_payment_intent.
- Classes and models: Capitals, like JobSubmission.
- Constants: All caps with underscores, like AUTO_ACCEPT_HOURS = 96.
- Tables: Plural with underscores, like jobs or submissions.
- Fields: Simple underscores, like poster_id or job_state.
- Enums: Lowercase values, like {'open', 'submitted', 'accepted'}.
- IDs: End with _id. Times: UTC strings like created_at.
- Back-End Folder Setup:
- jobs/: Routes in router.py, rules in service.py, data in repo.py.
- Same for auth/ or users/.
- Front-End Folder Setup:
- features/jobs/: Parts in components/, calls in api/, helpers in hooks/.
- Shared bits in lib/.
- Guards: ensureApproved(user).
- Checks: canTransition(oldState, newState).
- Mappers: geoRuleToCountries(rule).
- Safe Keys: makeIdempotencyKey(jobId, event).
- Focus on Why: "We wait 96 hours to give posters time without losing testers." (Not "Loop here.")
- Blocks for Big Ideas: Use for trade-offs or rules that stay true.
- Short Notes for Edges: Quick inline hits, like "Fallback to UTC—no time zones yet."
- Every Module's README: Cover "What," "How to Test," and "Watch Outs."
- Back-End Errors: Specific and helpful, like raise HTTPException(403, "Sorry, posters only.").
- Front-End Fixes: One retry on bad access, then login screen. No pop-up storms.
- Logs: Bundle details like { event: 'job_failed', userId, timeTaken }. Skip secrets.
- Back-End: Check state changes, filters, and retries.
- Front-End: Flows like "Post a Job" or "Submit Work."
- Style: "Given X, When Y, Then Z." Fake outside stuff for speed. Hit happy paths and the grumpy ones (empty inputs, timeouts).
- Formatters: Prettier for front, Black for back—run on save.
- Checkers: ESLint/TS strict; ruff for Python. Fail builds if they break.
- Commits: Label like feat: add timer or fix: login bug.
- Before Push: Hooks for auto-checks.
- PRs: Use this quick list:
- Names clear? Booleans start right?
- One job per spot? Short inputs?
- Comments explain why?
- Errors clear? Tests for edges?
- Flows work? Checks pass?
tsx
// Why: Stops unready users from posting; just checks, no changes.
function canPostJob(user: User): boolean {
return user.isApproved && user.role === 'poster';
}
Solid Back-End Timer:py# Safe to run twice—no duplicates. Why 96h: Data says it fits most users.
def auto_accept_overdue_jobs(now: datetime) -> List[str]:
overdue = query_overdue(now, hours=AUTO_ACCEPT_HOURS)
return [auto_accept_job(j.id) for j in overdue]
Skip This Mess:jsfunction doStuff(u, s) { /* Huh? Too much in one spot. */ }
No comments:
Post a Comment