Coding Standards: Conventions, Examples and Best Practices

Raghav Chamadiya13 min read
On this page

A standard has two halves. One half is mechanical (indentation, line length, import order) and a tool should enforce it with no human involved. The other half is judgment (how big a function may get, what an error handler must do) and it belongs in code review.

Coding standards are the written rules a team follows when it writes code: how to name things, format and structure files, handle errors, comment, and test. They exist so that any developer can read any file in the codebase and predict what they will find.

Coding standards vs coding conventions vs style guides

A coding convention is a single agreed habit, such as snake_case for functions. A style guide is a document of formatting conventions. A coding standard is the full set a team commits to, including structure, quality limits and process rules, and something checks it.

The words get used interchangeably, and in a search box they mean the same thing. Inside a team it helps to keep them apart:

TermWhat it coversExampleEnforced by
Coding conventionOne habitConstants are UPPER_SNAKE_CASEHabit, review
Style guideFormatting and naming rulesPEP 8, Google Java StyleFormatter, linter
Coding standardStyle guide plus quality limits and processPEP 8 plus max complexity 10, tests required, no bare exceptFormatter, linter, CI, review

Scroll the table sideways to see every column.

The practical difference is the third column. Anyone can adopt PEP 8. A standard says what happens when someone breaks a rule: the build fails, or a reviewer blocks the merge. If nothing happens, you have a convention.

Why coding standards matter

Code is read far more often than it is written, and every unexplained difference between two files costs the reader a moment of attention. Standards remove those moments. They also remove a whole category of review comment. If a formatter fixes indentation before the pull request opens, the reviewer spends their time on the logic.

The second payoff is less obvious. Standards give you a measurable floor. "Functions stay under complexity 10" can be checked on every file, tracked over time and used to decide where to refactor. A team without one argues about whether a function is too big. A team with one runs the tool. If you want the broader picture, the code quality guide covers how standards fit with testing, review and metrics.

Coding standards examples

A good standard is specific enough to check. "Write readable code" is a wish; "no function above complexity 10" is a rule. These are the areas most standards cover, each with a concrete rule.

Naming

Pick one style per kind of name and write it down. Names should say what a thing is, not how it is stored.

python
# Avoid
def proc(d, f):
    lst = []
    ...

# Prefer
def filter_active_users(users, include_trial):
    active_users = []
    ...

Common rules: functions and variables in snake_case (Python, Rust) or camelCase (Java, JavaScript, C# locals); classes in PascalCase; constants in UPPER_SNAKE_CASE; booleans that read as questions (is_ready, hasAccess); no single-letter names outside short loops.

Formatting

Do not write formatting rules for people to remember. Pick a formatter and say "the formatter output is the standard". Indentation, quote style, trailing commas and line wrapping then stop being discussion topics. Black, Prettier, gofmt and rustfmt all work this way.

Function size and responsibility

A function does one thing and you can describe it without the word "and". Numeric limits make that checkable. A reasonable starting set: 50 lines per function, 4 parameters, complexity 10. The thresholds section below lists what real tools default to.

Complexity and nesting

Cap cyclomatic complexity (the count of independent paths through a function, explained in code complexity metrics and the glossary entry) and nesting depth. Deep nesting is usually fixed with early returns:

javascript
// Nesting depth 3
function discount(user) {
  if (user) {
    if (user.active) {
      if (user.orders > 10) {
        return 0.1;
      }
    }
  }
  return 0;
}

// Nesting depth 1
function discount(user) {
  if (!user || !user.active) return 0;
  return user.orders > 10 ? 0.1 : 0;
}

Error handling

State what an error handler must do. A usable rule: never swallow an exception; either handle it, add context and rethrow, or let it propagate.

python
# Avoid
try:
    charge(order)
except Exception:
    pass

# Prefer
try:
    charge(order)
except PaymentDeclined as exc:
    logger.warning("charge declined for order %s", order.id)
    raise OrderFailed(order.id) from exc

Comments and docstrings

Comments explain why, not what. Public functions, classes and modules get a docstring or doc comment (PEP 257 for Python, Javadoc for Java, TSDoc for TypeScript). Commented-out code is deleted, because version control remembers it.

Imports

Group them (standard library, third party, local), sort them within each group and ban wildcard imports. Tools do this automatically, so the standard only needs to name the tool: isort or Ruff's I rules, eslint-plugin-import, goimports.

Tests

New behavior ships with a test. Bug fixes ship with a test that failed before the fix. Test names describe behavior (test_expired_token_is_rejected), and tests do not depend on each other's order.

A coding standards example you can copy

Paste this into CONTRIBUTING.md and edit the numbers to match your tools.

markdown
# Coding standard

1. Formatting is whatever the formatter produces. Run it on save and in pre-commit.
2. The linter must pass with zero warnings. CI blocks the merge otherwise.
3. Names: snake_case functions, PascalCase classes, UPPER_SNAKE constants.
   Booleans start with is_, has_ or can_.
4. A function is at most 50 lines, takes at most 4 parameters, has
   cyclomatic complexity of at most 10 and nests at most 4 levels deep.
5. A file is at most 500 lines of code. Split it by responsibility, not by size.
6. No bare except, no empty catch blocks. Errors are handled, wrapped with
   context, or propagated.
7. Every public function, class and module has a docstring. Comments explain
   why. No commented-out code.
8. New behavior has a test. A bug fix has a test that failed before the fix.
9. Existing files that break rules are listed in the baseline. New and
   changed code must meet the standard.

Coding standards by language

Every major language has a community style guide and a standard toolchain. Start from those instead of inventing your own.

LanguageStyle guideFormatterLinter
PythonPEP 8, PEP 257Black or Ruff formatRuff, Pylint, flake8
JavaGoogle Java Style, Oracle conventionsgoogle-java-formatCheckstyle, PMD
JavaScript and TypeScriptAirbnb, StandardJSPrettierESLint, typescript-eslint
GoEffective Gogofmtgo vet, staticcheck, golangci-lint
RustRust Style GuiderustfmtClippy
C#.NET coding conventionsdotnet formatRoslyn analyzers, StyleCop

Scroll the table sideways to see every column.

Python code standards

PEP 8 is the base: 4 spaces per indent, lines limited to 79 characters (72 for docstrings and comments), lower_case_with_underscores for functions and variables and CapWords for classes. It also says that consistency inside a module matters more than any single rule. PEP 257 covers docstrings. Most teams enforce this with Ruff, whose formatter defaults to a line length of 88 (Black's default), and many raise it to 100 or 120. See our Python language page for what repowise parses.

Java coding standards

Two documents dominate. The Google Java Style Guide sets a column limit of 100, two-space indentation, braces on every if, for and while, and K&R brace placement. The older Oracle conventions use four spaces. Pick one, then enforce it with Checkstyle, which ships ready-made configurations for both. Checkstyle's MethodLength check defaults to 150 lines, which is lenient, so most teams lower it. More on the Java language page.

JavaScript and TypeScript

There is no official guide, so teams choose between the Airbnb style guide and StandardJS (no semicolons, two spaces) and then let Prettier own formatting. typescript-eslint adds type-aware rules such as no floating promises and no any. The TypeScript language page has the repowise side.

Go

Go removed most of the argument: gofmt formats all code the same way, and Effective Go covers naming and idioms. Standards in Go teams are mostly about which linters run through golangci-lint. See the Go language page.

Rust

rustfmt formats, and its max_width defaults to 100. Clippy lints for idioms and mistakes. Its cognitive_complexity lint has a threshold of 25, but the lint sits in Clippy's restriction group and is allowed by default, so you switch it on yourself. Teams usually run cargo clippy -- -D warnings in CI so warnings fail the build. See the Rust language page.

C#

Microsoft's .NET coding conventions cover naming, var usage and layout, and an .editorconfig file turns them into build-time analyzer rules that Visual Studio, Rider and dotnet build all respect. See the C# language page.

Default thresholds in real tools

The defaults of widely used linters give you a defensible starting point, and they show how much the tools disagree. Each value below comes from the tool's own documentation as of November 2026.

RuleToolDefault
Cyclomatic complexityESLint complexity20
Cyclomatic complexityRuff C901 (mccabe)10
Nesting depthESLint max-depth4
Lines per functionESLint max-lines-per-function50
ParametersESLint max-params3
Branches per functionPylint max-branches12
ArgumentsPylint max-args5
Statements per functionPylint max-statements50
Nested blocksPylint max-nested-blocks5
Line lengthPylint max-line-length100
Lines per modulePylint max-module-lines1000
Lines per methodCheckstyle MethodLength150
Line lengthCheckstyle LineLength80

Scroll the table sideways to see every column.

ESLint is strict on parameters (3) and lenient on complexity (20, double McCabe's 10). Ruff is the opposite on complexity. Do not copy a default because it is a default. Decide what you want, set it explicitly in config, and write the number in your standard.

In 160 public repos with 1,000+ stars, 4.12% of production files nest deeper than 4 levels, 5.96% have more than 500 lines of code, and 23.28% contain a function above McCabe's limit of 10. We measured 200,715 production files in November 2026, excluding tests, generated code and vendored code. Complexity figures come from the same dataset as code complexity metrics.

Each file has fields for max_ccn (the highest cyclomatic complexity of any single function in it), max_nesting (its deepest nesting) and nloc (non-comment, non-blank lines). We do not have per-function rows, so every complexity number describes the most complex function in each file. Nesting is counted by our analyzer and can differ by one from how a given linter counts it.

LimitFiles over itCommon source of the limit
Nesting depth above 310.01%Many style guides
Nesting depth above 44.12%ESLint max-depth default
Nesting depth above 51.62%Pylint max-nested-blocks default
Above 300 lines of code11.86%Common team limit
Above 500 lines of code5.96%Common team limit
Above 1,000 lines of code2.06%Pylint max-module-lines default
Worst function above complexity 1023.28%McCabe, Ruff default
Worst function above complexity 1514.66%Common team limit
Worst function above complexity 209.88%ESLint default
Worst function above complexity 502.08%Very high band

Scroll the table sideways to see every column.

The pattern is clear. Size and nesting limits are met by 94% to 96% of files, so a standard with "500 lines per file, 4 levels deep" is realistic for a mature codebase. The complexity limit of 10 is a different story: nearly one file in four breaks it. Setting complexity 10 as a hard gate on legacy code produces thousands of failures on day one. 74.67% of files satisfy all three of complexity 10, nesting 4 and 500 lines at once.

Per repo, the picture holds. The median repo has 3.81% of files nesting deeper than 4, 6.00% over 500 lines and 6.81% with a function above complexity 20, so the pooled numbers are not driven by a few giant repos. The lesson is to gate new code and baseline the old.

For the full distribution, language breakdown and how complexity concentrates in a few files, read code complexity metrics.

How to enforce coding standards

Enforce a standard in layers: the editor, a pre-commit hook, CI, and code review, with each layer catching what the earlier one cannot.

  1. Formatter on save. Black, Prettier, gofmt, rustfmt, google-java-format. Nobody types formatting rules by hand again.
  2. Linter. The linter checks the rules a formatter cannot: complexity, unused variables, naming, banned patterns. Configure thresholds explicitly.
  3. Pre-commit hook. Run the formatter and the fast linter checks before the commit exists. The pre-commit framework works for every language.
  4. CI gate. The same checks run on every pull request and block the merge on failure. Local hooks can be skipped; CI cannot.
  5. Code review. Reviewers check what tools cannot: whether a name is clear, whether a function does one thing. A pull request checklist keeps those judgment items consistent.
  6. A baseline for legacy code. Do not fail the build on 4,000 old violations. Record the existing ones, fail only on new ones, and shrink the list over time. ESLint has bulk suppressions (--suppress-all writes existing violations of rules set to error into eslint-suppressions.json), Ruff and flake8 have per-file ignores, and Pylint can ignore by path. Static analysis suites (compared here for large codebases) usually support "new code only" gates too.

Here is a minimal Python setup that enforces rules 1 to 4 of the example standard:

toml
# pyproject.toml
[tool.ruff]
line-length = 100

[tool.ruff.lint]
select = ["E", "F", "I", "N", "B", "C90", "PLR"]

[tool.ruff.lint.mccabe]
max-complexity = 10

[tool.ruff.lint.pylint]
max-args = 4
max-statements = 50
yaml
# .pre-commit-config.yaml
repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.17.6  # pin to the latest tag
    hooks:
      - id: ruff
        args: [--fix]
      - id: ruff-format

Then run ruff check . as a CI step. For a point-in-time view of where the codebase stands against your limits, repowise's code health analysis scores every file from 1 to 10 and flags the high-complexity functions and deep nesting, which gives you the baseline list in one pass.

Good coding practices that outlast any standard

A standard covers what a tool can check. These habits cover the rest, and they matter just as much:

  • Make the change small. A reviewer can hold a 200-line diff in their head; they cannot hold 2,000.
  • Name the thing for the reader who has never seen it.
  • Delete code you no longer need. Dead code is a rule nobody enforces, and it slows everyone down.
  • Fix the file you are in. Leave it a little cleaner than you found it.
  • Write the test before you trust the code, especially for a bug.

The clean code guide goes deeper on these, and code smells lists the patterns that tell you a standard is being broken in practice.

Pitfalls

  • Too many rules. A standard nobody can remember is a standard nobody follows. Start with ten rules and let the tools hold the rest.
  • Rules without a tool. Every rule that depends on memory will be broken. If you cannot automate it, move it to the review checklist and keep it short.
  • Copying a famous guide wholesale. The Airbnb or Google guide fits their codebase. Take the ideas and set your own numbers.
  • Rewriting history to comply. Reformatting a whole repo in one commit buries git blame. Use .git-blame-ignore-revs so the formatting commit is skipped in blame.
  • No owner. Someone has to approve changes to the standard, or it drifts into three competing versions.

FAQ

What are coding standards?
Coding standards are the written rules a development team follows when writing code. They cover naming, formatting, structure, error handling, comments and testing, and they are enforced by tools and code review so that every file in the codebase looks and behaves consistently.
Why are coding standards important?
They make code easier to read, review and change, which lowers the cost of every future edit. They remove style arguments from code review, make onboarding faster and give a team a measurable quality floor, such as a maximum function complexity, that can be checked automatically.
What is the difference between coding standards and coding conventions?
A coding convention is one agreed habit, like using snake_case for functions. A coding standard is the complete set of conventions plus quality limits and enforcement rules. A style guide sits between them: it is the document that records the formatting and naming conventions.
What are examples of coding standards?
Examples include naming rules (PascalCase for classes), a formatter such as Prettier or Black, a maximum cyclomatic complexity of 10, no more than 4 levels of nesting, docstrings on public functions, no empty catch blocks and a required test for every bug fix. Well-known published standards include PEP 8 for Python and the Google Java Style Guide.
What are Java coding standards?
Java teams usually follow the Google Java Style Guide (100-character column limit, two-space indentation, braces on every block) or the older Oracle conventions (four-space indentation). Checkstyle enforces either one and can fail a build on violations. Its MethodLength check allows 150 lines per method by default.
What is PEP 8?
PEP 8 is the official style guide for Python code. It sets 4 spaces per indentation level, a 79-character line limit, lower_case_with_underscores for functions and variables and CapWords for classes. It also stresses that consistency within a project matters more than following any single rule.
How do you enforce coding standards?
Use a formatter on save, a linter with explicit thresholds, a pre-commit hook and a CI check that blocks merges on failure. Keep code review for judgment calls such as naming and design. For legacy code, record existing violations in a baseline and fail only on new ones.
What is the purpose of coding guidelines?
Coding guidelines make a codebase predictable. When every file follows the same naming, layout and error handling rules, developers read faster, review faster and make fewer mistakes in code they did not write. Guidelines also give a team something concrete to check automatically, which keeps quality from depending on who reviewed the pull request.
What is a good maximum function complexity for a coding standard?
McCabe's original recommendation is 10 per function, and Ruff uses 10 as its default. ESLint warns at 20. For a new codebase, gate at 10. For an existing one, 20 is a more practical first limit, and you can tighten it as the worst files get fixed.