opencode-skills-collection 4.0.0 → 4.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundled-skills/.antigravity-install-manifest.json +24 -1
- package/bundled-skills/007/SKILL.md +2 -2
- package/bundled-skills/10-andruia-skill-smith/SKILL.md +1 -1
- package/bundled-skills/agent-squad/SKILL.md +5 -0
- package/bundled-skills/agent-squad/alex/SKILL.md +3 -0
- package/bundled-skills/agent-squad/aria/SKILL.md +3 -0
- package/bundled-skills/agent-squad/dep/SKILL.md +3 -0
- package/bundled-skills/agent-squad/luna/SKILL.md +4 -1
- package/bundled-skills/agent-squad/mason/SKILL.md +3 -0
- package/bundled-skills/agent-squad/max/SKILL.md +3 -0
- package/bundled-skills/agent-squad/quinn/SKILL.md +3 -0
- package/bundled-skills/agent-squad/rex/SKILL.md +3 -0
- package/bundled-skills/angular/metadata.json +1 -1
- package/bundled-skills/angular-best-practices/metadata.json +1 -1
- package/bundled-skills/angular-state-management/metadata.json +1 -1
- package/bundled-skills/angular-ui-patterns/metadata.json +1 -1
- package/bundled-skills/antigravity-skill-orchestrator/SKILL.md +2 -2
- package/bundled-skills/apify-actor-development/SKILL.md +2 -2
- package/bundled-skills/apple-container/SKILL.md +165 -0
- package/bundled-skills/apple-container/references/commands.md +1593 -0
- package/bundled-skills/apple-container/references/concepts.md +294 -0
- package/bundled-skills/apple-container/references/configuration.md +499 -0
- package/bundled-skills/apple-container/references/workflows.md +498 -0
- package/bundled-skills/ask-copilot/SKILL.md +112 -0
- package/bundled-skills/auto-research/SKILL.md +126 -0
- package/bundled-skills/brooks-lint/SKILL.md +1 -1
- package/bundled-skills/browser-harness/references/install.md +3 -1
- package/bundled-skills/chrome-extension-developer/SKILL.md +1 -1
- package/bundled-skills/clean-code-guard/SKILL.md +184 -0
- package/bundled-skills/clean-code-guard/references/ai-failure-modes.md +345 -0
- package/bundled-skills/clean-code-guard/references/comments-and-formatting.md +115 -0
- package/bundled-skills/clean-code-guard/references/dry-kiss-yagni.md +133 -0
- package/bundled-skills/clean-code-guard/references/naming-and-functions.md +187 -0
- package/bundled-skills/clean-code-guard/references/review-checklist.md +150 -0
- package/bundled-skills/clean-code-guard/references/solid.md +280 -0
- package/bundled-skills/clean-code-guard/references/sources.md +47 -0
- package/bundled-skills/cloudflare-security-audit/SKILL.md +137 -0
- package/bundled-skills/cloudflare-security-audit/references/AI-AND-LLM.md +67 -0
- package/bundled-skills/cloudflare-security-audit/references/ATTACK-CLASSES.md +116 -0
- package/bundled-skills/cloudflare-security-audit/references/CLIENT-SIDE.md +67 -0
- package/bundled-skills/cloudflare-security-audit/references/HUNTING.md +110 -0
- package/bundled-skills/cloudflare-security-audit/references/MEMORY-SAFETY-AND-BINARY.md +58 -0
- package/bundled-skills/cloudflare-security-audit/references/RECONNAISSANCE.md +46 -0
- package/bundled-skills/cloudflare-security-audit/references/VALIDATION-AND-REPORTING.md +109 -0
- package/bundled-skills/cloudflare-security-audit/references/WEB-PROTOCOL-AND-AUTH.md +85 -0
- package/bundled-skills/cloudflare-security-audit/resources/report-schema.json +210 -0
- package/bundled-skills/comfyui-gateway/references/troubleshooting.md +1 -1
- package/bundled-skills/commit/SKILL.md +2 -1
- package/bundled-skills/deepapi/SKILL.md +6 -6
- package/bundled-skills/docs/README.md +1 -1
- package/bundled-skills/docs/contributors/quality-bar.md +1 -1
- package/bundled-skills/docs/contributors/security-guardrails.md +1 -1
- package/bundled-skills/docs/integrations/jetski-cortex.md +5 -5
- package/bundled-skills/docs/integrations/jetski-gemini-loader/README.md +3 -3
- package/bundled-skills/docs/maintainers/ci-drift-fix.md +7 -5
- package/bundled-skills/docs/maintainers/merge-batch.md +24 -7
- package/bundled-skills/docs/maintainers/pr-autonomy.md +89 -0
- package/bundled-skills/docs/maintainers/release-notes-7.2.0.md +1 -1
- package/bundled-skills/docs/maintainers/release-process.md +9 -9
- package/bundled-skills/docs/maintainers/repo-growth-seo.md +5 -5
- package/bundled-skills/docs/maintainers/skills-date-tracking.md +1 -1
- package/bundled-skills/docs/maintainers/skills-update-guide.md +2 -2
- package/bundled-skills/docs/users/{antigravity-awesome-skills-vs-awesome-claude-skills.md → agentic-awesome-skills-vs-awesome-claude-skills.md} +5 -5
- package/bundled-skills/docs/users/ai-agent-skills.md +4 -4
- package/bundled-skills/docs/users/best-claude-code-skills-github.md +3 -3
- package/bundled-skills/docs/users/best-cursor-skills-github.md +3 -3
- package/bundled-skills/docs/users/bundles.md +56 -57
- package/bundled-skills/docs/users/claude-code-skills.md +6 -6
- package/bundled-skills/docs/users/codex-cli-skills.md +5 -5
- package/bundled-skills/docs/users/cursor-skills.md +3 -3
- package/bundled-skills/docs/users/faq.md +27 -15
- package/bundled-skills/docs/users/gemini-cli-skills.md +4 -4
- package/bundled-skills/docs/users/getting-started.md +22 -12
- package/bundled-skills/docs/users/kiro-integration.md +7 -7
- package/bundled-skills/docs/users/plugins.md +8 -9
- package/bundled-skills/docs/users/security-skills.md +1 -1
- package/bundled-skills/docs/users/skills-vs-mcp-tools.md +1 -1
- package/bundled-skills/docs/users/specialized-plugin-roadmap.md +3 -4
- package/bundled-skills/docs/users/usage.md +9 -9
- package/bundled-skills/docs/users/visual-guide.md +7 -7
- package/bundled-skills/docs/users/windows-truncation-recovery.md +1 -1
- package/bundled-skills/docs/users/workflows.md +1 -1
- package/bundled-skills/docs/vietnamese/BUNDLES.vi.md +1 -1
- package/bundled-skills/docs/vietnamese/FAQ.vi.md +15 -8
- package/bundled-skills/docs/vietnamese/GETTING_STARTED.vi.md +12 -5
- package/bundled-skills/docs/vietnamese/QUALITY_BAR.vi.md +1 -1
- package/bundled-skills/docs/vietnamese/README.vi.md +21 -17
- package/bundled-skills/docs/vietnamese/SECURITY_GUARDRAILS.vi.md +1 -1
- package/bundled-skills/docs/vietnamese/SKILLS_README.vi.md +2 -2
- package/bundled-skills/docs/vietnamese/TRANSLATION_PLAN.vi.md +1 -1
- package/bundled-skills/docs/vietnamese/VISUAL_GUIDE.vi.md +8 -8
- package/bundled-skills/docs-guard/SKILL.md +109 -0
- package/bundled-skills/docs-guard/references/code-samples.md +46 -0
- package/bundled-skills/docs-guard/references/docstrings.md +60 -0
- package/bundled-skills/docs-guard/references/review-checklist.md +45 -0
- package/bundled-skills/docs-guard/references/sources.md +22 -0
- package/bundled-skills/docs-guard/references/verification.md +51 -0
- package/bundled-skills/efficient-web-research/SKILL.md +4 -0
- package/bundled-skills/electron-development/SKILL.md +1 -1
- package/bundled-skills/event-staffing-compliance/SKILL.md +3 -0
- package/bundled-skills/event-staffing-ordering/SKILL.md +3 -0
- package/bundled-skills/feature-tracking/SKILL.md +222 -0
- package/bundled-skills/flutter-expert/SKILL.md +6 -1
- package/bundled-skills/flutter-expert/resources/implementation-playbook.md +214 -0
- package/bundled-skills/gemini-deep-research/README.md +246 -0
- package/bundled-skills/gemini-deep-research/SKILL.md +136 -0
- package/bundled-skills/gemini-deep-research/requirements.txt +2 -0
- package/bundled-skills/gemini-deep-research/scripts/research.py +692 -0
- package/bundled-skills/git-pushing/SKILL.md +21 -4
- package/bundled-skills/git-pushing/scripts/smart_commit.sh +206 -11
- package/bundled-skills/go-in-depth/scripts/workflow-script.js +4 -1
- package/bundled-skills/grok-build/SKILL.md +167 -0
- package/bundled-skills/grok-build/references/cli.md +99 -0
- package/bundled-skills/huggingface-tool-builder/references/find_models_by_paper.sh +1 -1
- package/bundled-skills/idea-autopsy/SKILL.md +147 -0
- package/bundled-skills/it-manager-hospital/README.md +1 -1
- package/bundled-skills/it-manager-pro/README.md +1 -1
- package/bundled-skills/itil-expert/README.md +1 -1
- package/bundled-skills/langgraph/SKILL.md +1 -1
- package/bundled-skills/linkedin-content-generator/SKILL.md +1 -1
- package/bundled-skills/lint-and-validate/scripts/lint_runner.py +23 -23
- package/bundled-skills/lint-and-validate/scripts/type_coverage.py +30 -30
- package/bundled-skills/logic-lens/SKILL.md +1 -1
- package/bundled-skills/lore/LICENSE +21 -0
- package/bundled-skills/lore/README.md +386 -0
- package/bundled-skills/lore/README.zh-CN.md +386 -0
- package/bundled-skills/lore/SKILL.md +453 -0
- package/bundled-skills/lore/WORKFLOWS.md +216 -0
- package/bundled-skills/lore/WORKFLOWS.zh-CN.md +216 -0
- package/bundled-skills/lore/references/audit-template.md +60 -0
- package/bundled-skills/lore/references/compatibility.md +228 -0
- package/bundled-skills/lore/references/config.md +125 -0
- package/bundled-skills/lore/references/entry-format.md +70 -0
- package/bundled-skills/lore/references/history-command.md +106 -0
- package/bundled-skills/lore/references/monorepo-detection.md +78 -0
- package/bundled-skills/lore/references/platform-mirrors.md +377 -0
- package/bundled-skills/lore/references/stale-new-markers.md +62 -0
- package/bundled-skills/lore/references/summary-template.md +98 -0
- package/bundled-skills/lore/scripts/README.md +54 -0
- package/bundled-skills/lore/scripts/README.zh-CN.md +54 -0
- package/bundled-skills/lore/scripts/find_duplicates.py +211 -0
- package/bundled-skills/lore/scripts/find_stale.py +116 -0
- package/bundled-skills/lore/scripts/history.py +527 -0
- package/bundled-skills/lore/scripts/id_hash.py +32 -0
- package/bundled-skills/lore/scripts/list_entries.py +183 -0
- package/bundled-skills/lovable-cleanup/SKILL.md +3 -3
- package/bundled-skills/makepad-splash/SKILL.md +1 -1
- package/bundled-skills/mmx-cli/SKILL.md +14 -1
- package/bundled-skills/monopoly/SKILL.md +5 -0
- package/bundled-skills/monopoly/patterns/SKILL.md +4 -0
- package/bundled-skills/monopoly/scale-benchmarks/SKILL.md +4 -0
- package/bundled-skills/monopoly/security-checklist/SKILL.md +4 -0
- package/bundled-skills/monopoly/tech-matrix/SKILL.md +4 -0
- package/bundled-skills/mtls-configuration/SKILL.md +1 -1
- package/bundled-skills/network-101/SKILL.md +4 -5
- package/bundled-skills/nika/SKILL.md +270 -0
- package/bundled-skills/not-a-vibe-coder/SKILL.md +4 -0
- package/bundled-skills/ontoly-software-graph/SKILL.md +160 -0
- package/bundled-skills/openclaw-github-repo-commander/SKILL.md +1 -1
- package/bundled-skills/pilot-protocol/SKILL.md +6 -3
- package/bundled-skills/postgres-readonly-queries/README.md +77 -0
- package/bundled-skills/postgres-readonly-queries/SKILL.md +152 -0
- package/bundled-skills/postgres-readonly-queries/connections.example.json +34 -0
- package/bundled-skills/postgres-readonly-queries/requirements.txt +1 -0
- package/bundled-skills/postgres-readonly-queries/scripts/query.py +262 -0
- package/bundled-skills/pptx-deck-creation/SKILL.md +275 -0
- package/bundled-skills/pptx-deck-creation/references/audit-checklist.md +156 -0
- package/bundled-skills/pptx-deck-creation/references/design-profiles.md +96 -0
- package/bundled-skills/pptx-deck-creation/references/python-snippets.md +150 -0
- package/bundled-skills/pptx-deck-creation/references/reference-deck-analysis.md +91 -0
- package/bundled-skills/pptx-deck-creation/references/visual-asset-adapters.md +158 -0
- package/bundled-skills/privilege-escalation-methods/SKILL.md +1 -1
- package/bundled-skills/product-decision-agent/SKILL.md +94 -0
- package/bundled-skills/product-decision-agent/agents/openai.yaml +7 -0
- package/bundled-skills/product-decision-agent/references/methodology-basis.md +232 -0
- package/bundled-skills/product-decision-agent/references/product-playbooks.md +813 -0
- package/bundled-skills/product-decision-agent/references/reasoning-engine.md +289 -0
- package/bundled-skills/product-decision-agent/references/response-examples.md +279 -0
- package/bundled-skills/product-decision-agent/scripts/quality_gate.py +221 -0
- package/bundled-skills/product-decision-agent/scripts/test_quality_gate.py +94 -0
- package/bundled-skills/pytest-skill/reference/playbook.md +358 -0
- package/bundled-skills/quit-sponsor/SKILL.md +96 -0
- package/bundled-skills/rclone-cli/references/providers/s3.md +1 -1
- package/bundled-skills/security-and-hardening/SKILL.md +1 -1
- package/bundled-skills/semgrep-rule-creator/SKILL.md +6 -6
- package/bundled-skills/skill-creator/README.md +3 -3
- package/bundled-skills/skill-creator/SKILL.md +8 -4
- package/bundled-skills/skill-creator/scripts/quick_validate.py +1 -1
- package/bundled-skills/sql-injection-testing/SKILL.md +4 -4
- package/bundled-skills/subagent-orchestrator/README.md +1 -1
- package/bundled-skills/super-code/bash/SKILL.md +3 -0
- package/bundled-skills/super-code/c/SKILL.md +3 -0
- package/bundled-skills/super-code/cpp/SKILL.md +3 -0
- package/bundled-skills/super-code/csharp/SKILL.md +3 -0
- package/bundled-skills/super-code/dart/SKILL.md +3 -0
- package/bundled-skills/super-code/elixir/SKILL.md +3 -0
- package/bundled-skills/super-code/go/SKILL.md +3 -0
- package/bundled-skills/super-code/java/SKILL.md +3 -0
- package/bundled-skills/super-code/kotlin/SKILL.md +3 -0
- package/bundled-skills/super-code/php/SKILL.md +3 -0
- package/bundled-skills/super-code/python/SKILL.md +3 -0
- package/bundled-skills/super-code/ruby/SKILL.md +3 -0
- package/bundled-skills/super-code/rust/SKILL.md +3 -0
- package/bundled-skills/super-code/scala/SKILL.md +3 -0
- package/bundled-skills/super-code/swift/SKILL.md +3 -0
- package/bundled-skills/super-code/typescript/SKILL.md +3 -0
- package/bundled-skills/telegram-bot-messaging/README.md +185 -0
- package/bundled-skills/telegram-bot-messaging/SKILL.md +101 -0
- package/bundled-skills/telegram-bot-messaging/scripts/telegram.sh +420 -0
- package/bundled-skills/test-guard/SKILL.md +132 -0
- package/bundled-skills/test-guard/references/jest.md +50 -0
- package/bundled-skills/test-guard/references/llm-app-testing.md +40 -0
- package/bundled-skills/test-guard/references/phpunit.md +56 -0
- package/bundled-skills/test-guard/references/pytest.md +65 -0
- package/bundled-skills/trading-ledger/SKILL.md +11 -3
- package/bundled-skills/uizze-ui-research/SKILL.md +93 -0
- package/bundled-skills/vibe-code-auditor/SKILL.md +1 -1
- package/bundled-skills/vibecode-production-qa-validator/SKILL.md +1 -1
- package/bundled-skills/videodb/scripts/ws_listener.py +29 -15
- package/bundled-skills/voice-ai-engine-development/README.md +1 -1
- package/bundled-skills/vulnerability-scanner/SKILL.md +1 -1
- package/bundled-skills/warehouse/SKILL.md +154 -0
- package/bundled-skills/woo-guard/SKILL.md +113 -0
- package/bundled-skills/woo-guard/references/checkout-and-money.md +64 -0
- package/bundled-skills/woo-guard/references/hpos-and-crud.md +87 -0
- package/bundled-skills/woo-guard/references/review-checklist.md +44 -0
- package/bundled-skills/woo-guard/references/sources.md +17 -0
- package/bundled-skills/wp-guard/SKILL.md +119 -0
- package/bundled-skills/wp-guard/references/i18n.md +88 -0
- package/bundled-skills/wp-guard/references/performance.md +70 -0
- package/bundled-skills/wp-guard/references/review-checklist.md +57 -0
- package/bundled-skills/wp-guard/references/security.md +100 -0
- package/bundled-skills/wp-guard/references/sources.md +27 -0
- package/bundled-skills/writing-skills/gotchas.md +1 -1
- package/bundled-skills/writing-skills/references/standards/metadata-standard.md +1 -1
- package/bundled-skills/x-twitter-scraper/SKILL.md +14 -32
- package/bundled-skills/xss-html-injection/SKILL.md +3 -3
- package/bundled-skills/youtube-seo-optimizer/SKILL.md +1 -1
- package/bundled-skills/youtube-summarizer/CHANGELOG.md +2 -2
- package/package.json +1 -1
- package/skills_index.json +273 -0
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
# AI Failure Modes — the unique value of this skill
|
|
2
|
+
|
|
3
|
+
This file catalogs 15 systematic ways LLMs produce bad code, each backed by published research or widely-documented engineering observations. Read this first if you are an AI agent applying this skill — these are the patterns most likely to enter your own output.
|
|
4
|
+
|
|
5
|
+
For each failure mode you get:
|
|
6
|
+
- **Pattern:** one-line description.
|
|
7
|
+
- **Source:** the research or post documenting it as systematic, not incidental.
|
|
8
|
+
- **Bad / Good:** short before-and-after.
|
|
9
|
+
- **Rule:** the imperative for your own self-check.
|
|
10
|
+
|
|
11
|
+
## Contents
|
|
12
|
+
|
|
13
|
+
- 1. Catch-all error handling that swallows failures
|
|
14
|
+
- 2. Defensive guards for impossible cases
|
|
15
|
+
- 3. Premature abstraction
|
|
16
|
+
- 4. Comment pollution
|
|
17
|
+
- 5. Code duplication instead of reuse
|
|
18
|
+
- 6. Hallucinated APIs and packages
|
|
19
|
+
- 7. Generic, intent-less naming
|
|
20
|
+
- 8. Long functions doing many things
|
|
21
|
+
- 9. Parameter explosion
|
|
22
|
+
- 10. Inconsistency with surrounding code
|
|
23
|
+
- 11. Dead code, unused imports, half-implementations
|
|
24
|
+
- 12. Declares success with mock fallbacks in production code
|
|
25
|
+
- 13. Plausible-but-wrong code
|
|
26
|
+
- 14. YAGNI violations through speculative configurability
|
|
27
|
+
- 15. New dependency for trivial work
|
|
28
|
+
- Cross-cutting observation
|
|
29
|
+
- Where this skill differs from generic clean-code rules
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
## 1. Catch-all error handling that swallows failures
|
|
34
|
+
|
|
35
|
+
**Pattern.** Wrapping operations in broad catch-all handlers or returning null/empty success on any caught error, hiding real bugs.
|
|
36
|
+
|
|
37
|
+
**Source.** Karpathy directly observed that LLMs are unusually afraid of exceptions. Reinforced by field reports on LLM error suppression. Root cause is the reward signal during training — propagating exceptions penalizes the model, so the model learns to suppress them.
|
|
38
|
+
|
|
39
|
+
**Bad:**
|
|
40
|
+
```text
|
|
41
|
+
getEmail(userId):
|
|
42
|
+
attempt:
|
|
43
|
+
user = userStore.get(userId)
|
|
44
|
+
return user.email
|
|
45
|
+
catch anyError:
|
|
46
|
+
return null
|
|
47
|
+
```
|
|
48
|
+
Looks safe. In practice, a database outage is now indistinguishable from "user has no email."
|
|
49
|
+
|
|
50
|
+
**Good:**
|
|
51
|
+
```text
|
|
52
|
+
getEmail(userId):
|
|
53
|
+
user = userStore.get(userId) // storage errors propagate
|
|
54
|
+
return user.email // null only means the user has no email
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
**Rule.** Catch only the specific error type you can recover from. Never use broad catch-all handling without a documented recovery path. Returning null/empty success from a handler is forbidden unless the function's contract says so.
|
|
58
|
+
|
|
59
|
+
---
|
|
60
|
+
|
|
61
|
+
## 2. Defensive guards for impossible cases
|
|
62
|
+
|
|
63
|
+
**Pattern.** Adding null checks, runtime type checks, or truthiness checks for conditions the type system or call graph already prevents.
|
|
64
|
+
|
|
65
|
+
**Source.** arXiv 2409.19182, "AI-Generated Code Considered Harmful"; HN discussion of defensive code overuse. Same reward-shaping mechanism as #1.
|
|
66
|
+
|
|
67
|
+
**Bad:**
|
|
68
|
+
```text
|
|
69
|
+
total(orderItems):
|
|
70
|
+
if orderItems is null: return 0
|
|
71
|
+
if orderItems is not a collection: return 0
|
|
72
|
+
return sum(order.amount for each non-null order in orderItems)
|
|
73
|
+
```
|
|
74
|
+
The contract says `orderItems` is a collection of orders. None of these guards can fire under normal call paths.
|
|
75
|
+
|
|
76
|
+
**Good:**
|
|
77
|
+
```text
|
|
78
|
+
total(orderItems):
|
|
79
|
+
return sum(order.amount for each order in orderItems)
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
**Rule.** Do not add null checks, runtime type checks, or truthiness checks for values whose type annotation or caller contract already excludes that case. Trust the contract. This applies *inside* a trust boundary; at the boundary itself — external input, payloads, deserialized or cross-process data — validation is required, not defensive bloat.
|
|
83
|
+
|
|
84
|
+
---
|
|
85
|
+
|
|
86
|
+
## 3. Premature abstraction
|
|
87
|
+
|
|
88
|
+
**Pattern.** Factories, strategy classes, base classes, plugin hooks, dependency-injection scaffolding introduced before a second concrete user exists.
|
|
89
|
+
|
|
90
|
+
**Source.** Martin Fowler, "Patterns for Reducing Friction in AI-Assisted Development" — names "overeagerness (adding unrequested features)" as a documented AI pattern. Fowler, "I still care about the code". Fowler, "Conversation: LLMs and Building Abstractions".
|
|
91
|
+
|
|
92
|
+
**Bad:**
|
|
93
|
+
```text
|
|
94
|
+
PaymentProcessor interface
|
|
95
|
+
charge(amount)
|
|
96
|
+
|
|
97
|
+
CardPaymentProcessor implements PaymentProcessor
|
|
98
|
+
charge(amount):
|
|
99
|
+
return paymentProvider.createCharge(amount).id
|
|
100
|
+
|
|
101
|
+
PaymentProcessorFactory
|
|
102
|
+
create():
|
|
103
|
+
return new CardPaymentProcessor()
|
|
104
|
+
```
|
|
105
|
+
There is exactly one payment processor. The abstract interface, the factory, and the indirection are pure ceremony.
|
|
106
|
+
|
|
107
|
+
**Good:**
|
|
108
|
+
```text
|
|
109
|
+
charge(amount):
|
|
110
|
+
return paymentProvider.createCharge(amount).id
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
**Rule.** Do not introduce an interface, abstract class, factory, registry, strategy, or plugin pattern unless two or more concrete implementations exist today or the spec explicitly requires extensibility. One implementation = inline it.
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
## 4. Comment pollution
|
|
118
|
+
|
|
119
|
+
**Pattern.** Line-by-line comments restating the code in English; step-number scaffolding comments left in; documentation comments that paraphrase the signature.
|
|
120
|
+
|
|
121
|
+
**Source.** HN thread #43929768 — *"The most common thing that makes agentic code ugly is the overuse of comments."* arXiv 2402.13013, "Code Needs Comments" and arXiv on multi-intent comment generation — LLM-generated comments answer "what?" rather than "why?", averaging ~5 descriptive words versus 19-word mixed-intent author comments.
|
|
122
|
+
|
|
123
|
+
**Bad:**
|
|
124
|
+
```text
|
|
125
|
+
// Increment counter by one
|
|
126
|
+
counter += 1
|
|
127
|
+
|
|
128
|
+
// Step 3: return the result
|
|
129
|
+
return result
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
**Good:**
|
|
133
|
+
```text
|
|
134
|
+
counter += 1
|
|
135
|
+
|
|
136
|
+
// Reset counter at midnight UTC to align with billing periods.
|
|
137
|
+
if counter > daily_limit:
|
|
138
|
+
counter = 0
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
**Rule.** Comments explain *why*, never *what*. Strip restating-code comments and any leftover "Step N" scaffolding before finalizing. Keep comments only where the rationale wouldn't be obvious to a reader of the code.
|
|
142
|
+
|
|
143
|
+
---
|
|
144
|
+
|
|
145
|
+
## 5. Code duplication instead of reuse
|
|
146
|
+
|
|
147
|
+
**Pattern.** Inline copies of logic that already exists in a helper, instead of importing it.
|
|
148
|
+
|
|
149
|
+
**Source.** GitClear, AI Copilot Code Quality 2025 — 211M-LoC longitudinal analysis. Copy-pasted 5+ line blocks increased **8x** between 2021 and 2024. Copy/pasted lines rose from 8.3% to 12.3%. Refactoring share dropped from 25% to under 10%. This is the strongest quantitative result on LLM code quality available.
|
|
150
|
+
|
|
151
|
+
**Rule.** Before writing a function, search the codebase for a similar existing one. If a block of ≥5 lines matches existing code in the repo, extract or call the existing function.
|
|
152
|
+
|
|
153
|
+
---
|
|
154
|
+
|
|
155
|
+
## 6. Hallucinated APIs and packages
|
|
156
|
+
|
|
157
|
+
**Pattern.** Imports, method names, or signatures that don't exist in the version of the library actually installed.
|
|
158
|
+
|
|
159
|
+
**Source.** Spracklen et al., USENIX Security '25, "Package Hallucinations" — 16 models tested; average hallucination rate 19.6% (commercial ~5%, open source ~21%). arXiv 2409.20550 "LLM Hallucinations in Practical Code Generation" gives a taxonomy. arXiv 2407.09726, "Mitigating Code LLM Hallucinations with API Documentation".
|
|
160
|
+
|
|
161
|
+
**Rule.** Every import and external API call must be verified against the actual installed version — read the package, check the lockfile, or import and inspect. Do not call a method based on what "should exist."
|
|
162
|
+
|
|
163
|
+
---
|
|
164
|
+
|
|
165
|
+
## 7. Generic, intent-less naming
|
|
166
|
+
|
|
167
|
+
**Pattern.** `data`, `result`, `item`, `temp`, `value`, `obj`, `info`, `helper`, `manager`, `utils`, `process_*`, `handle_*`, `do_*`.
|
|
168
|
+
|
|
169
|
+
**Source.** arXiv 2512.01141, "Neural Variable Name Repair" — generic identifiers are an explicit target of name-repair models because LLM code over-produces them. arXiv 2510.03178, "When Names Disappear" — semantic names act as anchors during generation.
|
|
170
|
+
|
|
171
|
+
**Bad:**
|
|
172
|
+
```text
|
|
173
|
+
processData(data):
|
|
174
|
+
result = []
|
|
175
|
+
for item in data:
|
|
176
|
+
temp = item.value * 2
|
|
177
|
+
result.add(temp)
|
|
178
|
+
return result
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
**Good:**
|
|
182
|
+
```text
|
|
183
|
+
doublePrices(orders):
|
|
184
|
+
return orders.map(order -> order.priceCents * 2)
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
**Rule.** Identifiers must reveal intent. Ban `data`, `result`, `item`, `temp`, `value`, `obj`, `info`, `helper`, `manager`, `handle_*`, `process_*`, `do_*` unless qualified (`raw_csv_bytes`, `parsed_invoice`).
|
|
188
|
+
|
|
189
|
+
---
|
|
190
|
+
|
|
191
|
+
## 8. Long functions doing many things
|
|
192
|
+
|
|
193
|
+
**Pattern.** A single function mixing I/O, business logic, formatting, and side effects — often because the prompt asked for several things in one breath.
|
|
194
|
+
|
|
195
|
+
**Source.** arXiv 2512.11922, "Vibe Coding in Practice" — documents how AI-assisted "vibe coding" accumulates technical debt through architectural inconsistencies; the canonical symptom is a single function hundreds of lines long handling several unrelated concerns, assembled from multiple AI-generated fragments. GitClear 2025 — file size 142→267 LoC, cyclomatic complexity 4.2→8.1 in AI-assisted commits. arXiv 2304.10778 compares Copilot/CodeWhisperer/ChatGPT quality.
|
|
196
|
+
|
|
197
|
+
**Rule.** A function does one thing. If the prompt asks for N things, produce N functions and a small composer. Refactor ceiling: ~50 lines (target ≤20), ≤4 parameters, cyclomatic complexity ≤10 — refactor before exceeding.
|
|
198
|
+
|
|
199
|
+
---
|
|
200
|
+
|
|
201
|
+
## 9. Parameter explosion
|
|
202
|
+
|
|
203
|
+
**Pattern.** Functions taking 6+ positional or keyword args that should have been a typed config object.
|
|
204
|
+
|
|
205
|
+
**Source.** arXiv 2304.10778 quality study and Fowler's overeagerness pattern. The triggering behavior is "AI does not pause to extract a config struct."
|
|
206
|
+
|
|
207
|
+
**Bad:**
|
|
208
|
+
```text
|
|
209
|
+
sendEmail(to, subject, body, retry=true, backoff="exp",
|
|
210
|
+
html=false, fromAddress=null, encoding="utf-8",
|
|
211
|
+
internal=false, verbose=false)
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
**Good:**
|
|
215
|
+
```text
|
|
216
|
+
EmailRequest
|
|
217
|
+
to
|
|
218
|
+
subject
|
|
219
|
+
body
|
|
220
|
+
html = false
|
|
221
|
+
|
|
222
|
+
sendEmail(request: EmailRequest)
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
**Rule.** When a function reaches 5 parameters, stop and introduce a typed request/config object: record, struct, DTO, or equivalent. Do not keep adding positional args.
|
|
226
|
+
|
|
227
|
+
---
|
|
228
|
+
|
|
229
|
+
## 10. Inconsistency with surrounding code
|
|
230
|
+
|
|
231
|
+
**Pattern.** Introduces snake_case in a camelCase file, a new HTTP client when the repo has one, a new error type when an existing taxonomy exists, a new logging style.
|
|
232
|
+
|
|
233
|
+
**Source.** Pullflow, "The Context Illusion"; Honeycomb, "How I Code With LLMs These Days"; Stripe Minions architecture writeups (anup.io, Stripe blog). The explicit production fix is forcing the agent to read repo-local conventions before writing.
|
|
234
|
+
|
|
235
|
+
**Rule.** Before writing in a file, read the file and at least one neighbor. Match casing, import style, error handling pattern, and logging style. Reuse the project's existing HTTP, database, and logging utilities rather than introducing new ones.
|
|
236
|
+
|
|
237
|
+
---
|
|
238
|
+
|
|
239
|
+
## 11. Dead code, unused imports, half-implementations
|
|
240
|
+
|
|
241
|
+
**Pattern.** Imports never referenced, helper functions never called, branches never reachable, "just in case" exports.
|
|
242
|
+
|
|
243
|
+
**Source.** arXiv 2411.01414, "A Deep Dive Into LLM Code Generation Mistakes" — 7-category taxonomy of non-syntactic mistakes including specification-deviation patterns that leave half-implemented code. GitClear's "added-code dominates moved/deleted" finding is the quantitative version.
|
|
244
|
+
|
|
245
|
+
**Rule.** Before finalizing, run a linter or static check for unused imports, unused symbols, and unreachable branches; remove them. Do not leave a function defined unless something calls it now.
|
|
246
|
+
|
|
247
|
+
---
|
|
248
|
+
|
|
249
|
+
## 12. "Declares success" — mock fallbacks in production code
|
|
250
|
+
|
|
251
|
+
**Pattern.** Returning hardcoded success values, fixture data, or empty defaults instead of doing the actual work, then claiming the task is done.
|
|
252
|
+
|
|
253
|
+
**Source.** Fowler, "Patterns for Reducing Friction" — names "declaring success despite failing tests" and "brute-force fixes." claude-code issue #6984 "Systematic Mock Data Generation Bias". Anthropic Claude Code best practices explicitly tell agents: no mock implementations.
|
|
254
|
+
|
|
255
|
+
**Bad:**
|
|
256
|
+
```text
|
|
257
|
+
getUserBalance(userId):
|
|
258
|
+
return 1000 // TODO: actual provider call
|
|
259
|
+
```
|
|
260
|
+
Shipped as the implementation, function body is fiction.
|
|
261
|
+
|
|
262
|
+
**Good:**
|
|
263
|
+
```text
|
|
264
|
+
getUserBalance(userId):
|
|
265
|
+
raise NotImplemented("Wire to billing.getBalance() after auth is available")
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
**Rule.** Never return hardcoded "success" values or fixture data from a function the spec says should perform real work. Never disable, skip, or change a test to make it pass. If you cannot implement, fail explicitly with an unimplemented error and say what is missing.
|
|
269
|
+
|
|
270
|
+
---
|
|
271
|
+
|
|
272
|
+
## 13. Plausible-but-wrong code
|
|
273
|
+
|
|
274
|
+
**Pattern.** Code that compiles and reads correctly but encodes a slightly wrong formula, range, or null semantic — often lifted from a similar-but-different function.
|
|
275
|
+
|
|
276
|
+
**Source.** arXiv 2411.01414 — 4 of the 7 mistake categories are non-syntactic semantic mistakes prior work had missed; root cause is "misunderstanding of specification." Katanaquant, "Your LLM Doesn't Write Correct Code. It Writes Plausible Code". Simon Willison: hallucinations in code are *less* dangerous because they fail loudly — the corollary is that the dangerous class is plausible-but-wrong semantic code that runs.
|
|
277
|
+
|
|
278
|
+
**Bad:**
|
|
279
|
+
```text
|
|
280
|
+
# Compute median
|
|
281
|
+
median = (values[values.length / 2] + values[values.length / 2 + 1]) / 2
|
|
282
|
+
// off-by-one for odd length
|
|
283
|
+
|
|
284
|
+
# Iterate items
|
|
285
|
+
for index from 1 to items.length - 1:
|
|
286
|
+
... // silently drops items[0]
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
**Rule.** For any boundary, range, off-by-one, or null-semantic question, write the case enumeration in a comment first (`cases: empty / one / even / odd / null`) and verify each case before the code. Never copy a similar function and adapt — re-derive from the spec.
|
|
290
|
+
|
|
291
|
+
---
|
|
292
|
+
|
|
293
|
+
## 14. YAGNI violations — speculative configurability
|
|
294
|
+
|
|
295
|
+
**Pattern.** Config flags, env vars, optional parameters, and feature toggles for use cases that don't exist.
|
|
296
|
+
|
|
297
|
+
**Source.** Fowler's overeagerness pattern and the HN defensive-code thread. Anecdotal but widely observed.
|
|
298
|
+
|
|
299
|
+
**Bad:**
|
|
300
|
+
```text
|
|
301
|
+
renderInvoice(invoice,
|
|
302
|
+
format="pdf", template=null, locale="en",
|
|
303
|
+
includeQr=false, currencyOverride=null,
|
|
304
|
+
debug=false, legacyMode=false)
|
|
305
|
+
```
|
|
306
|
+
Only one caller exists. It passes `(invoice,)`.
|
|
307
|
+
|
|
308
|
+
**Good:**
|
|
309
|
+
```text
|
|
310
|
+
renderInvoice(invoice)
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
**Rule.** No optional parameter, config flag, env var, or feature toggle without a present-day caller. If you find yourself adding `enable_*`, `use_*`, or `*_mode` arguments, delete them and rely on the single concrete behavior.
|
|
314
|
+
|
|
315
|
+
---
|
|
316
|
+
|
|
317
|
+
## 15. New dependency for trivial work
|
|
318
|
+
|
|
319
|
+
**Pattern.** Adding a third-party package to do what the standard library, an already-installed dependency, or a few lines of code already cover — a micro-dependency for a one-line helper, or a heavy library pulled in for a single function.
|
|
320
|
+
|
|
321
|
+
**Source.** Field reports on AI over-building (Fowler's overeagerness pattern) and long-standing supply-chain guidance: every dependency is permanent maintenance surface — version churn, transitive vulnerabilities, audit and licensing weight — that a small local function never carries. Same emit-more bias as modes 3 and 14.
|
|
322
|
+
|
|
323
|
+
**Bad:**
|
|
324
|
+
```text
|
|
325
|
+
# add a package to sum a column of numbers
|
|
326
|
+
import stats_helpers
|
|
327
|
+
total = stats_helpers.sum_column(rows, "amount")
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
**Good:**
|
|
331
|
+
```text
|
|
332
|
+
total = sum(row.amount for row in rows)
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
**Rule.** Before adding a package, check the stdlib, the already-installed dependencies, and whether a few lines solve it. Add a dependency only when it owns real complexity you should not re-implement (cryptography, parsing, time zones — illustrative, not exhaustive), never to avoid a short function. This is the inverse of mode 5 and of [dry-kiss-yagni.md](dry-kiss-yagni.md) ranked item 8: don't re-implement what the platform gives you — and don't import what a few lines already cover.
|
|
336
|
+
|
|
337
|
+
---
|
|
338
|
+
|
|
339
|
+
## Cross-cutting observation
|
|
340
|
+
|
|
341
|
+
Nine of the 15 failure modes (1, 2, 3, 9, 12, 14, 15, plus pieces of 8 and 11) trace to one root cause: **the model is biased toward emitting more code, more parameters, more guards, more abstractions** — anything but the minimum required by the spec. The cure is restraint, not knowledge. Before writing each line, ask: *does the spec require this, today?* If no, do not write it.
|
|
342
|
+
|
|
343
|
+
## Where this skill differs from generic clean-code rules
|
|
344
|
+
|
|
345
|
+
Sections in [naming-and-functions.md](naming-and-functions.md), [solid.md](solid.md), and [dry-kiss-yagni.md](dry-kiss-yagni.md) cover the classic principles. They are necessary but not sufficient — an LLM that "knows" SOLID can still produce code that fails for the reasons in this file. The 15 patterns above are the high-leverage check. Walk them before delivery.
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
# Comments and Formatting — Clean Code Chapters 4 and 5
|
|
2
|
+
|
|
3
|
+
Source: Robert C. Martin, *Clean Code*. Summaries: Vivek Khatri Ch. 4, Vivek Khatri Ch. 5, LinkedIn summary of Ch. 4.
|
|
4
|
+
|
|
5
|
+
## Contents
|
|
6
|
+
|
|
7
|
+
- Comments
|
|
8
|
+
- C1. Acceptable comments
|
|
9
|
+
- C2. Banned comments
|
|
10
|
+
- C3. Docstring discipline
|
|
11
|
+
- Formatting
|
|
12
|
+
- Fmt1. Vertical openness separates concepts
|
|
13
|
+
- Fmt2. Vertical density implies association
|
|
14
|
+
- Fmt3. Vertical distance
|
|
15
|
+
- Fmt4. Horizontal density
|
|
16
|
+
- Fmt5. Match the file you're editing
|
|
17
|
+
- Self-check for comments and formatting
|
|
18
|
+
|
|
19
|
+
## Comments
|
|
20
|
+
|
|
21
|
+
The foundational rule: **"Don't comment bad code — rewrite it."** Comments are failures to express intent in code. Every comment is a candidate for rename or extract.
|
|
22
|
+
|
|
23
|
+
### C1. Acceptable comments
|
|
24
|
+
|
|
25
|
+
A short list of comments that earn their keep:
|
|
26
|
+
|
|
27
|
+
- **Legal headers** — license boilerplate, copyright.
|
|
28
|
+
- **Intent** — explaining *why* a decision was made when the choice is non-obvious. Example: `// Use exponential backoff to avoid hammering the rate limiter during retries.`
|
|
29
|
+
- **Warnings of consequences** — `// This function is called during transaction commit; do not raise.`
|
|
30
|
+
- **TODOs** — sparingly, with a tracking ticket reference. `// TODO(JIRA-1234): switch to streaming once API supports it.`
|
|
31
|
+
- **Public API documentation** — docstrings that document *contract* (preconditions, postconditions, raises), not body.
|
|
32
|
+
- **Amplification** — calling attention to something non-obvious. `# The `+ 1` accounts for the inclusive end of the range; see RFC §3.2.`
|
|
33
|
+
|
|
34
|
+
### C2. Banned comments
|
|
35
|
+
|
|
36
|
+
Delete on sight:
|
|
37
|
+
|
|
38
|
+
- **Restating-code comments.** `// increment counter by one` above `counter += 1`. The comment adds zero signal and creates two things to maintain.
|
|
39
|
+
- **Noise comments.** `# default constructor`, `# getter`, `# returns the day of month`.
|
|
40
|
+
- **Banner comments.** `# ====== USER FUNCTIONS ======`. Use a class or module split instead.
|
|
41
|
+
- **Closing-brace comments.** `} // end of for loop`. If you need this to follow the flow, the function is too long.
|
|
42
|
+
- **Attributions and journal comments.** `# Updated by Bob on 2023-04-01 to fix bug #42`. Version control records this.
|
|
43
|
+
- **Commented-out code.** Delete it. If you need it back, git has it. Commented blocks are toxic — readers don't know whether to trust them.
|
|
44
|
+
- **`Step 1` / `Step 2` scaffolding.** Common LLM artifact. Each step should be a function call with a name; the names provide the structure.
|
|
45
|
+
|
|
46
|
+
### C3. Docstring discipline
|
|
47
|
+
|
|
48
|
+
A documentation comment that paraphrases the function signature is noise:
|
|
49
|
+
|
|
50
|
+
**Bad:**
|
|
51
|
+
```text
|
|
52
|
+
add(a, b)
|
|
53
|
+
// Adds a and b and returns the result.
|
|
54
|
+
return a + b
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
**Good:**
|
|
58
|
+
```text
|
|
59
|
+
add(a, b)
|
|
60
|
+
return a + b
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
A documentation comment earns its keep when it documents contract: what may be passed, what may be returned, what errors are raised, and any non-obvious side effects.
|
|
64
|
+
|
|
65
|
+
**Good:**
|
|
66
|
+
```text
|
|
67
|
+
// Charge a payment source.
|
|
68
|
+
// Returns: charge identifier.
|
|
69
|
+
// Raises: CardDeclined for decline failures; PaymentProviderError otherwise.
|
|
70
|
+
// Side effect: writes an audit record on success.
|
|
71
|
+
charge(paymentSourceId, amountCents)
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
---
|
|
75
|
+
|
|
76
|
+
## Formatting
|
|
77
|
+
|
|
78
|
+
### Fmt1. Vertical openness separates concepts
|
|
79
|
+
|
|
80
|
+
Blank lines between concepts. No blank lines inside a tightly-coupled block. The eye uses blank lines as boundaries.
|
|
81
|
+
|
|
82
|
+
### Fmt2. Vertical density implies association
|
|
83
|
+
|
|
84
|
+
Code that belongs together should sit together. Variable declared 30 lines from its use is a smell.
|
|
85
|
+
|
|
86
|
+
### Fmt3. Vertical distance
|
|
87
|
+
|
|
88
|
+
- **Variables declared close to use.** Not at the top of the function "C-style."
|
|
89
|
+
- **Caller above callee.** Top-down reading: high-level function first, then the helpers it calls. The step-down rule ([naming-and-functions.md](naming-and-functions.md) F4).
|
|
90
|
+
- **Conceptually related functions adjacent.** If `parse_invoice` and `validate_invoice` are siblings, put them next to each other, not on opposite ends of the file.
|
|
91
|
+
|
|
92
|
+
### Fmt4. Horizontal density
|
|
93
|
+
|
|
94
|
+
- Spaces around assignment and comparison operators: `x = 1`, `if x == 1`.
|
|
95
|
+
- No space between function name and parenthesis: `f(x)` not `f (x)`.
|
|
96
|
+
- Line length: 80 traditional, ≤100–120 acceptable. Beyond 120 is careless.
|
|
97
|
+
|
|
98
|
+
### Fmt5. Match the file you're editing
|
|
99
|
+
|
|
100
|
+
The most common cross-cutting violation: introducing a new style in a file that already had one. If the file uses snake_case, do not introduce camelCase. If it uses double quotes, do not introduce single quotes. If it sorts imports alphabetically, do not append at the bottom. If the project already has an HTTP client, database wrapper, or logging helper, reuse it instead of introducing another one.
|
|
101
|
+
|
|
102
|
+
Team rules override personal preference. Read the file, then write.
|
|
103
|
+
|
|
104
|
+
---
|
|
105
|
+
|
|
106
|
+
## Self-check for comments and formatting
|
|
107
|
+
|
|
108
|
+
Before you ship code:
|
|
109
|
+
|
|
110
|
+
1. Walk every comment you added. For each, ask: does it explain *why*? If it explains *what*, delete it.
|
|
111
|
+
2. Walk every documentation comment you added. Is it paraphrasing the signature? Delete the paraphrase; keep only contract documentation.
|
|
112
|
+
3. Any commented-out code? Delete it.
|
|
113
|
+
4. Any `Step 1`, `Step 2`, `First, ...`, or `Then, ...` scaffolding comments? Delete.
|
|
114
|
+
5. Are variables declared near their use, not at the top?
|
|
115
|
+
6. Does the casing, quoting, and import order match the file's existing style?
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# DRY, KISS, YAGNI
|
|
2
|
+
|
|
3
|
+
Three short principles. Often confused. Often applied wrong by AI agents (and humans).
|
|
4
|
+
|
|
5
|
+
## Contents
|
|
6
|
+
|
|
7
|
+
- DRY: do not duplicate knowledge
|
|
8
|
+
- KISS: keep complexity low and local
|
|
9
|
+
- YAGNI: avoid speculative configurability
|
|
10
|
+
- Ranked list: where AI agents over-engineer
|
|
11
|
+
- Self-check for DRY, KISS, YAGNI
|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
## DRY — Don't Repeat Yourself
|
|
16
|
+
|
|
17
|
+
**Definition (Hunt & Thomas, *The Pragmatic Programmer*, verbatim).** *"Every piece of knowledge must have a single, unambiguous, authoritative representation within a system."*
|
|
18
|
+
|
|
19
|
+
Source: pragprog official DRY excerpt PDF; Wikipedia summary; O'Reilly *97 Things Every Programmer Should Know*, Ch. 30.
|
|
20
|
+
|
|
21
|
+
### The misreading
|
|
22
|
+
|
|
23
|
+
*"Don't have any duplicate code."* No. Hunt and Thomas frame DRY as duplication "of knowledge, of intent... expressing the same thing in two different places, possibly in two totally different ways." Two functions that **look alike but encode different rules** are not a DRY violation. **One rule** expressed in code + database schema + documentation **is**.
|
|
24
|
+
|
|
25
|
+
### Smells worth flagging
|
|
26
|
+
|
|
27
|
+
These are textual signals that *probably* indicate knowledge duplication, but verify the underlying meaning before refactoring:
|
|
28
|
+
|
|
29
|
+
- Identical token sequence of ≥5 non-trivial lines appearing in ≥2 functions.
|
|
30
|
+
- The same regex, SQL fragment, or URL literal repeated in ≥3 sites.
|
|
31
|
+
- The same magic number or string repeated ≥3 times outside a constants module.
|
|
32
|
+
- The same validation branch (for example, "if value is missing, raise") duplicated across siblings of one module.
|
|
33
|
+
|
|
34
|
+
### The Rule of 3 — wait for the third occurrence
|
|
35
|
+
|
|
36
|
+
Don't extract an abstraction the first time you see duplication. Don't extract on the second. Wait for the third — by then you have enough signal about the *real* shape of the shared knowledge to abstract correctly. The Rule of 3 is folklore from refactoring practice; the underlying principle (don't abstract too early) is in Fowler's *Refactoring* (refactoring.com/catalog) and in the wrong-abstraction work below.
|
|
37
|
+
|
|
38
|
+
### The Sandi Metz corollary — wrong abstraction is worse than duplication
|
|
39
|
+
|
|
40
|
+
From Sandi Metz, "The Wrong Abstraction" (Jan 2016): *"duplication is far cheaper than the wrong abstraction."*
|
|
41
|
+
|
|
42
|
+
If an abstraction has accumulated per-caller branches and special cases, it is the wrong abstraction. The remedy:
|
|
43
|
+
|
|
44
|
+
1. Re-inline the abstraction back into each caller.
|
|
45
|
+
2. Delete the per-caller dead branches.
|
|
46
|
+
3. Live with honest duplication for a while.
|
|
47
|
+
4. Re-abstract only when the *real* shared knowledge becomes obvious.
|
|
48
|
+
|
|
49
|
+
**Rule.** Do not introduce an abstraction to eliminate three lines of duplication unless you can name the underlying *knowledge* the lines represent. If you can't name it, leave the duplication.
|
|
50
|
+
|
|
51
|
+
---
|
|
52
|
+
|
|
53
|
+
## KISS — Keep It Simple, Stupid
|
|
54
|
+
|
|
55
|
+
**Origin.** Coined by Clarence "Kelly" Johnson at Lockheed's Skunk Works (U-2, SR-71). His designers were handed a basic toolkit; the aircraft had to be repairable by an average mechanic in a combat field with only those tools. The "stupid" refers to the mismatch between break-conditions and repair sophistication — not to the engineer.
|
|
56
|
+
|
|
57
|
+
Original phrasing: *"Keep it simple stupid"* (no comma). First documented use by the U.S. Navy in 1960.
|
|
58
|
+
|
|
59
|
+
Source: Wikipedia, KISS principle; Braithwaite background story.
|
|
60
|
+
|
|
61
|
+
### Operationalizing KISS for code review
|
|
62
|
+
|
|
63
|
+
KISS is fuzzy without numbers. Use these as defaults:
|
|
64
|
+
|
|
65
|
+
- **Cognitive Complexity ≤10 per function.** SonarSource's Cognitive Complexity metric measures *how hard the code is to understand* rather than the count of independent paths. It's the dominant 2026 metric — adopted by SonarQube, Biome, and ReSharper. Target <7 for greenfield code; <15 is the upper bound before refactor is mandatory.
|
|
66
|
+
- **Cyclomatic complexity ≤10 per function.** McCabe's original 1976 metric, still useful as a structural floor. 11–20 is moderate risk; 21–50 is high risk; >50 is untestable. Source: McCabe NIST 235r; JetBrains ReSharper threshold guidance. Use Cognitive Complexity for human-readability judgement; use cyclomatic for "is this testable" judgement. When they disagree, prefer Cognitive Complexity.
|
|
67
|
+
- **Nesting depth ≤5.** Source: Aivosto, Project Metrics: Complexity.
|
|
68
|
+
- **Function length:** no canonical absolute, but common static-analysis defaults (SonarQube, PMD) flag >50–60 lines. Pair with complexity ceiling rather than relying on LOC alone.
|
|
69
|
+
|
|
70
|
+
### Self-check
|
|
71
|
+
|
|
72
|
+
When you see a function exceed cyclo 10 or nest depth 5, refactor *before* finishing — not "later." Extract a helper, replace nested `if/else` with early returns or a lookup table.
|
|
73
|
+
|
|
74
|
+
---
|
|
75
|
+
|
|
76
|
+
## YAGNI — You Aren't Gonna Need It
|
|
77
|
+
|
|
78
|
+
**Canonical reference.** Martin Fowler, *bliki: Yagni* (May 2015). *"A mantra from ExtremeProgramming... capabilities we presume our software needs in the future should not be built now because 'you aren't gonna need it.'"*
|
|
79
|
+
|
|
80
|
+
### Fowler's four cost categories
|
|
81
|
+
|
|
82
|
+
When you build a presumptive feature, you pay:
|
|
83
|
+
|
|
84
|
+
1. **Cost of build.** Analysis, coding, testing of a feature that ends up unused.
|
|
85
|
+
2. **Cost of delay.** Opportunity cost — revenue-generating work you didn't do instead.
|
|
86
|
+
3. **Cost of carry.** Added complexity makes every future modification and debug slower.
|
|
87
|
+
4. **Cost of repair.** When the presumed feature turns out to be wrong, you pay to rip it out plus the technical debt accumulated against it.
|
|
88
|
+
|
|
89
|
+
Source: martinfowler.com/bliki/Yagni.html; InfoQ summary.
|
|
90
|
+
|
|
91
|
+
### AI-specific YAGNI traps
|
|
92
|
+
|
|
93
|
+
LLMs over-produce speculative surface area. These are the patterns to spot:
|
|
94
|
+
|
|
95
|
+
1. **Config flags / env vars nobody asked for.** `enable_x_v2`, `legacy_mode`, toggles for a single code path that has no second variant.
|
|
96
|
+
2. **Plugin / strategy systems for 2 known cases.** Registry + base class + 2 subclasses where a direct conditional is shorter and clearer.
|
|
97
|
+
3. **Generic helpers with one caller.** `normalizeAnything(value, strict=false, mode="default")` invoked from exactly one site.
|
|
98
|
+
4. **Optional parameters never passed.** `send(value, retries=3, backoff=null, jitter=false, logger=null)` where every call site uses defaults. Delete them until a real caller exists.
|
|
99
|
+
5. **Speculative async / batching / caching.** Async wrappers, queues, and batch endpoints where current load is single-digit RPS.
|
|
100
|
+
6. **Premature interfaces/protocols with one implementation.** `FooRepository` paired with one concrete `SqlFooRepository`. Inline until you have a second implementation.
|
|
101
|
+
|
|
102
|
+
### Self-check
|
|
103
|
+
|
|
104
|
+
For every parameter, class, file, or abstraction you introduce, answer: *who calls this today?* If the answer is "nobody yet," delete it.
|
|
105
|
+
|
|
106
|
+
---
|
|
107
|
+
|
|
108
|
+
## Ranked list — where AI agents over-engineer
|
|
109
|
+
|
|
110
|
+
By frequency observed (engineering-blog-grade, not from a controlled study):
|
|
111
|
+
|
|
112
|
+
1. **Premature interfaces/protocols** with one implementation.
|
|
113
|
+
2. **Factory classes for trivial constructors** — `UserFactory.create(...)` wrapping `User(...)`.
|
|
114
|
+
3. **DI containers in small apps** — wiring frameworks for 3–5 services where explicit construction in `main()` is shorter and traceable.
|
|
115
|
+
4. **Try/catch wrappers that change nothing** — adds lines, hides tracebacks.
|
|
116
|
+
5. **Speculative config surface** — settings objects with 15 fields where 3 are read.
|
|
117
|
+
6. **Plugin / registry scaffolding for two cases.**
|
|
118
|
+
7. **`utils.py` / `common.py` modules** — magnets for unrelated functions; violate DRY's "single authoritative representation" by location.
|
|
119
|
+
8. **Re-implementing what the platform already gives you** — custom retry loops, enums, or record-like types the standard library provides; hand-rolled validation a database/schema constraint, the type system, or a framework's declarative rule would enforce; a native platform feature replaced by hand-written app code. Prefer the cheapest existing solution: stdlib or native feature over new code, a declarative constraint over an imperative check. The flip side is mode 15 in [ai-failure-modes.md](ai-failure-modes.md) — don't reach for a *new* dependency for what a few lines already cover either.
|
|
120
|
+
9. **Excessive layering** (Controller → Service → Manager → Repository) for CRUD — four files to read one row.
|
|
121
|
+
10. **Wrapping libraries "to make them swappable"** — thin pass-through adapters around an HTTP, database, or SDK client you will never swap.
|
|
122
|
+
|
|
123
|
+
---
|
|
124
|
+
|
|
125
|
+
## Self-check for DRY, KISS, YAGNI
|
|
126
|
+
|
|
127
|
+
Before you ship code:
|
|
128
|
+
|
|
129
|
+
1. (DRY) Did you eliminate duplication of *knowledge*, or just duplication of *text*? Can you name the underlying rule?
|
|
130
|
+
2. (DRY/Metz) If you introduced an abstraction, are there at least two callers today whose code is structurally identical? Or is the abstraction speculative?
|
|
131
|
+
3. (KISS) Any function over cyclomatic 10 or nest depth 5?
|
|
132
|
+
4. (YAGNI) Any optional parameter, config flag, env var, interface, factory, or base class without a caller using it today?
|
|
133
|
+
5. (YAGNI) Did you wrap a library to "make it swappable"? Delete the wrapper.
|