Clean Codeのロゴ

Clean Code

コミュニティ
alpham8
clean-code

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

概要

公開者alpham8
リポジトリagentic-webdev
スキル名clean-code
スター
4
フォーク
0
同梱ファイル
6
ライセンスMIT
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 6個の同梱ファイル

    モデルが作業中に読み取れるスクリプト、テンプレート、参考資料です。ファイルは読み取り専用で、実行されることはありません。

  • オープンソース

    alpham8がGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキルClean CodeをTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/alpham8/agentic-webdev/tree/master/skills/wondelai/clean-code
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。
2

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをそのAIエージェントのスキルディレクトリにコピーしてください。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/alpham8/agentic-webdev.git /tmp/agentic-webdev
mkdir -p .claude/skills
cp -r /tmp/agentic-webdev/skills/wondelai/clean-code .claude/skills/clean-code
コピー後、新しいスキルを読み込むためにClaude Codeを再起動してください。

TypingMindで使用

TypingMindのチャットでClean Codeを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあると、モデルが自動的にClean Codeを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Clean Codeは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、未使用のスキルにはコストがかかりません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込む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 improvements.

Core Principle

Code is read far more often than it is written. Optimize for the reader. Every naming choice, function boundary, and formatting decision either adds clarity or adds cost. The ratio of time spent reading code to writing code is well over 10:1. Making code easier to read makes it easier to write, easier to debug, and easier to extend.

The foundation: Clean code is not about following rules mechanically -- it is about caring for the craft. A clean codebase reads like well-written prose: names reveal intent, functions tell a story one step at a time, and there are no surprises lurking in dark corners. The Boy Scout Rule applies: always leave the code cleaner than you found it.

Scoring

Goal: 10/10. When reviewing or writing code, rate it 0-10 based on adherence to the principles below. A 10/10 means full alignment with all guidelines; lower scores indicate gaps to address. Always provide the current score and 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 exist but may lack edge cases.
  • 5-6: Mixed quality -- some good patterns alongside unclear names, duplicated logic, or inconsistent error handling.
  • 3-4: Significant readability issues -- long functions doing multiple things, misleading names, poor or missing tests.
  • 1-2: Code works but is 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 poorly chosen name forces every reader to reverse-engineer the author's intent.

Key insights:

  • Names should answer why it exists, what it does, and how it is used
  • Avoid single-letter variables except for loop counters in tiny scopes
  • Avoid encodings, prefixes, and type information in names (no Hungarian notation)
  • Class names should be nouns or noun phrases; method names should be verbs or verb phrases
  • Use one word per concept consistently: don't mix fetch, retrieve, and get
  • Longer scopes demand longer, more descriptive names
  • Don't be afraid to rename -- IDEs make it trivial

Code applications:

ContextPatternExample
VariablesIntention-revealing nameelapsedTimeInDays not d or elapsed
BooleansPredicate phrasingisActive, hasPermission, canEdit
FunctionsVerb + noun describing actioncalculateMonthlyRevenue() not calc()
ClassesNoun describing responsibilityInvoiceGenerator not InvoiceManager
ConstantsSearchable, all-caps with contextMAX_RETRY_ATTEMPTS = 3 not 3 inline
CollectionsPlural nouns or descriptive phrasesactiveUsers not list or data

See: references/naming-conventions.md

2. Functions

Core concept: Functions should be small, do one thing, and do it well. The ideal function is 4-6 lines long, takes zero to two arguments, and operates at a single level of abstraction.

Why it works: Small functions are easy to name, easy to understand, easy to test, and easy to reuse. When a function does one thing, its name can describe exactly what it does, eliminating the need to read the body. Long functions hide bugs, resist testing, and accumulate responsibilities over time.

Key insights:

  • Functions should do one thing, do it well, and do it only
  • The Step-Down Rule: code should read like a top-down narrative, each function calling the next level of abstraction
  • Ideal argument count is zero (niladic), then one (monadic), then two (dyadic); three or more (polyadic) requires justification
  • Flag arguments (booleans) are a code smell -- they mean the function does two things
  • Command-Query Separation: a function should either change state or return a value, never both
  • Extract till you drop: if you can extract a named function from a block, do it
  • Functions should have no side effects -- no hidden changes to state

Code applications:

ContextPatternExample
Long functionExtract into named stepsvalidateInput(); transformData(); saveRecord();
Flag argumentSplit into two functionsrenderForPrint() and renderForScreen() not render(isPrint)
Deep nestingExtract inner blocksMove nested if/for bodies into named functions
Multiple returnsGuard clauses at topEarly return for error cases, single happy path
Many argumentsIntroduce parameter objectnew DateRange(start, end) not report(start, end, format, locale)
Side effectsMake effects explicitRename checkPassword() to checkPasswordAndInitSession() or separate

See: references/functions-and-methods.md

3. Comments and Formatting

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

Why it works: Comments rot. Code changes but comments often do not, creating misleading documentation that is worse than no documentation. Clean formatting -- consistent indentation, vertical spacing between concepts, and logical ordering -- lets developers scan code the way readers scan a newspaper: headlines first, details on demand.

Key insights:

  • The best comment is the code itself -- extract a well-named function instead of writing a comment
  • Legal comments (copyright headers) and TODO comments are acceptable
  • Javadoc for public APIs is valuable; Javadoc for internal code is noise
  • Commented-out code should be deleted -- version control remembers it
  • Journal comments (changelog in the file) are obsolete -- use git log
  • Vertical openness: separate concepts with blank lines
  • Vertical density: related code should appear close together
  • Variables should be declared close to their usage
  • Instance variables should be declared at the top of the class

Code applications:

ContextPatternExample
Explaining "what"Replace with better nameRename // check if eligible to isEligible()
Explaining "why"Keep as comment// RFC 7231 requires this header for proxies
Commented-out codeDelete itTrust version control to remember
File organizationNewspaper metaphorHigh-level functions at top, details below
Related codeGroup verticallyKeep caller near callee in the same file
Team formattingAgree on rules onceUse automated formatters (Prettier, Black, gofmt)

See: references/comments-formatting.md

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 force the caller to check immediately, cluttering the happy path with error-checking logic. Exceptions let you separate the happy path from error handling, making both easier to read. Returning null forces every caller to add null checks, and a single missing check produces a NullPointerException far from the source.

Key insights:

  • Write your try-catch block first -- it defines a transaction boundary
  • Use unchecked exceptions -- checked exceptions violate the Open/Closed Principle
  • Create informative exception messages: include the operation that failed and the context
  • Define exception classes in terms of the caller's needs, not the type of failure
  • The Special Case Pattern: return a special-case object instead of null (e.g., empty list, guest user)
  • Don't return null -- return empty collections, Optional, or throw
  • Don't pass null -- no reasonable behavior exists for null arguments
  • Wrap third-party APIs to translate their exceptions into your domain

Code applications:

ContextPatternExample
Null returnsReturn empty collection or Optionalreturn Collections.emptyList() not return null
Error codesReplace with exceptionsthrow new InsufficientFundsException(balance, amount)
Third-party APIsWrap with adapterPortfolioService wraps vendor API, translates exceptions
Null argumentsFail fast with assertionObjects.requireNonNull(user, "user must not be null")
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

5. Unit Testing

Core concept: Tests are first-class code. They must be clean, readable, and maintained 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 serve as executable documentation, showing exactly how the system is intended to behave. They provide a safety net for refactoring and a regression check for every change. Without tests, every modification is a potential bug. With dirty tests, every modification requires fighting through incomprehensible test code.

Key insights:

  • The Three Laws of TDD: (1) write a failing test first, (2) write only enough test to fail, (3) write only enough code to pass
  • One concept per test -- not necessarily one assert, but one logical assertion
  • Tests should be readable: use the Build-Operate-Check pattern (Arrange-Act-Assert)
  • F.I.R.S.T. principles: Fast, Independent, Repeatable, Self-validating, Timely
  • Test names should describe the scenario and expected behavior
  • Test code deserves the same refactoring attention as production code
  • Domain-specific testing language: build helper functions that read like a DSL

Code applications:

ContextPatternExample
Test structureArrange-Act-AssertSetup, execute, verify -- clearly separated
Test namingScenario + expected behaviorshouldRejectExpiredToken not test1
Shared setupExtract builder/factoryaUser().withRole(ADMIN).build()
Multiple scenariosParameterized testsOne test method, multiple input/output pairs
Flaky testsRemove external dependenciesMock time, network, file system
Test readabilityDomain-specific helpersassertThatInvoice(inv).isPaidInFull()

See: references/testing-principles.md

6. Code Smells and Heuristics

Core concept: Code smells are surface indicators of deeper design problems. Learn to recognize them quickly and apply targeted refactorings. Not every smell requires immediate action, but ignoring them accumulates technical debt.

Why it works: Smells are heuristics -- they point toward likely problems without requiring deep analysis. A developer who can quickly identify "this function has too many arguments" or "this class has feature envy" can make targeted improvements instead of vague "cleanup" efforts.

Key insights:

  • Comments: inappropriate information, obsolete comments, redundant comments that repeat the code
  • Functions: too many arguments, output arguments, flag arguments, dead functions never called
  • General: obvious duplication, code at wrong level of abstraction, feature envy (method uses another class more than its own), magic numbers
  • Names: names at wrong abstraction level, names that don't describe side effects, ambiguous short names
  • Tests: insufficient tests, skipped tests, untested boundary conditions, no failure-path tests
  • Apply the Boy Scout Rule: leave code cleaner than you found it
  • Refactor in small, tested steps -- never refactor and add features simultaneously

Code applications:

ContextPatternExample
DuplicationExtract shared logicCommon validation → validateEmail() helper
Long parameter listIntroduce parameter objectSearchCriteria groups related params
Feature envyMove method to 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

Common Mistakes

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

Quick Diagnostic

Audit any codebase:

QuestionIf NoAction
Can you understand each function without reading its body?Names don't reveal intentRename functions to describe what they do
Are all functions under 20 lines?Functions do too many thingsExtract sub-operations into named helpers
Are there zero commented-out code blocks?Dead code creating confusionDelete them -- version control has history
Is error handling separate from business logic?Try-catch blocks cluttering main flowExtract error handling; use exceptions not return codes
Does every class have a single responsibility?Classes accumulate unrelated dutiesSplit into focused classes with clear names
Is there a test for every public method?No safety net for changesAdd tests before making further changes
Are test names descriptive of behavior?Tests are hard to understand when they failRename to shouldDoXWhenY pattern
Is duplication below 3 occurrences?Copy-paste spreading bugsExtract into shared function or module
Are magic numbers replaced with named constants?Intent is hidden behind raw valuesExtract constants with descriptive names
Can you run all tests in under 10 seconds?Slow tests discourage running themMock external deps, split integration tests

Reference Files

  • naming-conventions.md: Intention-revealing names, avoiding disinformation, class vs. method naming, before/after examples
  • functions-and-methods.md: Small functions, argument counts, command-query separation, the step-down rule, side effects
  • comments-formatting.md: Good vs. bad comments, the newspaper metaphor, vertical formatting, team rules
  • error-handling.md: Exceptions over return codes, null handling, Special Case pattern, wrapping third-party APIs
  • testing-principles.md: TDD laws, F.I.R.S.T. principles, clean test patterns, test readability
  • code-smells.md: Comprehensive smell catalog organized by category, with targeted refactorings

Further Reading

This skill is based on Robert C. Martin's seminal guide to software craftsmanship:

About the Author

Robert C. Martin ("Uncle Bob") is a software engineer, instructor, and author who has been programming since 1970. He is a co-author of the Agile Manifesto and the founder of Uncle Bob Consulting LLC and Clean Coders. His books -- Clean Code (2008), The Clean Coder (2011), Clean Architecture (2017), and Clean Agile (2019) -- have shaped how an entire generation of developers think about code quality, professional responsibility, and software design. Martin is known for his uncompromising stance that developers are professionals who must take responsibility for the quality of their work, and that the only way to go fast is to go well.

同梱ファイル

スキルが読み込まれている間、モデルは必要に応じてこれらを読み取ります。読み取り可能なファイルとして提供され、実行されることはありません。

よくある質問

AIスキル「Clean Code」では何ができますか?

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

TypingMindでClean Codeを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Clean Codeはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにClean Codeをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/alpham8/agentic-webdev/tree/master/skills/wondelai/clean-codeを貼り付けてください。TypingMindがSKILL.mdを読み込み、関連ファイルをまとめて、チャットごとに有効にできるスキルとしてインストールします。

Clean Codeを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストが合致したときにこのスキルを読み込めます。

Clean Codeは何個のAIモデルで使えますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもClean Codeを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Clean Code」は無料ですか?

はい。alpham8がGitHubでMITライセンスの下で公開しています。支払いが必要なのは、利用したトークンに対する、ご自身が契約するAIプロバイダーへの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇