You’ve added a “coding standards” section to your CLAUDE.md. You wrote something like “follow best practices” and “write clean, readable code.” And Claude is still writing code that doesn’t quite match your style.
The problem isn’t Claude — it’s that “best practices” means different things to different developers. Claude can’t read your mind. But it can read specific, concrete rules written in plain language.
This article shows you how to write coding standards that Claude will actually follow consistently.
📋 TL;DR
– Vague rules (“write clean code”) don’t work — specific rules (“2-space indentation, no semicolons”) do
– Group standards into categories: formatting, naming, patterns, language-specific rules
– The most impactful standards to encode: formatting, naming conventions, error handling, and “never do X”
– Show examples inline in your CLAUDE.md — don’t just describe the rule, show it
– A well-structured coding standards section saves more editing time than any other CLAUDE.md section
This is part of our complete CLAUDE.md — The Complete Beginner’s Guide (2026). If you haven’t written your first CLAUDE.md yet, start with How to Create Your First CLAUDE.md File.
The Fundamental Rule: Be Specific Enough to Be Testable
A good coding standard in your CLAUDE.md is one you can test: read the code Claude wrote and check whether it followed the rule. If you can’t verify it, the rule is too vague.
Compare these:
❌ Write readable code with good naming
✅ Variable names should describe what the variable contains: use "userEmailAddress" not "email" not "e"
❌ Handle errors properly
✅ All async functions must have try/catch blocks. Caught errors must either be re-thrown or logged with logger.error() — never silently swallowed
❌ Keep functions small
✅ A function that does more than one thing should be split. If you can't name a function without using "and" or "or", it's doing too much
The testable rules produce consistent results. The vague rules produce whatever Claude interprets “good” to mean.
Category 1: Formatting Rules
Formatting rules are the easiest to write and have an immediate impact. They’re also the most objective — there’s no ambiguity about whether code uses 2 spaces or 4.
## Formatting
### Indentation and Spacing
- 2-space indentation (not 4, not tabs)
- One blank line between methods
- Two blank lines between class definitions and top-level functions
- No trailing whitespace on any line
- Files must end with a single newline character
### Line Length
- Maximum 100 characters per line
- Break long function calls across multiple lines with consistent alignment
- Chain methods with one method per line when the chain exceeds 60 characters:
// Do this
const result = someArray
.filter(item => item.active)
.map(item => item.name)
.sort()
// Not this
const result = someArray.filter(item => item.active).map(item => item.name).sort()
### Quotes and Punctuation
- Single quotes for strings (double quotes only inside JSX attributes)
- No semicolons (we use the StandardJS no-semi style)
- Trailing commas in multi-line arrays, objects, and function parameters
- No spaces before colons in object literals: `{ key: value }` not `{ key : value }`
### Import Organization
- Three groups, separated by blank lines:
1. External packages (node_modules)
2. Internal absolute imports (`@/components/...`)
3. Relative imports (`./utils`, `../types`)
- Alphabetical order within each group
💡 Pro Tip: If you already use a formatter like Prettier or Black, mention it explicitly in your CLAUDE.md. Claude will format code according to your formatter’s defaults rather than its own preferences. You can even include your key Prettier or Black settings so Claude knows what
npm run formatwill produce.
Category 2: Naming Conventions
Naming conventions are where codebases diverge most visibly. Claude’s defaults are sensible, but they may not match your conventions.
## Naming Conventions
### JavaScript / TypeScript
- Variables and functions: camelCase (`getUserById`, `isLoading`)
- React components: PascalCase (`UserProfileCard`, `InvoiceList`)
- TypeScript interfaces and types: PascalCase (`UserProfile`, `ApiResponse`)
- Constants: UPPER_SNAKE_CASE (`MAX_RETRY_COUNT`, `API_BASE_URL`)
- Private class members: prefixed with `_` (`_internalState`)
- Boolean variables: prefix with `is`, `has`, `should`, or `can`
(`isLoading`, `hasError`, `shouldRefetch`, `canDelete`)
- Event handlers: prefix with `handle` or `on` (`handleSubmit`, `onUserClick`)
### Files and Folders
- React component files: PascalCase (`UserProfileCard.tsx`)
- Utility files: camelCase (`formatCurrency.ts`)
- Config files: camelCase (`tailwind.config.ts`)
- Test files: same name as the file they test + `.test` (`UserProfileCard.test.tsx`)
- Folders: kebab-case (`user-profile/`, `api-client/`)
### Database (if applicable)
- Tables: snake_case plural (`user_accounts`, `invoice_line_items`)
- Columns: snake_case (`created_at`, `user_id`, `is_active`)
- Foreign keys: `[table_singular]_id` (`user_id`, `invoice_id`)
- Indexes: `idx_[table]_[column]` (`idx_users_email`)
Category 3: Code Organization and Structure Rules
These rules govern how code is organized within files and across the codebase.
## Code Organization
### Function Rules
- One function = one responsibility
- If you can't name a function without using "and", split it
- Functions should be short enough that their entire body is visible without scrolling
- Helper functions used only once are fine — don't over-DRY prematurely
### Class Rules (TypeScript / OOP)
- One class per file — the file name matches the class name
- Constructor should not contain business logic — just assignment
- Private methods at the bottom of the class, public methods at the top
- No more than 7-10 public methods per class — if there are more, consider splitting
### File Organization
- Each file exports one primary thing (component, class, or function group)
- Types and interfaces for a module at the top of the file
- Related functions grouped together, blank line between groups
- No circular imports — if A imports B, B must not import A
### Comments
- Comments explain *why*, not *what* — the code shows what
- A good comment: `// We use a 100ms debounce here to avoid hammering the API on every keystroke`
- A useless comment: `// Increment counter by 1`
- TODO comments must include a tracking ticket number: `// TODO: PROJ-123 — replace with real auth`
- Never leave commented-out code in a commit — delete it (git history preserves it)
Category 4: Error Handling Standards
Error handling is where the most consequential inconsistencies happen. Define your approach explicitly.
## Error Handling
### Async JavaScript / TypeScript
- All async functions must handle errors explicitly
- Use try/catch on every `await` call that could fail
- Never use `.catch(() => {})` with an empty handler — always log or re-throw
- Preferred pattern:
async function fetchUser(id: string): Promise
try {
const response = await api.get(/users/${id})
return response.data
} catch (error) {
logger.error(‘Failed to fetch user’, { userId: id, error })
throw new UserFetchError(Could not retrieve user ${id}, { cause: error })
}
}
### Custom Error Classes
- Define domain-specific error classes in `lib/errors.ts`
- Error classes extend `Error` and include a `code` property for programmatic handling
- Example error classes already in use: `AuthenticationError`, `NotFoundError`, `ValidationError`
- Use these existing error classes — don't create new ones without asking
### Error Boundaries (React)
- Wrap major page sections in Error Boundaries
- Error Boundary components in `components/ui/ErrorBoundary.tsx` — use this existing component
- Never let unhandled promise rejections reach the top level in Client Components
### Never Do These
- Never use `console.error()` in production code — use `logger.error()`
- Never swallow errors: `catch (error) { /* do nothing */ }` is forbidden
- Never rethrow the same error without adding context
Category 5: The “Never Do” List
A “never do” list is surprisingly effective. These are your bright-line rules — things Claude should refuse to do even if an approach is technically valid.
## Rules Claude Must Always Follow
- Write tests for all new utility functions (in the same PR as the utility)
- Add JSDoc comments to all exported functions
- Use the existing `logger` utility from `lib/logger` — never `console.log` in committed code
- Run `npm run validate` (lint + typecheck + test) before marking a task complete
## Rules Claude Must Never Break
- Never use `any` in TypeScript — not even temporarily
- Never write inline styles — Tailwind classes only
- Never modify files in `/src/legacy/` — this code is frozen
- Never hardcode environment-specific values — use environment variables
- Never install npm packages without asking first
- Never commit `.env` files
- Never use `==` in JavaScript — always use `===`
- Never use `var` — `const` by default, `let` when reassignment is needed
Showing Code Examples in Your CLAUDE.md
One of the most effective techniques for coding standards is showing an example rather than just describing the rule. Claude is excellent at pattern-matching from examples.
## Our Preferred Code Patterns
### Function Component Pattern
// UserProfileCard.tsx
// Props interface at top of file
interface UserProfileCardProps {
userId: string
showAvatar?: boolean
onEditClick: () => void
}
// Named export, not default export
export function UserProfileCard({ userId, showAvatar = true, onEditClick }: UserProfileCardProps) {
// Logic at top, JSX at bottom
const { data: user, isLoading } = useUser(userId)
if (isLoading) return
if (!user) return null
return (
{showAvatar &&
{user.name}
Edit profile
)
}
### Service Function Pattern
// userService.ts
// Service functions return typed results
// They throw domain errors, never HTTP errors
export async function getUserById(userId: string): Promise
try {
const user = await db.user.findUnique({ where: { id: userId } })
if (!user) {
throw new NotFoundError(User not found: ${userId})
}
return user
} catch (error) {
if (error instanceof NotFoundError) throw error
logger.error(‘Database error fetching user’, { userId, error })
throw new DatabaseError(‘Failed to fetch user’, { cause: error })
}
}
These examples become the pattern Claude anchors to. When it writes a new component, it models it on your example. When it writes a service function, it follows your pattern.
Structuring the Coding Standards Section
How you organize the section matters. Here’s the structure that works best:
## Coding Standards
### [Category 1: e.g. Formatting]
[Rules as bullet points — specific and testable]
### [Category 2: e.g. Naming Conventions]
[Rules as bullet points — specific and testable]
### [Category 3: e.g. TypeScript Rules]
[Rules with brief examples where helpful]
### [Category 4: e.g. Error Handling]
[Rules with code example showing the pattern]
### Always Do
[Short list of things Claude must include in every output]
### Never Do
[Short list of hard prohibitions — no exceptions]
Keep each bullet to one rule. Don’t combine multiple rules in a single bullet — it makes them easy to miss.
Common Mistakes in Coding Standards Sections
Writing aspirational standards instead of actual ones. If your codebase currently has both semicolons and no-semicolons, writing “no semicolons” in your CLAUDE.md won’t help Claude’s output match your existing code. Document what you actually follow, or document the standard you’re migrating toward and note it’s in transition.
Too many rules. A CLAUDE.md with 60 coding rules is hard to maintain and hard for Claude to prioritize. Focus on the 10-15 rules that change Claude’s output most.
Missing examples for complex patterns. Simple rules like “use single quotes” need no example. Complex rules like “our error handling pattern” need a code example.
Never updating the standards. Coding standards evolve. When your team adopts a new convention, update your CLAUDE.md. Otherwise Claude keeps following your old rules.
Key Takeaways
- Specific and testable** beats vague and aspirational — write rules you can verify in Claude’s output
- Five categories** cover the most impactful ground: formatting, naming, organization, error handling, and never-do rules
- Code examples in your CLAUDE.md** are worth several bullet points — Claude pattern-matches from them naturally
- A “never do” list** is one of the most effective sections — hard prohibitions produce consistent behavior
- Keep it to 10-15 rules** — prioritize the rules that change Claude’s output most, not every rule your team follows
Next Steps
- How to Add Architecture Notes to CLAUDE.md** — complement your coding standards with system design context
- CLAUDE.md Best Practices — Do’s and Don’ts** — validate your approach against common pitfalls
- Keeping Your CLAUDE.md Updated — A Simple System** — make sure your coding standards stay current as your project evolves
Return to CLAUDE.md — The Complete Beginner’s Guide (2026) for the full picture.