Elite Coder Standards
Core Philosophy
Apply these principles in strict priority order:
- Correctness — Code does what it claims. No silent failures.
- Clarity — A stranger reads it and understands it immediately.
- Simplicity — The least code that solves the actual problem.
- Robustness — Graceful handling of edge cases and bad input.
- Performance — Fast enough, measured not guessed.
Hard Limits
These are non-negotiable. NEVER violate them.
80 characters max per line
No exception. Break the line. Use intermediate variables, extract
helpers, or restructure the expression. Long lines are a code smell
indicating excessive nesting or complexity.
20 lines max per function
Count only logic lines (exclude blank lines, docstrings, and the
signature). If a function exceeds 20 lines, decompose it. Extract
a helper, split the workflow, or rethink the approach.
5 functions max per file
If a module needs more than 5 functions (excluding __init__ and
dunder methods), it has too many responsibilities. Split it into
focused modules with clear names.
Naming Conventions
- Names reveal intent:
remaining_retries not r, is_valid not flag
- Use domain vocabulary:
invoice, order, not data, item
- Booleans: prefix with
is_, has_, can_, should_
- Functions: strong verbs —
parse_config,
validate_input, send_notification
- Python:
snake_case for functions/variables,
PascalCase for classes, UPPER_SNAKE for constants
- No abbreviations unless universally understood (
url, id, http)
Function Design
- Single responsibility: one function, one job
- Max 3 parameters: beyond that, use a dataclass or config object
- Guard clauses first: handle invalid cases early with early returns
- Pure functions preferred: same input, same output, no side effects
- 20 lines max: if it does not fit, decompose (see Hard Limits)
# Good: guard clauses + single responsibility
def calculate_discount(price: float, tier: str) -> float:
if price <= 0:
raise ValueError("Price must be positive")
if tier not in DISCOUNT_TIERS:
raise ValueError(f"Unknown tier: {tier}")
rate = DISCOUNT_TIERS[tier]
return round(price * rate, 2)
Error Handling
- Never use bare
except: or except Exception:
- Catch specific exceptions:
except ValueError, except KeyError
- Fail fast: validate inputs at boundaries, crash early
- Error messages must be actionable: say what went wrong AND what to do
- Use custom exceptions for domain errors
# Bad
try:
process(data)
except:
pass
# Good
try:
process(data)
except ValidationError as e:
logger.warning("Invalid input: %s", e)
raise
Code Structure
Python project layout:
project/
pyproject.toml
src/
package/
__init__.py
module.py
tests/
test_module.py
- Imports: stdlib first, then third-party, then
local — separated by blank lines
- No dead code: delete unused functions,
commented-out blocks, and TODO-marked stubs
- Max 5 functions per file: split into focused modules (see Hard Limits)
- One class per file when the class is non-trivial
Testing
- Test behavior, not implementation details
- Descriptive names:
test_expired_token_returns_401 not test_auth
- AAA pattern: Arrange, Act, Assert — clearly separated
- Cover edge cases: empty inputs, boundaries, error paths
- Reproduce the bug first: write a failing test before fixing
def test_discount_rejects_negative_price():
with pytest.raises(ValueError, match="positive"):
calculate_discount(-10, "gold")
Security
- No hardcoded secrets: use environment variables or a vault
- Validate all external input: user data, API payloads, file content
- Parameterized queries: never concatenate SQL strings
- Least privilege: request minimal permissions, scopes, and access
Performance
- Choose the right data structure:
set for membership, dict for lookup
- Avoid N+1 queries: batch database calls
- Know your complexity: O(n) vs O(n^2) matters at scale
- Paginate large result sets — never return unbounded lists
Git Discipline
- Atomic commits: one logical change per commit
- Conventional commits:
type(scope): description
- Types:
feat, fix, refactor, test, docs, chore
- Never commit:
.env, __pycache__, .pyc, IDE configs, build artifacts
- Write meaningful commit messages that explain WHY, not WHAT
Documentation
- Code is self-documenting when names and structure are clear
- Comments explain WHY, never WHAT — the code shows WHAT
- Docstrings for public API only (public functions, classes, modules)
- Keep docstrings concise: one-line summary, then params if needed
def retry(fn, max_attempts=3):
"""Call fn with exponential backoff on failure."""
Self-Review Checklist
Before finalizing any code, verify:
For detailed conventions, refactoring patterns, and API design
guidance, consult references/detailed-guidelines.md.
1---2name: elite-coder3description: Enforces elite coding standards and conventions when writing code, refactoring, reviewing, or discussing best practices. Use when user asks to write code, do a code review, apply clean code principles, or follow best practices. Covers Python primarily, with universal principles for any language.4license: MIT5---67# Elite Coder Standards89## Core Philosophy1011Apply these principles in strict priority order:12131. **Correctness** — Code does what it claims. No silent failures.142. **Clarity** — A stranger reads it and understands it immediately.153. **Simplicity** — The least code that solves the actual problem.164. **Robustness** — Graceful handling of edge cases and bad input.175. **Performance** — Fast enough, measured not guessed.1819## Hard Limits2021These are non-negotiable. NEVER violate them.2223### 80 characters max per line2425No exception. Break the line. Use intermediate variables, extract26helpers, or restructure the expression. Long lines are a code smell27indicating excessive nesting or complexity.2829### 20 lines max per function3031Count only logic lines (exclude blank lines, docstrings, and the32signature). If a function exceeds 20 lines, decompose it. Extract33a helper, split the workflow, or rethink the approach.3435### 5 functions max per file3637If a module needs more than 5 functions (excluding `__init__` and38dunder methods), it has too many responsibilities. Split it into39focused modules with clear names.4041## Naming Conventions4243- Names reveal intent: `remaining_retries` not `r`, `is_valid` not `flag`44- Use domain vocabulary: `invoice`, `order`, not `data`, `item`45- Booleans: prefix with `is_`, `has_`, `can_`, `should_`46- Functions: strong verbs — `parse_config`,47 `validate_input`, `send_notification`48- Python: `snake_case` for functions/variables,49 `PascalCase` for classes, `UPPER_SNAKE` for constants50- No abbreviations unless universally understood (`url`, `id`, `http`)5152## Function Design5354- **Single responsibility**: one function, one job55- **Max 3 parameters**: beyond that, use a dataclass or config object56- **Guard clauses first**: handle invalid cases early with early returns57- **Pure functions preferred**: same input, same output, no side effects58- **20 lines max**: if it does not fit, decompose (see Hard Limits)5960```python61# Good: guard clauses + single responsibility62def calculate_discount(price: float, tier: str) -> float:63 if price <= 0:64 raise ValueError("Price must be positive")65 if tier not in DISCOUNT_TIERS:66 raise ValueError(f"Unknown tier: {tier}")6768 rate = DISCOUNT_TIERS[tier]69 return round(price * rate, 2)70```7172## Error Handling7374- **Never** use bare `except:` or `except Exception:`75- Catch specific exceptions: `except ValueError`, `except KeyError`76- **Fail fast**: validate inputs at boundaries, crash early77- Error messages must be actionable: say what went wrong AND what to do78- Use custom exceptions for domain errors7980```python81# Bad82try:83 process(data)84except:85 pass8687# Good88try:89 process(data)90except ValidationError as e:91 logger.warning("Invalid input: %s", e)92 raise93```9495## Code Structure9697Python project layout:9899```100project/101 pyproject.toml102 src/103 package/104 __init__.py105 module.py106 tests/107 test_module.py108```109110- **Imports**: stdlib first, then third-party, then111 local — separated by blank lines112- **No dead code**: delete unused functions,113 commented-out blocks, and TODO-marked stubs114- **Max 5 functions per file**: split into focused modules (see Hard Limits)115- **One class per file** when the class is non-trivial116117## Testing118119- Test **behavior**, not implementation details120- Descriptive names: `test_expired_token_returns_401` not `test_auth`121- **AAA pattern**: Arrange, Act, Assert — clearly separated122- Cover edge cases: empty inputs, boundaries, error paths123- **Reproduce the bug first**: write a failing test before fixing124125```python126def test_discount_rejects_negative_price():127 with pytest.raises(ValueError, match="positive"):128 calculate_discount(-10, "gold")129```130131## Security132133- **No hardcoded secrets**: use environment variables or a vault134- **Validate all external input**: user data, API payloads, file content135- **Parameterized queries**: never concatenate SQL strings136- **Least privilege**: request minimal permissions, scopes, and access137138## Performance139140- Choose the right data structure: `set` for membership, `dict` for lookup141- Avoid N+1 queries: batch database calls142- Know your complexity: O(n) vs O(n^2) matters at scale143- Paginate large result sets — never return unbounded lists144145## Git Discipline146147- **Atomic commits**: one logical change per commit148- **Conventional commits**: `type(scope): description`149 - Types: `feat`, `fix`, `refactor`, `test`, `docs`, `chore`150- Never commit: `.env`, `__pycache__`, `.pyc`, IDE configs, build artifacts151- Write meaningful commit messages that explain WHY, not WHAT152153## Documentation154155- **Code is self-documenting** when names and structure are clear156- Comments explain **WHY**, never WHAT — the code shows WHAT157- Docstrings for public API only (public functions, classes, modules)158- Keep docstrings concise: one-line summary, then params if needed159160```python161def retry(fn, max_attempts=3):162 """Call fn with exponential backoff on failure."""163```164165## Self-Review Checklist166167Before finalizing any code, verify:168169- [ ] All lines under 80 characters170- [ ] All functions under 20 lines171- [ ] All files under 5 functions172- [ ] Names reveal intent173- [ ] No bare except clauses174- [ ] No hardcoded secrets175- [ ] Guard clauses used for validation176- [ ] Tests cover the happy path and edge cases177- [ ] No dead code or commented-out blocks178- [ ] Imports are sorted (stdlib / third-party / local)179180For detailed conventions, refactoring patterns, and API design181guidance, consult `references/detailed-guidelines.md`.