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

clean-code · mindrally — скилл для Claude Code: правила и установка

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

Apache-2.0 182 установок ★ 312 обновлён 2026-10-08

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

Что делает clean-code

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

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

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

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

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

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

Как установить clean-code

1Через Skills CLI (Vercel)

npx skills add Mindrally/skills --skill clean-code -a claude-code

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

~/.claude/skills/clean-code/SKILL.md

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

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

Вопросы о clean-code

Как установить clean-code в Claude Code?

Выполни npx skills add Mindrally/skills --skill clean-code -a claude-code. Файл скилла будет доступен по пути ~/.claude/skills/clean-code/SKILL.md.

Что делает clean-code?

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

Когда clean-code предлагает выносить повторяющийся код в абстракцию?

Правило трёх предлагает дождаться третьего появления паттерна. Первые два повторения остаются без преждевременного обобщения.

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

SKILL.md · Apache-2.0
---
name: clean-code
description: "Clean, maintainable, human-readable code principles combined with anti-over-engineering discipline: naming, single responsibility, DRY, and scoping changes to exactly what was requested. Use when writing new code, refactoring existing code, reviewing code for quality, or deciding how much abstraction a change actually needs."
metadata:
  maintainer: Mindrally
  source: https://github.com/Mindrally/skills
---

# Clean Code

This skill covers writing code that is easy to read and change, and — just as important — avoiding the over-engineering that makes code harder to read and change in the name of "best practices." Both halves matter together: clean code is simple code, not merely well-decorated code.

## Workflow for Writing or Reviewing Code

1. **Scope the change** — Identify exactly what was asked for. Note what's out of scope before writing anything.
2. **Reach for the simplest solution first** — Prefer the direct, obvious implementation over a general or configurable one, unless a concrete current need justifies more.
3. **Name things for their purpose** — Choose names that reveal intent before writing the body of a function or the shape of a type.
4. **Keep functions single-purpose** — If a function needs a comment to explain what it does, split it.
5. **Remove duplication deliberately** — Extract shared logic only once it's actually duplicated (see Rule of Three below), not preemptively.
6. **Write or update tests** — Cover the new behavior and the edge cases it introduces.
7. **Verify scope before delivery** — Confirm only the requested code changed, check for a simpler approach you might have missed, and confirm no unrequested files were touched.

## Meaningful Names

- Variables, functions, and classes should reveal their purpose from the name alone.
- Names should explain why something exists and how it's used, not just its type or contents (`activeUserIds`, not `list1`).
- Avoid abbreviations unless they're universally understood in the domain (`id`, `url` — fine; `usrCfgTmp` — not fine).

## Constants Over Magic Numbers

- Replace hard-coded values with named constants (`MAX_RETRY_COUNT = 3`, not a bare `3` three call sites later).
- Use descriptive constant names that explain the value's purpose, not just its value.
- Keep constants at the top of the file or in a dedicated constants module when shared across files.

## Smart Comments

- Don't comment on what the code does — make the code self-documenting through naming and structure instead.
- Use comments to explain *why* something is done a certain way, especially when the reason isn't visible in the code (a workaround for a library bug, a non-obvious ordering requirement).
- Document public APIs, genuinely complex algorithms, and non-obvious side effects.

## Single Responsibility

- Each function should do exactly one thing.
- Functions should be small and focused enough to be understood without scrolling.
- If a function needs a comment to explain what it does, that's a signal to split it into named sub-functions instead.

## DRY — Don't Repeat Yourself

- Extract repeated code into reusable functions once the repetition is real, not anticipated.
- Share common logic through a proper abstraction — a shared function or module, not copy-paste with tweaks.
- Maintain a single source of truth for any given piece of business logic or configuration value.

## Encapsulation

- Hide implementation details behind a clear interface; callers shouldn't need to know how a thing works to use it.
- Move nested conditionals into well-named functions or guard clauses instead of deep `if`/`else` trees.

```js
// Before
function canCheckout(cart) {
  if (cart.items.length > 0) {
    if (cart.user.isVerified) {
      if (cart.total <= cart.user.creditLimit) {
        return true;
      }
    }
  }
  return false;
}

// After
function canCheckout(cart) {
  const hasItems = cart.items.length > 0;
  const isWithinCreditLimit = cart.total <= cart.user.creditLimit;
  return hasItems && cart.user.isVerified && isWithinCreditLimit;
}
```

## Clean Structure

- Keep related code together (a feature's components, hooks, and styles in one directory, not scattered by file type).
- Organize code in a logical hierarchy that mirrors how the domain is understood.
- Use consistent file and folder naming conventions across the codebase.

## Avoiding Over-Engineering

- Only change what was asked. The simplest solution that satisfies the request comes first.
- When the right level of abstraction is unclear, ask rather than guessing toward the more elaborate option.
- Do not modify unrequested code, even if it looks improvable — a drive-by refactor in an unrelated function expands the review surface and the risk of the change.
- Do not add abstractions (interfaces, factories, plugin systems, config layers) without a concrete, current need. A single implementation doesn't need an interface "in case" a second one shows up later — that's speculative generality (YAGNI: "You Aren't Gonna Need It").
- Do not import a new dependency to solve a problem a few lines of existing code already solve.
- Do not rewrite entire files for small changes — a targeted diff is easier to review and safer to ship than a full-file rewrite.
- Do not add error handling for scenarios that cannot occur given the surrounding code's guarantees — defensive code for impossible states adds reading cost without adding safety.

### Rule of Three

- Tolerate duplication the first two times a pattern appears.
- Extract an abstraction on the third occurrence, once the actual shape of the shared logic is clear — extracting after one or two instances often guesses wrong about what's actually shared.

### Signs of Over-Engineering

- A configuration option that has only ever been set to one value.
- An interface with exactly one implementation and no test double that needs a second.
- A generic `options` object accreting fields for hypothetical future callers.
- A plugin/strategy pattern introduced before there are two strategies to switch between.

## Code Quality Maintenance

- Refactor continuously in small steps rather than deferring cleanup to a dedicated "refactor sprint."
- Fix technical debt early, while the context for why the code looks the way it does is still fresh.
- Leave code cleaner than you found it, scoped to the area you're already touching — not as license to refactor unrelated files.

## Testing

- Write a failing test before fixing a bug, so the fix is verified and the bug can't silently regress.
- Keep tests readable and maintainable — a test that's harder to understand than the code it tests has failed at its job.
- Test edge cases and error conditions explicitly, not just the happy path.

## Version Control

- Write clear, specific commit messages that explain why a change was made.
- Make small, focused commits — one logical change per commit.
- Use meaningful branch names that describe the work, not the author or the date.

## Before Delivery Checklist

- Only the requested code changed — no unrelated files touched.
- No abstraction was added without a concrete need that exists today.
- No dependency was added that duplicates something already available.
- A simpler approach was considered and ruled out, not just skipped.
- New behavior has test coverage, including at least one edge case.

© Mindrally · Apache-2.0 · Mindrally/skills

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

Все скиллы по теме «Код-ревью и рефакторинг» →

Сначала — clean-code от других авторов.

clean-code sickn33 Помогает писать и рефакторить код по принципам Clean Code: проясняет имена, упрощает функции и выявляет хрупкую структуру. Применяется при ревью и работе с легаси-кодом. CX Codex +1 13 100установок clean-code wondelai Скилл clean-code для ИИ-агентов, который задаёт планку читаемости кода: имена, мелкие функции, дисциплина комментариев, единая обработка ошибок. CX Codex +1 7 200установок clean-code ciembor Скилл clean-code для Claude Code применяет правила чистого кода при правках читаемости, имён и устройства функций. Он включается в задачах повседневной разработки и тестирования кода. CX Codex +1 683установок clean-code decebals Скилл clean-code учит агента принципам DRY, KISS и YAGNI, правилам именования и структурированию функций. Помогает при рефакторинге запутанного кода с длинными методами. CX Codex +1 448установок clean-code pproenca Скилл clean-code для Claude Code, который подключает 48 правил из «Чистой архитектуры» Роберта Мартина. Срабатывает при ревью кода, нейминге, проектировании функций и написании тестов. CX Codex +1 871установок clean-architecture wondelai Скилл clean-architecture держит бизнес-правила отдельно от фреймворка и базы: исходники зависят только от внутренних слоёв, и это проверяется по чек-листу. CX Codex +1 8 000установок clean-code-guard amElnagdy Скилл clean-code-guard проверяет свежий код по Clean Code и SOLID, ловит повторяющиеся провалы LLM и работает в трёх режимах: прогон диффа, правка по правилам, ревью. CX Codex +1 4 900установок clean-code-principles AsyrafHussin Скилл clean-code-principles для ревью архитектуры и качества кода: SOLID, DRY, KISS, паттерны проектирования. Пригодится при рефакторинге и обсуждении решений по дизайну. CX Codex +1 1 900установок typescript-clean-code bmad-labs Скилл typescript-clean-code для ревью и рефакторинга TypeScript: каталоги запахов кода, четыре слоя проверки и готовые рабочие процессы. CX Codex +1 669установок clean-code-ts-react pproenca Скилл clean-code-ts-react переносит принципы Clean Code Роберта Мартина на TypeScript 5.x и React 19. Помогает на код-ревью, при рефакторинге и проектировании компонентов или функций. CX Codex +1 238установок code-refactoring-refactor-clean rmyndharis Скилл code-refactoring-refactor-clean для Claude Code помогает очищать и перестраивать существующий код. Включается при работе со сложными модулями, дублированием и проблемами тестируемости. CX Codex +1 154установок

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

Весь набор →
lerna Скилл задаёт агенту правила Lerna: структура пакетов, версионирование, публикация и запуск скриптов в монорепозитории. CX Codex +1 692установок onchainkit Помогает собирать onchain-приложения на OnchainKit SDK: компоненты, провайдеры, транзакции и обмен токенов. CX Codex +1 682установок robocorp-cursor-rules Набор правил для ИИ-агента: как писать RPA-автоматизацию на Python под RoboCorp — функционально, с Pydantic и async. CX Codex +1 677установок parcel-bundler Скилл parcel-bundler для Claude Code задаёт агенту правила работы со сборщиком Parcel: точки входа, TypeScript, CSS-модули, кэш и продакшен-сборку. Описывает сборку проекта без конфига. CX Codex +1 674установок embedded-stm32 Скилл embedded-stm32 для Claude Code и Codex задаёт правила разработки встроенного ПО на C/C++ под микроконтроллеры STM32 с библиотекой HAL. Включается при генерации кода в CubeMX, настройке DMA и обработке прерываний. CX Codex +1 132установок network-troubleshooting Скилл network-troubleshooting для Claude Code разбирает сетевые сбои в командах и сервисах. Запускается при ошибках DNS, TLS, прокси, соединения или тайм-аутах реестра пакетов. CX Codex +1 131установок readme-best-practices Скилл readme-best-practices для Claude Code помогает писать и проверять README проектов. Он подключается при создании файла, переработке существующего README или оценке его качества. CX Codex +1 121установок security-devsecops Скилл security-devsecops для Claude Code и Codex направляет разработку по практикам DevSecOps и AppSec. Включается при работе с секретами, базой данных, аутентификацией или настройке CI/CD. CX Codex +1 117установок

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

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