Markdown Editor

Coding Standards Template

Team coding standards: naming, tool-enforced formatting, structure, errors, logging, tests, reviews, language rules

सॉफ़्टवेयर और इंजीनियरिंगमानकcodingstandards
एडिटर में खोलें.md डाउनलोड करें

उपयोग कैसे करें: Use it when a team wants to stop repeating the same review comments. Fill the formatting and linting tools first so most rules are automated, then add only rules that need a reason. The main pitfall is prose rules that contradict the existing code and are never enforced.

प्रीव्यू

Coding Standards: [Project or organisation]

Coding standards for a codebase: scope, principles, naming, tool-enforced formatting, structure, error handling, logging, testing conventions, documentation, code review expectations, language-specific rules and the exception process, with do and do not examples. Based on common industry practice. Write a rule once here instead of a hundred times in pull request comments.

FieldValue
Applies to[Repositories, languages, teams]
Owner[@name or guild]
Version[1.0]
Status[Draft / Active / Superseded]
Last reviewedYYYY-MM-DD
Enforcement[CI job name, pre-commit hook]
Related[Architecture guidelines, security standard, ADR index]

1. Scope

This standard applies to [all production and test code in the listed repositories]. It does not apply to generated code (for example [protobuf output]) or vendored third-party code, which keep their own style. Where a rule here conflicts with a framework convention, the framework convention wins and the conflict is noted in section 11.

Rule levels used below: must (enforced in review or CI), should (default, deviation needs a reason), may (optional).

2. Principles

  1. Clarity beats cleverness. Code is read far more often than it is written.
  2. Consistency with the surrounding code comes before personal preference.
  3. Make invalid states unrepresentable where the type system allows it.
  4. Fail loudly and early; never hide an error.
  5. Small, reviewable changes; one concern per change.
  6. A rule that cannot be automated needs a reason that reviewers can explain.

3. Naming

ElementConventionDoDo not
Fileskebab-caseuser-service.tsUserService.ts, user_service.ts
Types and classesPascalCase nounInvoiceRepositoryInvoiceRepoImplManager
FunctionscamelCase verb phrasefetchInvoice, isOverdueinvoice, doStuff
BooleansQuestion formisEnabled, hasAccessflag, enabled2
ConstantsSCREAMING_SNAKE_CASEMAX_RETRIESmaxretries
Units in namesSuffix the unittimeoutMs, sizeBytestimeout

Abbreviations must be ones a new team member understands; spell out anything domain-specific.

4. Formatting (tool-enforced)

Formatting is not discussed in review. The tools below decide.

ConcernToolConfigCommand
Formatting[Prettier / Black / gofmt / rustfmt][.prettierrc][pnpm format]
Linting[ESLint / Ruff / golangci-lint / Clippy][eslint.config.mjs][pnpm lint]
Type checking[tsc strict / mypy strict][tsconfig.json][pnpm typecheck]
Import order[Linter rule][Config]Included in lint
Pre-commit[lint-staged / pre-commit][Config]Runs on commit

Disabling a lint rule inline must include a reason, for example // eslint-disable-next-line no-await-in-loop -- sequential by design, rate-limited API.

5. Structure

  • Modules must depend in one direction: [ui -> application -> domain; domain imports nothing from ui].
  • Functions should do one thing at one level of abstraction; as a rough signal, split above [40] lines or [4] parameters.
  • Side effects (I/O, network, time, randomness) should live at the edges and be injected, so the core is testable.
  • Public surface must be explicit: export only what other modules use.
  • Dead code must be deleted, not commented out; version control remembers it.

Do:

export function totalDue(invoices: Invoice[], now: Date): Money {
  return invoices.filter((i) => isOverdue(i, now)).reduce(addAmount, Money.zero());
}

Do not:

export function process(data: any) {
  const now = new Date(); // hidden dependency on the clock
  // ... 120 lines mixing parsing, HTTP calls and formatting
}

6. Error handling

  • Errors must not be swallowed. An empty catch block is a review blocker.
  • Expected failures (validation, not found) should be typed results or specific error classes; unexpected failures are thrown and caught at the boundary.
  • Add context when re-throwing; keep the original error as the cause.
  • User-facing messages must not leak stack traces, SQL or internal identifiers.
  • Retries must be bounded with backoff and only for idempotent operations.

Do:

try {
  await repo.save(order);
} catch (err) {
  throw new OrderSaveError(`saving order ${order.id}`, { cause: err });
}

Do not:

try { await repo.save(order); } catch {}

7. Logging

LevelUse forExample
ERRORFailure needing actionPayment provider returned 5xx after retries
WARNUnexpected but handledCache unavailable, falling back to database
INFOBusiness-relevant eventsOrder 8812 submitted
DEBUGDiagnostic detail, off in productionParsed 42 line items
  • Logs must be structured (key-value or JSON) with a correlation or trace ID.
  • Logs must not contain secrets, tokens, passwords or full personal data; mask or omit them.
  • Log once per error, at the boundary that handles it, not at every layer.

8. Testing conventions

  • New behaviour must ship with tests; bug fixes must include a test that fails without the fix.
  • Test names describe behaviour: returns 404 when the invoice does not exist.
  • Structure tests as arrange, act, assert; one behaviour per test.
  • Tests must be deterministic: no real network, fixed clocks and seeds.
  • Coverage floor: [80% lines on changed code], used as a signal, not a goal.
  • Flaky tests are fixed or quarantined with an owner and a date within [5] working days, never silently retried.
Test typeLocationRunnerRuns in CI
Unit[src/**/*.test.ts][Vitest / pytest]Every push
Integration[tests/integration][Runner]Every push
End to end[tests/e2e][Playwright]Pull requests to main

9. Documentation and code review

9.1 Documentation

  • Comments explain why, not what the code already says.
  • Public APIs must have doc comments covering parameters, return values, errors and an example when the usage is not obvious.
  • Significant design choices are recorded in an ADR and linked from the code.
  • README files cover setup, run, test and deploy for each service.

9.2 Code review expectations

TopicExpectation
SizeAim for under [400] changed lines; split larger changes
ReadinessAll checks green and self-review done before requesting review
TurnaroundFirst response within [1 working day]
Comment labelsblocking:, suggestion:, nit:, question:
Approvals[1] approval, [2] for security-sensitive paths listed in CODEOWNERS
ToneComment on the code, not the person; explain the reason

10. Language-specific rules

Add a subsection for each language in use.

10.1 [TypeScript]

  • strict mode on; any must not be used in new code; use unknown and narrow.
  • Prefer type unions and discriminated unions over boolean flags.
  • No default exports in library code.
  • Use async/await over raw promise chains.

10.2 [Python]

  • Type hints on all public functions; mypy --strict in CI.
  • Use pathlib over os.path; f-strings over % formatting.
  • No mutable default arguments.

10.3 [SQL]

  • Keywords upper case, identifiers snake_case.
  • Parameterised queries only; string concatenation of user input is prohibited.
  • Every migration is reversible or documents why not.

11. Exceptions

A rule may be broken when the reason is documented next to the code and accepted in review. Permanent or repeated exceptions are recorded below and reviewed with this document.

IDRuleScopeReasonApproved byReview date
EX-01Example: Function length guidelineparser/grammar.tsGenerated-style state machine reads better as one function[@lead]YYYY-MM-DD
EX-02[Rule][Scope][Reason][@name]YYYY-MM-DD

Proposals to change this standard go through a pull request to this document with at least [two] approvals from [the owning guild].

Standard and licence note

Based on common industry practice for team coding standards: tool-enforced formatting, structured logging, explicit error handling and review etiquette. Language rules are examples to replace with your own. No named standard is reproduced. Template licence: MIT.

संबंधित टेम्पलेट