К основному содержанию
скилл CX Codex

coding-principles — скилл для Claude Code: принципы и установка

Скилл coding-principles для Claude Code задаёт принципы читаемого и поддерживаемого кода. Подключается при реализации функций, рефакторинге и проверке качества кода.

MIT ★ 720 обновлён 2026-11-11

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add shinpr/claude-code-workflows --skill coding-principles -a claude-code
Открыть на GitHub

Что делает coding-principles

Скилл задаёт правила для написания и изменения кода: выбирать простые решения, давать понятные имена, разделять преобразование данных и побочные эффекты, явно обрабатывать ошибки. Он также описывает работу с зависимостями, комментариями, структурой файлов и производительностью.

При изменениях скилл предлагает изучать потребителей затронутого кода и искать похожие по ответственности участки, даже если у них нет общих ссылок или названий. Публичные сигнатуры сохраняются, если их изменение не входит в согласованный результат. Оптимизацию рекомендуют начинать после измерения узких мест.

Какие задачи решает

  • реализовать функцию с понятной структурой и обработкой ошибок
  • отделить побочные эффекты от преобразования данных
  • найти похожую логику в соседних модулях
  • решить, когда разбить файл или выделить функцию
  • проверить изменения публичного контракта и его потребителей

Примеры запросов агенту

  • Реализуй эту функцию по принципам читаемого и поддерживаемого кода.
  • Отрефактори модуль: отдели побочные эффекты и сохрани публичные сигнатуры.
  • Проверь изменения и найди потребителей затронутого публичного контракта.

Как установить coding-principles

1Через Skills CLI (Vercel)

npx skills add shinpr/claude-code-workflows --skill coding-principles -a claude-code

2Вручную: положить файлы

~/.claude/skills/coding-principles/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/coding-principles/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о coding-principles

Как установить coding-principles в Claude Code?

Выполни npx skills add shinpr/claude-code-workflows --skill coding-principles -a claude-code.

Что делает coding-principles?

Скилл задаёт принципы проектирования функций, обработки ошибок, зависимостей и организации кода. Claude Code подключает его при реализации функций, рефакторинге и проверке качества.

Когда Claude Code использует coding-principles?

При работе над функциями, рефакторингом кода и проверкой его качества.

Исходный текст

SKILL.md · MIT
---
name: coding-principles
description: Language-agnostic coding principles for maintainability, readability, and quality. Use when implementing features, refactoring code, or reviewing code quality.
---

# Language-Agnostic Coding Principles

## Core Philosophy

1. **Maintainability over Speed**: Prioritize long-term code health over initial development velocity
2. **Simplicity First**: Choose the simplest solution that meets requirements (YAGNI principle)
3. **Design Convergence**: Deliver the current required outcome with the least new design surface. Selecting persistent state, public or cross-boundary contracts, behavioral modes, reusable abstractions, or component splits carries enough surface to justify the full convergence process first.
4. **Explicit over Implicit**: Make intentions clear through code structure and naming
5. **Delete over Comment**: Remove unused code instead of commenting it out

## Code Quality

### Continuous Improvement
- Refactor related code inside the accepted outcome and governing boundaries when it reduces the change's risk or maintenance cost
- Improve code structure incrementally
- Keep the codebase lean and focused
- Delete code proven obsolete by the requested change after checking its callers; report uncertain or out-of-scope cleanup separately

### Readability
- Use meaningful, descriptive names drawn from the problem domain
- Use full words in names; abbreviations are acceptable only when widely recognized in the domain
- Use descriptive names; single-letter names are acceptable only for loop counters or well-known conventions (i, j, x, y)
- Extract magic numbers and strings into named constants
- Keep code self-documenting where possible

## Function Design

### Parameter Management
- Group related positional parameters into an object, struct, or dictionary when call-site clarity or coordinated evolution requires it. Retain positional parameters when their order is conventional and the call remains clear, or an external/public signature requires them
- Preserve external/public signatures unless their migration is part of the accepted outcome or governing artifact

### Single Responsibility
- Each function should do one thing well
- Extract a function when independently changing responsibilities or obscured control flow make the current unit harder to understand, verify, or reuse; retain a cohesive domain flow when extraction would create artificial coupling
- Extract complex logic into separate, well-named functions
- Functions should have a single level of abstraction

### Function Organization
- Pure functions when possible (no side effects)
- Separate data transformation from side effects
- Use early returns to reduce nesting
- Use early returns or extraction when nesting obscures state transitions or decision ownership; retain nested structure when it maps the domain decision more clearly

## Error Handling

### Error Management Principles
- **Always handle errors**: Log with context or propagate explicitly
- **Log appropriately**: Include context for debugging
- **Protect sensitive data**: Mask or exclude passwords, tokens, PII from logs
- **Fail fast**: Detect and report errors as early as possible

### Error Propagation
- Use language-appropriate error handling mechanisms
- Propagate errors to appropriate handling levels
- Provide meaningful error messages
- Include error context when re-throwing

## Dependency Management

### Loose Coupling via Parameterized Dependencies
- Inject external dependencies as parameters (constructor injection for classes, function parameters for procedural/functional code)
- Depend on abstractions, not concrete implementations
- Minimize inter-module dependencies
- Facilitate testing through mockable dependencies

## Reference Representativeness

Existing code relates to a change in two ways. Code that depends on it — callers, consumers, configuration — is reached through references to the changed code. Code that already holds the same responsibility may share no name or reference with it; reach it through position and role (sibling features, files with the same role in the same layer, shared layers) and through the input it takes and the purpose it serves, then compare their logic to judge whether the responsibility is the same.

When alternatives coexist, choose the pattern from responsibility, contract, lifecycle and repository usage rather than proximity or global popularity alone. Record the evidence only when it changes the choice.

Expand to all known consumers for a changed public, shared, serialized or persistent contract whose compatibility depends on them. Stop when the candidates that could change implementation or proof have been read and judged; a search with no match shows only that the search found nothing. Resolve versions from applicable manifests and usage; record a specific limitation only when required compatibility evidence remains unavailable.

## Performance Considerations

### Optimization Approach
- **Measure first**: Profile before optimizing
- **Focus on algorithms**: Algorithmic complexity > micro-optimizations
- **Use appropriate data structures**: Choose based on access patterns
- **Resource management**: Handle memory, connections, and files properly

### When to Optimize
- After identifying actual bottlenecks through profiling
- When performance issues are measurable
- Optimize only after measurable bottlenecks are identified, not during initial development

## Code Organization

### Structural Principles
- **Group related functionality**: Keep related code together
- **Separate concerns**: Domain logic, data access, presentation
- **Consistent naming**: Follow project conventions
- **Module cohesion**: High cohesion within modules, low coupling between

### File Organization
- One primary responsibility per file
- Logical grouping of related functions/classes
- Clear folder structure reflecting architecture
- Split a file when it contains independently changing responsibilities or creates material navigation, coupling, or verification cost; retain a cohesive file when splitting would add avoidable coupling or navigation cost

## Commenting Principles

### Default: code first
Names, types, and structure are the primary medium. A comment earns its place only by carrying information the code itself cannot express. When in doubt, improve the name instead of adding a comment.

### The test for every comment
A comment is justified only if it answers one of these:
- **Why**: reasoning, trade-off, or constraint behind a non-obvious decision
- **Limitation / edge case**: a boundary a reader cannot infer from the code
- **Public API contract**: behavior, inputs, outputs of an exported interface

One comment per decision. If a comment restates what the names and control flow already show, delete it and rename instead.

### Comment Scope
- Comment the why, limits, and public contracts (per the test above); let names and structure carry everything else, including the "how"
- Record historical context in version control commit messages, not in comments
- Delete commented-out code (retrieve from git history when needed)

### Comment Quality
- Base comments on stable rationale, limits, and contracts rather than dates, versions, temporary state, or references to documents and their sections, which drift as those documents change
- Update comments when changing code
- Use proper grammar and formatting
- Write for future maintainers

## Refactoring Approach

### Safe Refactoring
- **Small steps**: Make one change at a time
- **Maintain working state**: Keep tests passing
- **Verify behavior**: Run tests after each change
- **Incremental improvement**: Make the smallest sufficient improvement in each increment

### Refactoring Triggers
- Code duplication (DRY principle)
- Functions that contain independently changing responsibilities or obscured control flow
- Complex conditional logic
- Unclear naming or structure

## Security Principles

### Secure Defaults
- Store credentials and secrets through environment variables or dedicated secret managers
- Use parameterized queries (prepared statements) for all database access
- Use established cryptographic libraries provided by the language or framework
- Generate security-critical values (tokens, IDs, nonces) with cryptographically secure random generators
- Encrypt sensitive data at rest and in transit using standard protocols

### Input and Output Boundaries
- Validate all external input at system entry points for expected format, type, and length. External input includes request data, external service responses, model or tool output, and stored data whose writer is untrusted or whose consumer needs a guarantee the store does not make
- When a change alters a boundary where external content or model output selects a tool's action, target, or destination, verify that those values cannot exceed the operation scope and access rights already granted to the caller
- Encode output appropriately for its rendering context (HTML, SQL, shell, URL)
- Return only information necessary for the caller in error responses; log detailed diagnostics server-side

### Access Control
- Apply authentication to all entry points that handle user data or trigger state changes
- Verify authorization for each resource access, not only at the entry point
- Grant only the permissions required for the operation (files, database connections, API scopes)
- For changes involving identity or protected resources, prioritize authentication and per-resource authorization review

For concrete detection patterns used by security review, see `references/security-checks.md`.

## References

- [references/frontend.md](references/frontend.md): read when implementing, reviewing, or fixing React/TypeScript code

© shinpr · MIT · shinpr/claude-code-workflows

Похожие скиллы

Все скиллы по теме «Код-ревью и рефакторинг» →
principle-boundary-discipline backnotprop Скилл principle-boundary-discipline для Claude Code выносит валидацию на внешние границы системы. Включается при настройке адаптеров фреймворков, разборе конфигов, CLI-аргументов и ответов API. CX Codex +1 10 100установок software-design-principles databricks-solutions Скилл software-design-principles для Claude Code задаёт правила архитектурного ревью, планирования рефакторинга и проверки зависимостей. Помогает согласовать слои и зоны ответственности перед слиянием PR. CX Codex +1 ★ 38звёзд репо clean-code-principles AsyrafHussin Скилл clean-code-principles для ревью архитектуры и качества кода: SOLID, DRY, KISS, паттерны проектирования. Пригодится при рефакторинге и обсуждении решений по дизайну. CX Codex +1 1 900установок Coding Structure with MVC and SOLID Principles Abdooo2235 Промпт Coding Structure with MVC and SOLID Principles превращает ИИ в эксперта по архитектуре ПО для разбора паттерна MVC и принципов SOLID на практических примерах кода. GP ChatGPT ★ 178 201звёзд репо solid ramziddin Скилл внедряет в работу ассистента инженерные стандарты: цикл TDD, принципы SOLID и строгие правила чистоты кода. Пригодится при проектировании архитектуры и рефакторинге. CX Codex +1 3 700установок thinking-first-principles tjboudreaux Скилл thinking-first-principles для Claude Code отделяет реальные ограничения от привычек и перестраивает решение с нуля. Запускается, если задачу останавливает «так не делается» без доказательств. CX Codex +1 844установок

Из того же набора43

Весь набор →
code-verifier Субагент code-verifier для Claude Code сверяет утверждения в PRD, дизайн-документах и планах работ с кодом репозитория. Его запускают перед ревью документа, после реализации или для проверки описания существующей системы. CX Codex ★ 720звёзд репо scope-discoverer Субагент scope-discoverer разбирает кодовую базу на функциональные блоки и связи для обратного документирования. Помогает подготовить фундамент под PRD. CX Codex ★ 720звёзд репо ui-spec-designer Субагент ui-spec-designer для Claude Code превращает требования к интерфейсу в спецификацию экранов, состояний и компонентов. Запускается при проектировании фронтенда или запросе на разбиение UI на компоненты. CX Codex ★ 720звёзд репо integration-test-reviewer Субагент integration-test-reviewer ревьюит изменённые интеграционные и E2E-тесты: доказывают ли они заявленное поведение. На выходе только существенные пробелы и минимальные правки. CX Codex ★ 720звёзд репо recipe-design Скилл recipe-design для Claude Code координирует проектирование архитектуры от анализа кодовой базы до утверждения Design Doc. Процесс включает промежуточные остановки для подтверждения решений человеком. CX Codex +1 ★ 720звёзд репо code-reviewer Субагент code-reviewer для Claude Code проверяет готовые изменения по требованиям проекта, контрактам и правилам качества. Запускается после реализации или по запросу на ревью и проверку соответствия. CX Codex ★ 720звёзд репо solver Субагент solver подбирает несколько вариантов исправлений для подтверждённой причины бага и сравнивает компромиссы. Помогает выбрать оптимальный путь без повторного расследования. CX Codex ★ 720звёзд репо design-sync Субагент design-sync сопоставляет Design Docs, находит противоречия в общих требованиях и выдаёт структурированный отчёт. Запускайте его, когда нужно проверить согласованность нескольких документов. CX Codex ★ 720звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой