Source profileQuality 87/100

wondelai/skills/clean-code/SKILL.md

clean-code

Write readable, maintainable code through disciplined naming, small functions, and clean error handling. Use when the user mentions "clean up this code", "this function is too long", "code smells", "naming conventions", "boy scout rule", "single responsibility", or "unit test quality". Also trigger when reviewing a pull request for readability, untangling a messy function, debating comment styles, or improving error-handling patterns. Covers SRP, comment discipline, formatting, and unit testing.

Source repository stars
1,835
Declared platforms
0
Static risk flags
0
Last source update
2026-07-22
Source checked
2026-08-04

Decision brief

What it does—and where it fits

A disciplined approach to writing code that communicates intent, minimizes surprises, and welcomes change. Apply these principles when writing new code, reviewing pull requests, refactoring legacy systems, or advising on code quality.

Best for

  • Use when the user mentions "clean up this code", "this function is too long", "code smells", "naming conventions", "boy scout rule", "single responsibility", or "unit test quality".

Not for

  • Tasks that require unconfirmed production actions or broad system permissions.
  • Environments where the pinned source and install steps cannot be inspected.

Compatibility matrix

Platform support, with evidence labels

PlatformStatusEvidenceWhat to check
CodexNot declaredNo explicit evidencePortability before use
Claude CodeNot declaredNo explicit evidencePortability before use
CursorNot declaredNo explicit evidencePortability before use
Gemini CLINot declaredNo explicit evidencePortability before use
Open the compatibility checker

Installation

Inspect first. Install second.

The source command is displayed only when detected. A safe inspection prompt is always available so your agent can explain every action before execution.

Source-detected install commandSource
npx skills add https://github.com/wondelai/skills --skill "clean-code"
Safe inspection promptEditorial

Inspect the Agent Skill "clean-code" from https://github.com/wondelai/skills/blob/dd37ee506ff558e939b3d421557987cced49b866/clean-code/SKILL.md at commit dd37ee506ff558e939b3d421557987cced49b866. List every install step, command, network request, credential, file read/write, external action, and rollback step. Explain whether it fits my task. Do not install or execute anything until I approve.

Workflow

What the source asks the agent to do

  1. 01

    Core Principle

    Code is read far more often than it is written — optimize for the reader. The read-to-write ratio is well over 10:1, so every naming choice, function boundary, and formatting decision either adds clarity or adds cost. Clean code reads like well-written prose: names reveal intent…

    Code is read far more often than it is written — optimize for the reader. The read-to-write ratio is well over 10:1, so every naming choice, function boundary, and formatting decision either adds clarity or adds cost. C…
  2. 02

    Scoring

    Goal: 10/10. Rate any code 0-10 against the principles below. Report the current score and the specific improvements needed to reach 10/10.

    9-10: Names reveal intent, functions are small and focused, error handling is consistent, tests are clean and comprehensive7-8: Mostly clean with minor naming ambiguities or a few long functions; tests may lack edge cases5-6: Mixed — good patterns alongside unclear names, duplicated logic, or inconsistent error handling
  3. 03

    The Clean Code Framework

    Six disciplines for writing code that communicates clearly and adapts to change:

    A name should answer why it exists, what it does, and how it is usedNo encodings, prefixes, or type information (no Hungarian notation); single letters only for tiny-scope loop countersClasses are nouns; methods are verbs
  4. 04

    1. Meaningful Names

    Core concept: Names should reveal intent, avoid disinformation, and make the code read like prose. If a name requires a comment to explain it, the name is wrong.

    A name should answer why it exists, what it does, and how it is usedNo encodings, prefixes, or type information (no Hungarian notation); single letters only for tiny-scope loop countersClasses are nouns; methods are verbs
  5. 05

    2. Functions

    Core concept: Functions should be small, do one thing, and do it well — ideally 4-6 lines, zero to two arguments, one level of abstraction.

    Step-Down Rule: code reads top-down, each function calling the next level of abstractionArgument count: zero best, one fine, two acceptable, three+ requires justificationFlag arguments are a smell — the function does two things; split it

Permission review

Static risk signals and limitations

No configured static risk pattern was detected

This is not proof of safety. Runtime behavior, indirect dependencies, and hidden external systems are outside the static scan.

Evidence record

Why each signal appears

EvidenceSourceComputedTestedEditorial
SignalValueEvidence typeMeaning
Quality score87/100ComputedDocumentation, specificity, maintenance, and trust rules
Repository stars1,835SourceRepository attention, not individual Skill quality
Compatibility0 platformsSourceDeclared in the catalog source record
Usage guideautomated source guideEditorialGenerated or reviewed according to the visible evidence level

Pinned source

Provenance and original SKILL.md

Repository
wondelai/skills
Skill path
clean-code/SKILL.md
Commit
dd37ee506ff558e939b3d421557987cced49b866
License
MIT
Collected
2026-08-04
Default branch
main
View the original SKILL.md

Clean Code Framework

A disciplined approach to writing code that communicates intent, minimizes surprises, and welcomes change. Apply these principles when writing new code, reviewing pull requests, refactoring legacy systems, or advising on code quality.

Core Principle

Code is read far more often than it is written — optimize for the reader. The read-to-write ratio is well over 10:1, so every naming choice, function boundary, and formatting decision either adds clarity or adds cost. Clean code reads like well-written prose: names reveal intent, functions tell a story one step at a time, and the Boy Scout Rule applies — always leave the code cleaner than you found it.

Scoring

Goal: 10/10. Rate any code 0-10 against the principles below. Report the current score and the specific improvements needed to reach 10/10.

  • 9-10: Names reveal intent, functions are small and focused, error handling is consistent, tests are clean and comprehensive
  • 7-8: Mostly clean with minor naming ambiguities or a few long functions; tests may lack edge cases
  • 5-6: Mixed — good patterns alongside unclear names, duplicated logic, or inconsistent error handling
  • 3-4: Long multi-purpose functions, misleading names, poor or missing tests
  • 1-2: Nearly unreadable — magic numbers, cryptic abbreviations, no structure, no tests

The Clean Code Framework

Six disciplines for writing code that communicates clearly and adapts to change:

1. Meaningful Names

Core concept: Names should reveal intent, avoid disinformation, and make the code read like prose. If a name requires a comment to explain it, the name is wrong.

Why it works: Names are the most pervasive form of documentation — a well-chosen name eliminates the need to read the implementation; a poor one forces every reader to reverse-engineer intent.

Key insights:

  • A name should answer why it exists, what it does, and how it is used
  • No encodings, prefixes, or type information (no Hungarian notation); single letters only for tiny-scope loop counters
  • Classes are nouns; methods are verbs
  • One word per concept: don't mix fetch, retrieve, and get
  • Longer scope demands a longer, more descriptive name
  • Rename freely — IDEs make it trivial

Code applications:

ContextPatternExample
VariablesIntention-revealingelapsedTimeInDays not d
BooleansPredicate phrasingisActive, hasPermission, canEdit
FunctionsVerb + nouncalculateMonthlyRevenue() not calc()
ClassesNoun naming the responsibilityInvoiceGenerator not InvoiceManager

See references/naming-conventions.md when renaming or reviewing names — per-language conventions, pronounceable/searchable tables, and before/after examples.

2. Functions

Core concept: Functions should be small, do one thing, and do it well — ideally 4-6 lines, zero to two arguments, one level of abstraction.

Why it works: Small single-purpose functions are easy to name, understand, test, and reuse; long functions hide bugs, resist testing, and accumulate responsibilities.

Key insights:

  • Step-Down Rule: code reads top-down, each function calling the next level of abstraction
  • Argument count: zero best, one fine, two acceptable, three+ requires justification
  • Flag arguments are a smell — the function does two things; split it
  • Command-Query Separation: change state or return a value, never both
  • Extract till you drop: if you can pull out a named function, do it
  • No hidden side effects — the name must tell the whole truth

Code applications:

ContextPatternExample
Long functionExtract named stepsvalidateInput(); transformData(); saveRecord();
Flag argumentSplit into two functionsrenderForPrint() / renderForScreen() not render(isPrint)
Error casesGuard clauses at topEarly return for errors, single happy path
Many argumentsIntroduce parameter objectnew DateRange(start, end) not report(start, end, format, locale)
Side effectsMake effects explicitcheckPassword() that starts a session → rename or separate

See references/functions-and-methods.md when splitting a long function — argument-count rules, command-query separation, and step-down worked examples.

3. Comments and Formatting

Core concept: A comment is a failure to express yourself in code. When comments are necessary, they explain why, never what. Formatting creates the visual structure that makes code scannable.

Why it works: Comments rot — code changes but comments often don't, creating documentation worse than none. Clean formatting lets developers scan code like a newspaper: headlines first, details on demand.

Key insights:

  • The best comment is a well-named extracted function
  • Acceptable: legal headers, TODOs, public API docs, genuine "why" explanations
  • Commented-out code and journal comments: delete — version control remembers
  • Vertical openness between concepts; vertical density within them; declare variables near usage
  • Newspaper metaphor: high-level functions at the top of the file, details below

Code applications:

ContextPatternExample
Explaining "what"Replace with better name// check if eligibleisEligible()
Explaining "why"Keep as comment// RFC 7231 requires this header for proxies
Commented-out codeDelete itTrust version control
Team formattingDecide once, automatePrettier, Black, gofmt

See references/comments-formatting.md when deciding whether a comment earns its place — good-vs-bad comment catalog and vertical-formatting rules.

4. Error Handling

Core concept: Error handling is a separate concern from business logic. Use exceptions rather than return codes, provide context with every exception, and never return or pass null.

Why it works: Return codes clutter the happy path with checks; exceptions separate the two cleanly. Returning null forces null checks on every caller, and one missing check crashes far from the source.

Key insights:

  • Write the try-catch first — it defines a transaction boundary
  • Prefer unchecked exceptions — checked ones violate the Open/Closed Principle
  • Define exception classes by the caller's needs, not the failure type
  • Don't return null (use empty collections, Optional, or throw); don't pass null either
  • Special Case / Null Object pattern: return an object with default behavior instead of null

Code applications:

ContextPatternExample
Null returnsEmpty collection or Optionalreturn Collections.emptyList() not return null
Error codesReplace with exceptionsthrow new InsufficientFundsException(balance, amount)
Third-party APIsWrap with adapterPortfolioService wraps the vendor API, translates its exceptions
Special casesNull Object patternGuestUser with default behavior instead of null checks
Context in errorsInclude operation + state"Failed to save invoice #1234 for customer 'Acme'"

See references/error-handling.md when designing exception or null strategy — Special Case pattern and third-party-API wrapping examples.

5. Unit Testing

Core concept: Tests are first-class code, kept clean with the same discipline as production code. Dirty tests are worse than no tests — they become a liability that slows every change.

Why it works: Clean tests are executable documentation and a safety net for refactoring; dirty tests make every modification a fight through incomprehensible test code.

Key insights:

  • Three Laws of TDD: write a failing test first; only enough test to fail; only enough code to pass
  • One concept per test — one logical assertion, not necessarily one assert
  • F.I.R.S.T.: Fast, Independent, Repeatable, Self-validating, Timely
  • Build a domain-specific testing language: helpers that read like a DSL
  • Refactor test code as readily as production code

Code applications:

ContextPatternExample
Test structureArrange-Act-AssertSetup, execute, verify — clearly separated
Test namingScenario + expected behaviorshouldRejectExpiredToken not test1
Shared setupBuilder/factory helpersaUser().withRole(ADMIN).build()
Flaky testsRemove external dependenciesMock time, network, file system

See references/testing-principles.md when writing or cleaning tests — TDD laws, F.I.R.S.T. expanded, and clean-test patterns.

6. Code Smells and Heuristics

Core concept: Smells are surface indicators of deeper design problems — learn to recognize them quickly and apply targeted refactorings instead of vague "cleanup".

Why it works: Smells are heuristics that point toward likely problems without deep analysis, turning code review instinct into specific, repeatable moves.

Key insights:

  • Function smells: too many arguments, output arguments, flag arguments, dead functions
  • General smells: duplication, wrong level of abstraction, feature envy, magic numbers
  • Test smells: insufficient coverage, skipped tests, untested boundary conditions and failure paths
  • Refactor in small, tested steps — never refactor and add features simultaneously
  • Boy Scout Rule: leave the code cleaner than you found it

Code applications:

ContextPatternExample
DuplicationExtract shared logicCommon validation → validateEmail() helper
Feature envyMove method to the data's classorder.calculateTotal() not calculator.total(order)
Dead codeDelete itRemove unused functions, unreachable branches
Magic numbersNamed constantsMAX_LOGIN_ATTEMPTS = 5 not bare 5
Shotgun surgeryConsolidate related changesGroup scattered logic into a single module

See references/code-smells.md when a smell is hard to name — the full catalog by category, each paired with its targeted refactoring.

Common Mistakes

MistakeWhy It FailsFix
Abbreviating namesSaves seconds writing, costs hours readingFull descriptive names; IDEs autocomplete
"Clever" one-linersImpressive to write, impossible to debugExpand into readable named steps
Comments instead of refactoringComments rot; code is the truthExtract a well-named function instead
Catching generic exceptionsSwallows bugs along with expected errorsCatch specific exceptions; let the rest propagate
No tests for error pathsHappy path works, edge cases crashTest every branch, boundary, and failure mode
Premature optimizationObscures intent for marginal gainsClean first; optimize measured bottlenecks
God classesOne 2000-line class does everythingApply SRP — split by responsibility
Refactoring without testsNo safety net for regressionsWrite characterization tests first
Inconsistent conventionsEvery file feels like a different codebaseAgree on style; enforce with linters and formatters
Returning null everywhereNull checks spread like a virusOptional, empty collections, or Null Object

Quick Diagnostic

QuestionIf NoAction
Can you understand each function without reading its body?Names don't reveal intentRename to describe what it does
Are all functions under 20 lines?Functions do too many thingsExtract sub-operations into named helpers
Zero commented-out code blocks?Dead code creating confusionDelete — version control has history
Is error handling separate from business logic?Try-catch clutters the main flowExtract handlers; exceptions over return codes
Does every class have a single responsibility?Classes accumulate unrelated dutiesSplit into focused, well-named classes
Is there a test for every public method?No safety net for changesAdd tests before changing further
Are test names descriptive of behavior?Failures are hard to interpretRename to shouldDoXWhenY
Is duplication below 3 occurrences?Copy-paste spreading bugsExtract shared logic (§6)
Are magic numbers named constants?Intent hidden behind raw valuesName the constant (§6)
Do all tests run in under 10 seconds?Slow tests don't get runMock external deps; split integration tests

Further Reading

Based on Robert C. Martin's seminal guide to software craftsmanship:

About the Author

Robert C. Martin ("Uncle Bob") has been programming since 1970, co-authored the Agile Manifesto, and founded Uncle Bob Consulting and Clean Coders. His books — Clean Code, The Clean Coder, Clean Architecture, and Clean Agile — shaped how a generation of developers think about code quality, and his core stance is that the only way to go fast is to go well.

Alternatives

Compare before choosing

Computed 954,922

dotnet/skills

grade-tests

Grades a specified set of test methods individually and produces a concise table mapping each test (fully-qualified name) to a letter grade (A–F), a score band, and a one-line note — designed to be posted as a PR comment. Use when the caller wants per-test feedback on a curated list of methods (for example, the new or modified tests in a pull request), not a suite-wide audit. Polyglot: .NET, Python, TS/JS, Java, Go, Ruby, Rust, Swift, Kotlin, PowerShell, C++. Input is a list of test methods (or

Computed 9447,525

prisma/prisma

contrib-pr

Open a high-quality external contributor PR against prisma-next. Use when the user is an outside contributor (not a Prisma maintainer) and wants to submit a change as a pull request from a fork. Encodes the contribution flow from CONTRIBUTING.md so the resulting PR passes review on the first round.

Computed 94195

PramodDutta/qaskills

Code Review Excellence

Master code review best practices with constructive feedback patterns, quality assurance standards, review checklists, security considerations, and collaborative improvement techniques for high-quality software delivery.

Computed 93398

tobihagemann/turbo

review-code

Review code for bugs, security vulnerabilities, API misuse, consistency issues, simplicity problems, or test coverage gaps by running internal reviews and a peer review in parallel and returning combined findings. Single-concern with a type argument, or full review with no argument. Use when the user asks to "review my code", "full code review", "review my changes", "check for bugs", "scan for bugs", "review correctness", "security audit", "find vulnerabilities", "review security", "check API us