feat: Add SOLID principles and TDD reference documentation

- Created solid.md to document the SOLID principles for clean code practices.
- Created tdd.md to outline Test Driven Development principles and practices.
- Added kana-rust-backend-best-practice.md as a reference guide for building a Rust backend using Axum and SeaORM.
- Established push-flow-convention.md to enforce pre-commit and pre-push hooks with versioning rules.
- Introduced AGENTS.md to provide guidance on best practices and available commands for Kilo.
- Configured kilo.json to include new skills and agents for enhanced functionality.
- Added lefthook.yml for managing git hooks to ensure code quality and adherence to conventions.
This commit is contained in:
asepharyana
2026-07-21 07:10:17 +07:00
parent d615090dcd
commit 55677dd671
23 changed files with 2110 additions and 33 deletions
+94
View File
@@ -0,0 +1,94 @@
---
name: commit-and-push
description: Enforce Conventional Commits specification for all commit messages and push workflows
---
# Commit and Push Rule
All commits MUST follow the [Conventional Commits v1.0.0](https://www.conventionalcommits.org/en/v1.0.0/) specification. No exceptions.
## Commit Message Format
```
<type>[optional scope]: <description>
[optional body]
[optional footer(s)]
```
## Types
| Type | When to use |
|------|-------------|
| `feat` | New feature — correlates with `MINOR` in semver |
| `fix` | Bug fix — correlates with `PATCH` in semver |
| `chore` | Maintenance, deps, config — no production code change |
| `docs` | Documentation only |
| `style` | Formatting, whitespace — no logic change |
| `refactor` | Code restructure — no feature or fix |
| `perf` | Performance improvement |
| `test` | Adding or correcting tests |
| `build` | Build system or external dependency changes |
| `ci` | CI configuration and scripts |
| `revert` | Reverts a previous commit |
## Breaking Changes
Append `!` after type/scope to indicate a breaking change. This correlates with `MAJOR` in semver.
```
feat(api)!: remove deprecated /v1/users endpoint
BREAKING CHANGE: /v1/users has been removed. Use /v2/users instead.
```
A `BREAKING CHANGE:` footer can also be used in the commit body.
## Rules
1. Type is ALWAYS lowercase.
2. Description is imperative mood ("add", not "added" or "adds").
3. Description is lowercase, no trailing period.
4. Keep subject line under 72 characters.
5. Scope is optional but recommended for `feat` and `fix` — use the affected module name.
6. One logical change per commit. If a commit spans multiple types, split into multiple commits.
7. Body wraps at 72 characters. Use it to explain **why**, not **what**.
8. Footer uses `git trailer` format (e.g., `BREAKING CHANGE:`, `Reviewed-by:`, `Refs:`).
## Lefthook Hooks
Every commit and push MUST go through Lefthook's `pre-commit` and `pre-push` hooks. Hooks are the gatekeeper — if they fail, the commit/push does not happen.
1. `pre-commit` runs lint-staged on staged files. Commit is blocked until lint-staged passes.
2. `pre-push` runs lint-staged diff check and version bump. Push is blocked until both pass.
3. If a hook fails, **fix the root cause**. Do not work around it.
## Push
1. Every push MUST pass pre-commit and pre-push hooks (see `push-flow-convention` skill).
2. **NEVER use `--no-verify`** to bypass hooks. No exceptions. No "just this once." If hooks fail, fix the issue and retry.
3. **NEVER use `git commit --no-verify`**. If pre-commit fails, fix linting/formatting and restage.
4. **NEVER use `git push --no-verify`**. If pre-push fails, fix the failing check and push again.
5. Commit message quality is enforced — reject vague messages like "fix stuff", "update", "wip", "misc".
6. If Lefthook is not installed, run `pnpm exec lefthook install` before committing. Do not commit without hooks registered.
7. **NEVER add `Co-Authored-By` trailers for AI tools** (e.g., `Co-Authored-By: Claude Code <noreply@anthropic.com>`). Commits are authored by humans only. No AI attribution in commit messages.
8. **NEVER stage all files in one commit** (`git add .` or `git add -A` then commit). Group related changes into separate, focused commits. Each commit = one logical change. If a feature touches auth + billing, split into separate commits per module.
9. Stage files deliberately by name (`git add src/auth/login.ts src/auth/types.ts`). Review what's staged before committing (`git status`, `git diff --cached`).
## Examples
```
feat(auth): add google oauth sign-in
fix(cart): correct total calculation when discount is zero
chore: update eslint config
docs: add setup guide to README
refactor(billing): extract invoice calculation to service layer
test(users): add unit tests for avatar upload
perf(api): cache user profile queries
feat(api)!: change response format for /orders endpoint
```
## Reference
Full specification: [conventionalcommits.org/en/v1.0.0](https://www.conventionalcommits.org/en/v1.0.0/)
+58
View File
@@ -0,0 +1,58 @@
---
name: docs-folder
description: Route non-hexagonal files to docs/ folder to keep domain architecture clean
---
# Docs Folder Rule
Any file that does not fit the hexagonal architecture design pattern MUST live in the `docs/` folder. The source tree stays clean — only hexagonal-compliant code belongs in `src/`.
## Hexagonal Architecture Recap
```
src/
├── domain/ # Pure business logic, entities, value objects, ports (interfaces)
├── application/ # Use cases, orchestration, input/output ports
├── infrastructure/ # Adapters — DB, HTTP clients, messaging, external APIs
└── interfaces/ # Controllers, routes, CLI, resolvers (driving adapters)
```
Only code that fits one of these layers belongs in the source tree.
## What goes in `docs/`
| Item | Why it's not hexagonal |
|------|----------------------|
| Architecture decision records (ADRs) | Documentation, not code |
| API documentation / OpenAPI specs | Reference material |
| Database diagrams / ERDs | Design artifacts |
| Flowcharts / sequence diagrams | Visual documentation |
| Meeting notes / technical decisions | Project context |
| Onboarding guides | People documentation |
| RFC / proposal documents | Decision records |
| Scratch files / experiments | Not production code |
| Third-party integration guides | Reference material |
| Deployment runbooks | Ops documentation |
| Configuration examples / templates | Not domain logic |
| Migration guides / upgrade notes | Process documentation |
## Structure
```
docs/
├── adr/ # Architecture Decision Records
├── api/ # API specs, OpenAPI/Swagger files
├── diagrams/ # ERDs, flowcharts, sequence diagrams
├── guides/ # Onboarding, deployment, migration guides
├── rfcs/ # Proposals and RFCs
└── notes/ # Meeting notes, scratch, experiments
```
## Non-negotiables
1. NEVER put documentation files in `src/` — they pollute the domain.
2. NEVER put scratch code, experiments, or spikes in `src/` — use `docs/notes/` or a separate branch.
3. NEVER put config examples or templates in `src/` — use `docs/` or project root.
4. If a file doesn't implement a port, adapter, use case, or entity — it doesn't belong in `src/`.
5. Keep `docs/` organized by category, not by date or author.
6. README at project root is fine — detailed docs go in `docs/`.
+295
View File
@@ -0,0 +1,295 @@
---
name: clean-code
description: Apply Robert C. Martin's (Uncle Bob's) Clean Code, Clean Architecture, and Clean Craftsmanship principles when writing, reviewing, or refactoring code. Use this skill whenever the user asks to write new code of non-trivial size (functions, classes, modules, services), refactor or clean up existing code, review code for quality, design a module or system boundary, write tests, or whenever the user mentions "clean code," "clean architecture," "SOLID," "SRP," "OCP," "LSP," "ISP," "DIP," "TDD," "refactor," "code smells," "code review," "Uncle Bob," or "Robert Martin." Also engage proactively when producing or examining code that shows poor naming, long functions (>20 lines), deep nesting, unclear abstractions, duplicated logic, switch/if-else chains that should be polymorphic, missing tests, leaky boundaries, or frameworks bleeding into business logic — even if the user did not explicitly ask for a cleanup. Do not wait for magic words; if you are writing or touching code, consult this skill.
---
# Clean Code (Uncle Bob)
This skill codifies the principles that Robert C. Martin teaches across *Clean Code* (2008), *Clean Architecture* (2017), *Clean Craftsmanship* (2021), his blog at blog.cleancoder.com, the older wiki at butunclebob.com, his Google Sites articles, and his courses at cleancoder.com. It applies during code generation, review, refactoring, and system design.
## Core Philosophy
Three mental anchors to carry into every edit:
1. **Code is read far more than written.** The ratio is well over 10:1. Optimize for the reader — future teammates, and your future self.
2. **The Boy Scout Rule.** Leave every module cleaner than you found it — even if just by renaming one variable or extracting one tiny function.
3. **The only way to go fast is to go well.** Dirty code slows the whole team down. "We'll clean it up later" rarely happens, and productivity collapses into the Productivity Roller-Coaster or the Grand-Redesign Myth. Clean as you go, always.
Some quotes from other practitioners Uncle Bob cites:
- "Clean code is simple and direct. Clean code reads like well-written prose." — Grady Booch
- "Clean code always looks like it was written by someone who cares." — Michael Feathers
- "You know you are working on clean code when each routine you read turns out to be pretty much what you expected." — Ward Cunningham
## How to Use This Skill in a Session
When generating, reviewing, or refactoring code, work in this order:
1. **Name first.** Before writing a function body, confirm the name tells you what it does and why. If you cannot name it, you do not yet understand it.
2. **Extract till you drop.** "A function does one thing if, and only if, you cannot extract another function from it." Keep extracting until you cannot.
3. **Keep diffs honest.** When refactoring, do not also change behavior. When adding a feature, refactor *before* or *after*, never *during*.
4. **Prefer tests first** for non-trivial logic. If infeasible, write them immediately after. See [references/tdd.md](references/tdd.md).
5. **Respect boundaries.** Business rules must never depend on frameworks, databases, or UIs. See [references/architecture.md](references/architecture.md).
6. **Prefer polymorphism to conditionals** for anything that varies by type — place if/else/switch in a factory that creates polymorphic objects. See [references/paradigms.md](references/paradigms.md).
7. **Reread as a stranger.** Before declaring a task done, reread the code as if you had not written it.
## Deeper References
When the task calls for it, load the matching reference file:
- **[references/solid.md](references/solid.md)** — The five SOLID principles (SRP, OCP, LSP, ISP, DIP), their origins in Parnas (1972), Meyer (1988), Liskov (1987), their 2020 re-affirmation, and the component principles (REP, CCP, CRP, ADP, SDP, SAP). Load when designing a class, module, or microservice boundary.
- **[references/architecture.md](references/architecture.md)** — Clean Architecture: the Dependency Rule, concentric layers, Screaming Architecture, why "the database is a detail," Ivar Jacobson's use-case foundation. Load when structuring a new service, deciding what a microservice should own, or untangling framework coupling.
- **[references/tdd.md](references/tdd.md)** — The Three Laws of TDD, F.I.R.S.T., canonical test taxonomy (unit/acceptance/integration/system/micro/functional), test doubles, Chicago vs. London schools, fragile tests, the Transformation Priority Premise, the Cycles of TDD. Load when writing or reviewing tests.
- **[references/paradigms.md](references/paradigms.md)** — The three programming paradigms (structured, OO, functional), the reductionist definitions Uncle Bob uses for each, the Data/Object Anti-Symmetry (why DTOs are not objects), polymorphism as the heart of OO, if-else-switch refactoring, why FP and OO are orthogonal not exclusive. Load when the task involves choosing between procedural and OO style, writing code in a functional language, refactoring switch statements, or handling persistence.
- **[references/craft.md](references/craft.md)** — The craftsmanship ethic: mess vs. technical debt, Martin's First Law of Documentation, Saying No, estimation, pairing guidelines, "Going Fast" vs. "Speed Kills," the "Screaming Architecture" mindset applied to whole projects. Load when the task raises professional-judgment questions.
- **[references/oath.md](references/oath.md)** — The Programmer's Oath. Load when the task raises a question of professional responsibility (shipping under pressure, accumulating "temporary" hacks, padding estimates, degrading code to hit a deadline).
The remaining sections are the core rulebook for code at the function and class level. Scan them against anything you produce.
---
## 1. Meaningful Names
Names are the single highest-leverage lever for readability. From Tim Ottinger's naming rules, expanded in the book:
- **Use intention-revealing names.** `int d;``int elapsedTimeInDays;`. Names should answer: *What is this? Why does it exist? How is it used?*
- **Avoid disinformation.** Don't call something `accountList` unless it truly is a List. Don't use lowercase `l` or uppercase `O` as variable names (look like 1 and 0).
- **Make meaningful distinctions.** `productInfo` vs. `productData` is noise. `a1`, `a2`, `a3` is a red flag.
- **Use pronounceable, searchable names.** `genymdhms` is bad. Single letters are acceptable only for tiny local scopes.
- **Class names are nouns** (`Customer`, `WikiPage`, `AddressParser`). **Method names are verbs** (`postPayment`, `deletePage`, `save`).
- **Do not encode types.** Skip Hungarian notation, `m_` prefixes, `I` prefixes for interfaces.
- **Ubiquitous language.** Use the business domain's vocabulary. If the domain says "policyholder," do not name it `user`.
- **Pick one word per concept.** Standardize `fetch` vs. `retrieve` vs. `get`. Same for `controller` vs. `manager` vs. `driver`.
- **Add meaningful context, and no more.** Scattered `firstName`/`street`/`city` need an `addr_` prefix or an `Address` type.
## 2. Functions
> First rule: functions should be small. Second rule: smaller than that.
- **Target ~20 lines, often far fewer.** If you cannot see the whole function without scrolling, it is too long.
- **Do one thing.** *Operational definition:* a function does one thing if, and only if, you cannot extract another function from it (Uncle Bob, "Extract till you drop," 2009).
- **One level of abstraction per function.** The Step-Down Rule: public high-level functions at top, calling slightly lower-level helpers, and so on. Reading top to bottom should feel like descending a staircase.
- **Extract till you drop.** Most programmers stop far too early. Extract until you cannot.
- **Descriptive names beat short names.** A long descriptive name is better than a long descriptive comment.
- **Few arguments.** 0 ideal. 12 fine. 3 suspect. 4+ almost always means a struct or a split.
- **No flag arguments.** `render(true)` is terrible. Split into `renderForSuite()` and `renderForSingleTest()`.
- **No hidden side effects.** A function named `checkPassword` must not also initialize a session.
- **Command-Query Separation.** A function either *does* something or *answers* something, never both.
- **Tell, don't ask.** Alan Kay's original OO concept: cells in a biological system tell each other what to do; they do not ask for state and decide. Neurons, hormones — all tellers.
- **Prefer exceptions (or Result types) to error codes.**
- **Extract try/catch bodies.** Each should be a single function call.
- **Avoid switch statements** in business logic. See [references/paradigms.md](references/paradigms.md) for the factory+polymorphism pattern.
- **Don't Repeat Yourself.** Duplication is the root of many evils.
**Example — doing one thing:**
Bad:
```
def process_order(order):
if not order.items:
raise ValueError("Empty")
total = sum(i.price * i.qty for i in order.items)
total *= 1.1 # tax
send_email(order.customer, f"Total: {total}")
db.save(order, total)
return total
```
Clean:
```
def process_order(order):
validate(order)
total = calculate_total_with_tax(order)
notify_customer(order, total)
persist(order, total)
return total
```
## 3. Comments
> "Don't comment bad code — rewrite it." — Brian Kernighan
Every comment represents a failure to make the code self-explanatory. Before writing a comment, ask: *can I rename or extract to make this unnecessary?*
**Good comments (rare but valuable):**
- Legal headers (when required).
- Informative comments you cannot encode in names (regex explanations, format specs, wire protocol details).
- Explanation of **intent***why*, not *what*. Why this ordering, why this tradeoff, why this workaround.
- Clarification of obscure arguments or return values you cannot rename.
- Warnings of consequences ("this test takes two hours to run").
- TODOs — prune regularly; a stale TODO list is worse than none.
- Public API documentation (Javadoc, rustdoc, TSDoc, etc.).
- **Genuine complexity that resists expression in code.** Uncle Bob's own "Necessary Comments" (2017) example: a "choked function" (throttled cache wrapper) required a timing diagram in the test comments because no amount of naming or extraction could communicate the six interleaved test cases. Rare — but it happens.
**Bad comments — delete on sight:**
- Mumbling (written for yourself, unclear to others).
- Redundant (restates the code).
- Misleading (out of date or wrong — actively harmful).
- Mandated (comment-every-function policies produce noise).
- Journal/changelog (that's what git is for).
- Noise (`// default constructor`).
- Commented-out code (delete it; git remembers).
- Closing-brace comments (`} // end if`) — your function is too long.
- Attributions (`// added by Rick`) — `git blame` exists.
**Martin's First Law of Documentation** (from *Agile Software Development: PPP*): Produce no document unless its need is immediate and significant. Note the scope: *documents*, not code comments. Agile is not the rejection of documentation — that is "flawed religious behavior." Documentation earns its keep on a prioritized, ROI basis.
## 4. Formatting
**Vertical formatting — the newspaper metaphor:**
- Top of file: high-level concept. Details grow as you scroll.
- Related concepts stay vertically close.
- Dependent functions: caller above callee (the Step-Down Rule).
- Blank lines separate concepts, not pad.
**Horizontal formatting:**
- Keep lines readable (~100120 chars).
- Do not align assignments artificially.
- Use indentation consistently; never collapse a multi-branch `if`/`while` onto one line.
- Follow the team's standard. Consistency within a project beats any individual preference.
**Indentation is an abstraction-level signal.** Ideal functions have zero indentation beyond the function body; one or two levels (one if/while, one try) is acceptable. Deeper nesting usually means you have missed an extraction.
## 5. Objects and Data Structures
**Data/Object Anti-Symmetry** (Chapter 6, *Clean Code*):
- **Object:** a set of functions that operate on **implied** data. Data exists but is hidden.
- **Data structure:** a set of data elements operated on by **implied** functions. Data is exposed; functions are not specified by the structure itself.
These are **complements**, not siblings. Consequences:
- DTOs are data structures, not objects.
- Database tables are data structures, not objects.
- "ORM" is a misnomer — there is no real mapping between tables and objects.
- **The axis of expected change determines the style.** If you expect more new functions than new types, prefer procedural style (data structures + functions). If you expect more new types than new functions, prefer OO (classes + polymorphism). The Visitor pattern bridges the two.
Other rules:
- **Law of Demeter — don't talk to strangers.** A method `f` of class `C` should only call methods of: `C` itself, objects it creates, objects passed as arguments, or objects it holds as fields. Avoid train wrecks: `a.getB().getC().doSomething()`.
- **Tell, don't ask.** Instead of asking for state and deciding, tell the object to do the work.
More on this in [references/paradigms.md](references/paradigms.md).
## 6. Error Handling
- **Use exceptions (or Result types), not return codes.**
- **Write try-catch-finally first** when an operation can fail. It defines the transactional scope.
- **Provide context with exceptions.** Wrap third-party exceptions in your own types.
- **Define exception classes by the needs of the caller**, not by implementation detail.
- **Do not return null.** Return empty collections, use Option/Result/Maybe, or throw. Null checks pollute callers.
- **Do not pass null.** If a function cannot handle null, do not accept it. Fail fast at the boundary.
## 7. Boundaries
- **Wrap third-party APIs in adapters.** Your code talks to the adapter, not the library. Localizes changes when the library upgrades or is replaced.
- **Write learning tests** when exploring a new library: small, focused tests that probe its behavior. When the library upgrades, they tell you what broke.
- Keep boundaries clean so replacing a dependency is a localized change, not a project-wide rewrite.
- The big structural story is in [references/architecture.md](references/architecture.md).
## 8. Tests
See [references/tdd.md](references/tdd.md) for the full treatment. Essentials:
**Three Laws of TDD:**
1. Do not write production code until you have a failing test.
2. Do not write more of a test than is sufficient to fail.
3. Do not write more production code than is sufficient to pass.
**F.I.R.S.T.:** Fast, Independent, Repeatable, Self-validating, Timely.
**Michael Feathers' definition of legacy code:** *Legacy code is code without tests.* Uncle Bob calls Feathers's *Working Effectively with Legacy Code* "the only book I know of that addresses this topic."
Test code is first-class. Hold it to the same clarity bar as production code.
## 9. Classes
- **Small.** For functions we counted lines. For classes we count **responsibilities**.
- **Single Responsibility Principle.** The formulation has evolved: "do one thing" → "one reason to change" → most recently (Clean Architecture, 2017) "responsible to one, and only one, **actor**" (where actor is a person or tightly coupled group). See [references/solid.md](references/solid.md).
- **Cohesion.** Methods should use most of the instance variables. Low cohesion = two classes in a trench coat.
- **Organize for change.** Isolate volatile concepts behind interfaces so changes do not ripple.
- **Class organization order:** public static constants → private static variables → private instance variables → public functions → private helpers (grouped with their public caller).
## 10. Systems
- **Separate construction from use.** Startup code (wiring dependencies) lives in one place; business logic does not touch it.
- **Dependency injection** over hardcoded `new` expressions deep in business logic.
- **Cross-cutting concerns** (logging, transactions, security, metrics) belong in middleware/aspects/interceptors, not scattered through the domain.
- Let architecture **emerge** as the system grows, but defend the seams — the places where modules plug together — at every stage.
- See [references/architecture.md](references/architecture.md).
## 11. Emergent Design — Kent Beck's Four Rules
A design is *simple* if, in priority order, it:
1. **Runs all the tests.**
2. **Contains no duplication.**
3. **Expresses the intent of the programmer.**
4. **Minimizes the number of classes and methods.**
Order matters. Never sacrifice test coverage to reduce class count.
---
## 12. Code Smells — A Review Checklist
Scan for these before declaring code done.
**Function smells**
- Too many arguments (>3).
- Flag arguments (booleans that switch behavior).
- Selector arguments (enums that drive internal switches).
- Dead parameters, dead code paths.
- Obscure intent — body reads as a sequence of mystery steps.
- Misplaced responsibility — function lives on the wrong class/module.
- Inappropriate static — method should be polymorphic.
**Class smells**
- Feature envy (method uses another class's data more than its own).
- Large class / god class.
- Too many responsibilities.
- Inappropriate intimacy between classes.
- Lazy class — no longer pulls its weight.
**General smells**
- **Duplication** — the #1 smell; hunt it everywhere.
- Magic numbers or strings — extract named constants.
- Inconsistent names for the same concept.
- Artificial coupling — things glued together that don't belong.
- Negative conditionals (`if (!isNotEmpty)`) — invert.
- **If-else or switch chains on type** — replace with factory + polymorphism; see [references/paradigms.md](references/paradigms.md).
- Dead code.
- Vertical separation — variables declared far from use.
- Boundaries violated — business logic importing framework classes, entities reaching the DB.
**Name smells**
- Non-descriptive (`data`, `info`, `handle`, `process`).
- Names not matching level of abstraction.
- Mental mapping required (decode `r`, `q`, `tmp`).
- Encoded names (Hungarian, type prefixes).
- Side info stuffed into names ("the `u` here is because…").
**Test smells**
- Insufficient tests.
- Skipped or ignored tests accumulating.
- Tests dependent on execution order.
- Tests that test the framework, not your code.
- Slow tests (they will stop being run).
- Over-mocking — tests break on refactor without any real regression.
---
## A Note on Disagreement
Clean Code is not scripture. Uncle Bob himself has revised definitions across his career (SRP has three formulations; LSP was initially taught as about inheritance and later clarified as about subtyping). He has also publicly recommended John Ousterhout's *A Philosophy of Software Design* (2022) while noting disagreements with Ousterhout on two key Clean Code points:
- Ousterhout prefers larger functions with "deep implementations behind narrow interfaces."
- Ousterhout advocates more use of comments.
These are honest, ongoing debates. The skill's default aligns with Uncle Bob; you are expected to think about the tradeoffs, not apply the rules blindly. When a codebase's structure makes the opposite choice more readable for the reader-in-context, the reader wins.
## One More Thing
Clean code is not a destination — it is a **practice**. Every function is an opportunity to practice. The single most important lesson is not any rule; it is the **attitude of caring enough to leave the code better than you found it**.
The professional commitment behind all of this is captured in [references/oath.md](references/oath.md) and elaborated in [references/craft.md](references/craft.md).
+66
View File
@@ -0,0 +1,66 @@
# Sources
This skill was built from material crawled from the Uncle Bob source network you provided. This file is an honest accounting of what was fetched and what wasn't, so you can verify the provenance of any claim and follow up if something seems off.
## Fully read (body captured)
### Course outlines (cleancoder.com/files/)
- cleanCodeCourse.md
- cleanArchitectureCourse.md
- tdd.md
- advanced-tdd.md
- clean-agile.md
- immersion.md
### Blog posts (blog.cleancoder.com) — full or near-full body
- The Clean Architecture (2012-08-13)
- The Programmer's Oath (2015-11-18)
- The Single Responsibility Principle (2014-05-08, partial)
- The Open Closed Principle (2014-05-12, via search)
- OO vs FP (2014-11-24, via search)
- First-Class Tests (2017-05-05, via search)
- Testing Like the TSA (2017-03-06, via search)
- Test Contra-variance (2017-10-03, via search)
- Necessary Comments (2017-02-23)
- Solid Relevance (2020-10-18)
- if-else-switch (2021-03-06, via search)
- Screaming Architecture (2011-09-30, via search)
- A Little Architecture (2016-01-04, via search)
- Classes vs Data Structures (2019-06-16, via search)
- Functional Classes (2023-01-18, via search)
- Loopy (2020-09-30, via search)
### Other sources
- cleancoder.com/books (full — Uncle Bob's recommended-reading list with annotations)
- sites.google.com/site/unclebobconsultingllc/.../articles (index + inline excerpts of ~40 articles)
- sites.google.com/.../articles/one-thing-extract-till-you-drop (full body after fighting Google Sites' massive-nav rendering)
- butunclebob.com old-wiki pages via web_search:
- ArticleS.UncleBob.PrinciplesOfOod (SRP evolution, component principles)
- ArticleS.UncleBob.AgilePeopleStillDontGetIt (shipping untested code is unacceptable)
- ArticleS.UncleBob.OnDocumentation (Martin's First Law of Documentation)
- ArticleS.UncleBob.P2M2 (pairing guidelines)
- ArticleS.UncleBob.IuseVisitor (Visitor pattern as SRP-preserver)
- ArticleS.MichaelFeathers.LiskovSubstitutionInDynamicLanguages (LSP in dynamic languages)
## Titles only (index excerpts captured, body not fetched)
~120 additional blog.cleancoder.com posts — titles, dates, and (for ~30 of them) 13 sentence excerpts from Anthropic web_search results. Topics include: The Cycles of TDD, The Little Mocker, When to Mock, Monogamous TDD, Test Induced Design Damage?, The Transformation Priority Premise (+ three follow-ups), Three Paradigms, Why Clojure, FP Basics E1E4, The Principles of Craftsmanship, The Humble Craftsman, Saying No, The Churn, The Lurn, NO DB, Clean Micro-service Architecture, Framework Bound, 'Interface' Considered Harmful, The Little Singleton, Type Wars, TDD Doesn't Work, TDD Harms Architecture, and roughly 90 others (including essays on hiring, certification, industry culture, and a handful of politically-themed posts).
The remaining ~40 Google Sites top-level articles — again, titles captured with some inline excerpts, bodies not individually fetched due to Google Sites' nav-heavy rendering (each fetch costs ~20K tokens in nav alone before the article body begins).
## Not fetched
- butunclebob.com front page and the full wiki structure beyond the few articles surfaced via web_search. The old wiki is largely dormant; the direct URLs I tried returned empty pages; content was reachable only via search result excerpts.
- cleancoders.com video-episode descriptions (peripheral; the book/blog material covers the same ground).
- Uncle Bob's Twitter/X archive (referenced in a few places but I fetched only material that appeared in search results).
## What this means for the skill
- Core-principle claims (the SOLID wording, the Clean Architecture layers, the TDD three laws, the F.I.R.S.T. attributes, the test taxonomy, the Data/Object Anti-Symmetry, the three paradigms, the oath) are backed by directly fetched body text or search-excerpt evidence.
- Some narrower historical and biographical claims (the Parnas 1972 citation, Liskov 1987 date, Meyer 1988 OOSC citation, attribution of specific phrasings to specific articles) were corroborated across multiple sources but not verified at their original citations. If any of them matters for a formal use, double-check against the original paper.
- The sections on ~120 unfetched blog posts are not directly represented in the skill — the skill is built from the ~25 sources I did read fully, plus the consistent pattern of excerpts from the rest.
If there's a specific blog post from the unfetched list that you want me to integrate, point me at it and I'll fetch it directly and revise the relevant reference file.
@@ -0,0 +1,144 @@
# Clean Architecture
When to load this reference: when structuring a new service or module, drawing boundaries between components, deciding what a microservice should own, untangling framework coupling, reviewing a system for testability and longevity, or choosing a top-level folder structure.
Clean Architecture is Uncle Bob's synthesis of Hexagonal Architecture (Alistair Cockburn), Onion Architecture (Jeffrey Palermo), DCI (Coplien & Reenskaug), and BCE (Ivar Jacobson, *Object-Oriented Software Engineering*, 1992). They differ in detail but agree on one goal: **separation of concerns by layering**, with business rules isolated from delivery mechanisms.
The foundational insight comes from Jacobson: **architectures are structures that support the use cases of the system.** Not frameworks. Not databases. Not UIs. Use cases.
---
## What a Clean Architecture Produces
A system that is:
1. **Independent of frameworks.** Frameworks are tools, not constraints.
2. **Testable.** Business rules tested without UI, DB, web server, or any external element.
3. **Independent of UI.** The UI can be replaced (web → console → CLI → TUI) without touching business rules.
4. **Independent of database.** Swap PostgreSQL for MongoDB, ClickHouse, or in-memory without rewriting domain logic.
5. **Independent of any external agency.** The core business rules know nothing about the outside world.
**The database is a detail.** So is the web. So is the framework. These are the most common sources of architectural rot because developers mistake them for foundations.
> "The database is merely an IO device. It happens to provide some useful tools for sorting, querying, and reporting but those are ancillary to the system architecture." — *A Little Architecture* (2016)
---
## The Dependency Rule
The one rule that makes everything else work:
> **Source code dependencies point only inward, toward higher-level policy.**
- Nothing in an inner layer may name anything from an outer layer — no function, class, variable, or data format.
- Data formats convenient for the outer layer (ORM row struct, JSON DTO) must not leak inward.
- Control flow may cross boundaries in either direction, but *source dependencies* point only inward. The Dependency Inversion Principle (see [solid.md](solid.md)) is the mechanism that makes this possible when control flow runs outward.
When this rule is obeyed, external details — databases, frameworks, UIs — become replaceable plugins.
---
## The Four Concentric Layers
Schematic. You may need more or fewer for a given system, but the Dependency Rule always applies.
### 1. Entities (innermost)
Encapsulate **enterprise-wide** business rules. An entity can be a class with methods or a data structure plus functions — style choice.
- Entities know nothing about applications, use cases, frameworks, or anything outside.
- For single applications (no "enterprise"), these are your core business objects.
- These are the least affected by operational change. Changes to page navigation, auth mechanisms, or DB schemas must not reach here.
### 2. Use Cases
Encapsulate **application-specific** business rules. Use cases orchestrate entities to accomplish the application's goals.
- A use case directs entities; it does not contain enterprise-wide rules itself.
- Changes to the application's *behavior* land here. Changes to externalities do not.
- Simple request/response data structures (not entities) flow in and out.
### 3. Interface Adapters
Convert data between the format convenient for use cases/entities and the format convenient for external agencies.
- MVC's Controllers, Presenters, and Views live here.
- All SQL lives here (if the database is SQL). Nothing inside knows about SQL.
- DTOs are translated into domain types and back here.
### 4. Frameworks and Drivers (outermost)
The web framework, the database, the message broker, the file system. Glue code only — you do not write much application logic here. Details live here because details change, and the outer ring is where change is cheap.
---
## Crossing Boundaries
When control flow needs to run outward — a use case needs to call a presenter — a direct call violates the Dependency Rule (the inner layer names something in the outer layer).
**Solution: the Dependency Inversion Principle.** The use case calls an interface (an "output port") defined in its own layer. The outer-layer presenter implements that interface. Control flows outward; source dependencies point inward. Same pattern works for repositories, gateways, any outward call.
---
## What Crosses Boundaries
Only **simple data structures** cross boundaries:
- Plain structs or Data Transfer Objects.
- Primitive arguments in function calls.
- Maps/dictionaries, when appropriate.
Never pass Entity objects or ORM row objects across boundaries — that couples layers. Translate to the format most convenient for the inner circle at every boundary crossing.
---
## Screaming Architecture
From the 2011 blog post of the same name. The top-level layout of a project should *scream* what the system does, not what framework it uses.
**The blueprint metaphor.** Imagine looking at the blueprints of a building. A single-family residence: front entrance, foyer, living room, dining room, kitchen. A library: grand entrance, check-in clerks, reading areas, galleries of bookshelves. A shopping mall: corridors, store bays, parking lots. You can tell what kind of building it is before you see any sign.
What does *your* application architecture scream?
**Bad top-level:** `controllers/`, `models/`, `views/`, `services/`. Tells you the system uses MVC. Tells you nothing about what the system is for.
**Good top-level:** `billing/`, `shipping/`, `catalog/`, `fraud_detection/`. Now you know what the system does.
**Why it matters:** A good architecture lets you defer decisions about Rails, Spring, Hibernate, Tomcat, MySQL, or React until much later in the project. A framework-centric top-level locks those decisions in day one, and also makes the code base mute about its own purpose. The web is a *delivery mechanism*; the database is a *detail*. Neither should dominate your system structure.
If a stranger cannot tell from the directory structure whether they are looking at an e-commerce platform or a hospital records system, the architecture is failing at the highest level.
---
## Component Principles
Once modules are organized, they group into **components** — independently deployable units (libraries, services, jars, crates). Two sets of principles govern them.
### Component Cohesion
- **REP — Reuse/Release Equivalence Principle.** The unit of reuse is the unit of release.
- **CCP — Common Closure Principle.** Group together classes that change for the same reasons at the same times. (SRP at component scale.)
- **CRP — Common Reuse Principle.** Classes used together belong together; classes not used together don't. (ISP at component scale.)
These three pull in different directions — the **tension diagram** is a triangle and component design is an ongoing balance. Early-stage projects lean toward REP+CCP (ship quickly, include more); mature, widely-reused components shift toward CRP (exclude what clients don't need).
### Component Coupling
- **ADP — Acyclic Dependencies Principle.** The dependency graph among components must have no cycles. Break cycles with DIP or by extracting a new component both sides depend on.
- **SDP — Stable Dependencies Principle.** Depend in the direction of stability.
- **SAP — Stable Abstractions Principle.** Stable components should be abstract; volatile components should be concrete.
---
## Applying This in Practice
- **"NO DB" and "NO Web" are valid starting positions.** Business rules should be expressible, testable, and useful before either is chosen.
- **Frameworks are tools, not partners.** Wrap them. Keep `import django` or `import axum::Router` out of the core. (Uncle Bob's 2014 "Framework Bound" is a full rant on this.)
- **Not every project needs four full circles.** Small projects may collapse Entities and Use Cases into one layer. The Dependency Rule still applies whatever the count.
- **The seams matter most.** Architecture lives at the boundaries between components. Defend them at every review — once they rot, replacing a dependency stops being a weekend task and becomes a six-month project.
- **Dialog from *A Little Architecture* (2016).** An aspiring architect says they want to make decisions about databases, frameworks, and webservers. Uncle Bob's response: "Oh. Well, then you don't want to become a Software Architect after all." The architect's job is to make decisions that let you **defer** the irrelevant decisions.
---
## Architecture and Agility
From "The Scatology of Agile Architecture" (2009): Agile does *not* mean no up-front architecture. The myth that you evolve architecture from zero is, in Uncle Bob's words, "horse shit." Good teams do enough architecture up front to get the seams right, then let the details emerge inside those seams. See [craft.md](craft.md) for more on this.
@@ -0,0 +1,135 @@
# The Craftsmanship Ethic
When to load this reference: when the task raises questions of professional judgment — estimation, deadline pressure, sloppy code accumulating, pairing, saying no to bad requests, or when the user invokes "technical debt" or "mess" or "craftsmanship."
The behaviors in *Clean Code* and *Clean Architecture* are not ends in themselves. They are instrumental to a larger ethic that Uncle Bob has been refining since the early 2000s: the software craftsmanship movement, which evolved into the Programmer's Oath (see [oath.md](oath.md)) and the 2022 book *Clean Craftsmanship*. This reference captures the non-code parts of that ethic that still materially affect how Claude should behave when writing or reviewing code.
---
## Clean Code Is a Practice, Not a Destination
From many posts, consolidated:
- Every function is an opportunity to practice. You don't reach "clean" and stop.
- The **Boy Scout Rule** is the daily discipline: leave each module cleaner than you found it, even if just by renaming one variable.
- "The only way to go fast is to go well." Dirty code does not trade speed for quality; it trades illusory short-term speed for enormous long-term slowness. This is the Productivity Roller-Coaster: feel fast for weeks, slow to a crawl over months.
- From *Going Fast*: "Fast" is a property you get by being disciplined, not by skipping discipline.
- From *Speed Kills*: conversely, the illusion that you can get fast by cutting corners almost always kills a project.
---
## A Mess Is Not Technical Debt
**This distinction matters.** People conflate them, and the conflation is a way to make sloppiness sound respectable.
**Ward Cunningham's Technical Debt (the original, 1992):** a **deliberate, considered** engineering trade-off when a schedule or learning situation justifies using a suboptimal design temporarily. You know what the right design is; you are choosing the wrong one now, *with intent*, and you will fix it later. Example: initial website uses server-rendered pages because there's no time to build an Ajax framework.
**A Mess:** bad code written by someone who did not do the work to understand the problem, did not refactor, did not test, did not think. It is not "debt" because it was never a considered choice — it is just poor craftsmanship.
From "A Mess is not a Technical Debt" (2009): calling a mess "technical debt" launders bad craftsmanship as if it were responsible engineering. It is not. When refusing to ship a mess, do not accept the framing that "we're just taking on some debt." Debt is deliberate; a mess is sloppy.
**Fowler's four quadrants of debt** (prudent/imprudent × deliberate/inadvertent) are a better map:
- Deliberate+prudent: the original Cunningham case ("we must ship now, we'll fix X next sprint").
- Deliberate+imprudent: "we don't have time for design" (toxic, not actually debt).
- Inadvertent+prudent: "now I know how we should have done it" (honest learning).
- Inadvertent+imprudent: plain-old-mess masquerading as debt.
---
## Saying No
From "Saying No!" (2009) and elaborated in *The Clean Coder*: professionals have an obligation to refuse impossible or unethical demands.
- When a manager asks for something that cannot be done correctly in the time allowed, the professional answer is "no, but here's what I can do," not "yes" followed by silent quality compromise.
- "Yes and then failing to deliver" is worse than "no" — the manager loses the ability to plan around reality.
- Professionals push back on their own estimates. If pressure makes you shorten a number you believe, you have stopped being the expert the organization pays you to be.
Applied to Claude: when a user asks for something that cannot be done well under the stated constraints (skip the tests, skip the error handling, ship something that will crash), the right response includes the pushback. Offer what you *can* deliver cleanly, not a degraded version of what was asked for.
---
## Honest Estimates
From "Why is Estimating so Hard?" (2012) and related posts:
- Estimates are **probability distributions, not numbers.** Give a range: optimistic, nominal, pessimistic. Three-point estimates are honest; single-point estimates almost always compress uncertainty.
- "I don't know yet, let me do a spike" is a professional answer. "I'll have it by Friday" said under duress without real confidence is not.
- An estimate is not a commitment; commitments come from negotiating after estimates are honestly given.
---
## On Documentation
**Martin's First Law of Documentation** (from *Agile Software Development: PPP*): "Produce no document unless its need is immediate and significant."
This is often misread as "Agile means no documentation." It does not. From the butunclebob.com wiki:
> "Agile Development is NOT development without documentation. Rejecting documentation in the name of 'Agility' is a flawed religious behavior. It is just as flawed as uncritically accepting the production of dozens of different documents."
Documentation, like any engineering activity, is prioritized by ROI. Create documents that more than pay back the effort to produce them. Skip documents written because policy requires them but no one will read them.
What counts as documentation:
- API docs (rustdoc, TSDoc, javadoc) — high value, close to code.
- Architecture decision records (ADRs) — capture *why* decisions were made.
- Onboarding / how-to guides — pay back every time a new person joins.
- Specs for important flows — pay back every time a flow breaks.
What does not:
- Status reports that recapitulate information already in the tracker.
- Design documents written after implementation that no one will read.
- Comments that restate the code.
---
## Pairing Guidelines
From "Pairing Guidelines" (2021) and earlier posts:
- Pairing is a **tool**, not a religion. Use it when it works; don't when it doesn't.
- Mature agile teams pair maybe 5070% of the time, not 100%.
- Some problems require "time, focus, and silence" to study before attacking. Pairing on those is worse than solo.
- Pair at the start of a story to align direction; solo for deep-focus passages; reunite to review.
- The strategy "separate the syntax issues from the semantic issues" is a useful pattern when stuck as a pair — refactor the mechanical noise (parsing, config, regex) into a helper module so the core algorithm can be reasoned about on its own.
---
## Shipping Under Pressure
From "AgilePeopleStillDontGetIt" (2006) and "We must ship now and deal with consequences" (2009):
- "It is completely unacceptable to release code that you aren't sure works. Either make sure it works, or don't ship it. Period."
- "A feature that crashes is much worse than a feature that doesn't exist. A feature that doesn't exist will defer revenue. A feature that crashes makes enemies out of customers."
- "Our customers interpret features as promises. When we release a feature we are promising that it works. When it crashes we have broken that promise."
- "Shipping untested software is shipping something unfinished and your customers will force you to finish it. The pressure will be higher at orders of magnitude if you finish it AFTER you have shipped it."
Applied to Claude: when asked to ship quickly and drop tests, the honest response is that the tests aren't slowing you down; they are the only way to ship correctly. "Going fast" without tests produces code that will return tenfold in debugging and firefighting over the next weeks.
---
## Professionalism Is Not Rigid Formalism
From "Why the sea is boiling hot" (2009) — the closing statement of Uncle Bob's 2009 Rails Conf keynote:
> "Professionalism does not mean rigid formalism. Professionalism does not mean adhering to bureaucracy. Professionalism is **honor**. Professionalism is being honest with yourself and disciplined in the way you work. Professionalism is not letting fear take over."
Honor and discipline. Not process for its own sake. The rules in this skill are tools for being disciplined; they are not a rulebook to hide behind.
---
## The Tricky Bit
From "The Tricky Bit" (2010): a British MP flew the Concorde and complained to the designer that going supersonic "didn't feel any different at all." The designer beamed: "Yes, that was the tricky bit."
Clean code, good architecture, solid tests — when they are working, the reader doesn't notice. The absence of friction is the product. Code that *announces* how clever it is, how much architecture it has, how sophisticated its patterns are, is usually the opposite of clean. The goal is invisibility — the reader moves through the code and feels nothing but understanding.
---
## When Claude Should Invoke Any of This
- **User wants to skip tests "just this once":** reference the "A Mess is not Debt" framing and the shipping-under-pressure material.
- **User wants a speculative number instead of a range:** offer a range and explain why.
- **User wants you to document something they won't read:** suggest the minimum viable doc that pays its way.
- **User wants a "quick fix" that you can see will rot the module:** explain the Boy Scout Rule cost — a quick fix that makes the code worse is a negative-value change even at zero time cost.
- **User says "we're doing Agile, we don't write documentation":** redirect to Martin's First Law and the "it's about ROI" framing.
The oath ([oath.md](oath.md)) captures the promises. This file captures the attitude and the vocabulary for navigating the hard conversations where craft meets pressure.
@@ -0,0 +1,81 @@
# The Programmer's Oath
When to load this reference: when the task raises a question of professional responsibility — shipping under pressure with known defects, accumulating "temporary" hacks, padding estimates, degrading code to hit a deadline, or pushing back on a manager who is asking for the impossible.
In 2015, Uncle Bob proposed an oath for programmers, modeled loosely on the Hippocratic Oath, that captures the professional commitments behind Clean Code, Clean Architecture, and Agile practice. The oath exists because software increasingly runs civilization — cars, medical devices, infrastructure, money — and the people who write that software carry a corresponding weight of responsibility. His 2019 post "737 Max 8" is the most concrete illustration of why this matters: what happens when mission-critical software ships without the oath.
---
## The Oath
*In order to defend and preserve the honor of the profession of computer programmers, I promise that, to the best of my ability and judgement:*
1. **I will not produce harmful code.** Not code known to be defective. Not code that degrades the product. Not code that lies.
2. **The code I produce will always be my best work.** I will not knowingly allow defective behavior or defective structure to accumulate.
3. **I will produce, with each release, a quick, sure, and repeatable proof that every element of the code works as it should.** Automated tests that run fast and tell the truth.
4. **I will make frequent, small releases** so that I do not impede the progress of others.
5. **I will fearlessly and relentlessly improve my creations at every opportunity.** I will never degrade them. Each commit leaves the system at least as clean as I found it — preferably cleaner.
6. **I will do all that I can to keep the productivity of myself and others as high as possible.** I will do nothing that decreases that productivity. This is why clean code matters: dirty code taxes every future developer who reads it.
7. **I will continuously ensure that others can cover for me, and that I can cover for them.** No knowledge silos. No indispensable person. Shared ownership of the codebase.
8. **I will produce estimates that are honest** both in magnitude and precision. **I will not make promises without certainty.** "I don't know yet" is a professional answer. Padding to please is not.
9. **I will never stop learning and improving my craft.** Programming is a practice, not a credential.
---
## How This Oath Informs the Skill
The oath is not abstract ethics — it is directly wired into the practices that Clean Code, Clean Architecture, and TDD embody.
- **"Not produce harmful code"** → No flag arguments hiding branches, no null returns that hide failures, no functions with secret side effects. Clean Code, Chapter 7 (Error Handling). Mission-critical relevance: the 737 MAX is what happens when software that can kill people is built without the oath.
- **"Best work … will not allow defective structure to accumulate"** → the Boy Scout Rule. A mess is not technical debt (see [craft.md](craft.md)).
- **"Quick, sure, repeatable proof"** → TDD and F.I.R.S.T. tests. See [tdd.md](tdd.md).
- **"Frequent small releases"** → continuous integration and the Agile practices. If a release takes a day, releases are infrequent by economic necessity; fix the release process, not the schedule.
- **"Fearlessly improve"** → only possible with a test net. Without tests, every change is a gamble, so code rots by default. *Legacy code is code without tests* (Feathers).
- **"Keep productivity high"** → the whole argument for clean code. Dirty code slows the team down. "We'll clean it up later" is almost always a lie.
- **"Others can cover for me"** → pairing, code review, shared ownership, honest naming. See [craft.md](craft.md). If only one person understands the billing module, the billing module is a liability.
- **"Honest estimates"** → ranges, not points. Three-point estimates (optimistic, nominal, pessimistic). "I cannot know yet, I will know more after the spike" is honest; a number pulled from the air to calm a manager is not.
- **"Never stop learning"** → the craftsmanship attitude. Every function is practice.
---
## The Underlying Argument: Professionalism Is Honor
From Uncle Bob's 2009 Rails Conf keynote "Why the sea is boiling hot":
> "Professionalism does not mean rigid formalism. Professionalism does not mean adhering to bureaucracy. Professionalism is honor. Professionalism is being honest with yourself and disciplined in the way you work. Professionalism is not letting fear take over."
The oath is not a rulebook; it is a set of promises about the kind of engineer you intend to be. When pressure mounts and shortcuts beckon, those promises are what keep the work honest.
---
## The 737 MAX Argument
From "737 Max 8" (2019). Software increasingly operates in domains where failure kills. Cars, medical devices, aircraft, infrastructure control systems. The argument Uncle Bob makes:
- Our industry still doesn't act like a profession. There are no widely-enforced standards for competence. Anyone can ship anything.
- When failures in a civilian product only mean frustrated customers, this is tolerable. When failures mean dead people, it is not.
- Either the industry disciplines itself, or governments will do it for us — and government-imposed discipline will be crude and bureaucratic compared to what we could choose.
- The oath is a voluntary first step.
For Claude-written code, this usually doesn't feel immediate. But the oath's standards apply to any code that runs. A user asking Claude to "just ship it, we'll fix bugs later" in a payment system is asking Claude to contribute to harm the user probably hasn't imagined.
---
## When to Cite This in a Session
- **User is asking Claude to skip tests "just this once."** Clean code practice says no — the "just this once" mindset is how codebases accumulate the slow-rotting debt the oath forbids.
- **User is asking Claude to estimate something the code cannot yet answer.** Honest ranges beat false precision. "I do not know, let me find out" is honest.
- **User is under deadline pressure and proposes shipping code with known defects.** The oath is unambiguous: unknown defects happen to everyone; knowingly shipped ones are a professional failure.
- **User asks Claude to produce code that lies** — silently swallows errors, hides side effects, misrepresents state. Decline and explain why.
- **A proposed change would make future developers' lives worse** for a short-term gain. Promise 6 of the oath is explicitly about not decreasing others' productivity.
- **User is shipping to a safety-critical domain** and cutting corners. Name the risk explicitly; the user may not have considered it.
The oath is not a stick to beat users with. It is a reminder of the stakes that clean practice is trying to address, and a useful touchstone when a decision has no obvious technical answer. Lead with helpfulness; invoke the oath when helpfulness would mean producing work Claude should not be producing.
---
## Related Reading
- [craft.md](craft.md) — the surrounding ethic in more detail: mess vs. debt, saying no, estimation, pairing, the "tricky bit."
- Uncle Bob's *The Clean Coder* (2011) — the book-length treatment of professional ethics in software. Unlike *Clean Code*, it is about behavior rather than technique.
- Uncle Bob's *Clean Craftsmanship* (2021) — the discipline-focused sequel to *Clean Code*, integrating TDD, refactoring, simple design, and the oath.
@@ -0,0 +1,161 @@
# Programming Paradigms
When to load this reference: when choosing between procedural and OO style, writing code in a functional language, refactoring switch statements, handling persistence, or when the user asks about OO vs FP, design patterns, or Clean Code's chapter on objects and data structures.
Uncle Bob's reductionist framing of the three paradigms is a powerful lens for reasoning about code shape. Each paradigm imposes **discipline** by **taking something away** from the programmer.
---
## The Three Paradigms
Each paradigm is defined by what it *forbids*, not by what it enables. This is Dijkstra-style reasoning: fewer primitives mean fewer ways to be wrong.
### Structured Programming
- **Forbids:** `goto` (direct transfer of control).
- **Provides:** Sequence, Selection (if/else), Iteration (while). Dijkstra proved any algorithm can be expressed with just these three.
- **Why:** Dijkstra's 1968 letter "Go To Statement Considered Harmful." Unrestricted `goto` makes programs impossible to reason about. Restricted control flow is provably correct for sequence, selection, iteration; not provably correct with arbitrary `goto`.
- **Status today:** Won so completely that most developers don't even realize they're using it. Modern languages don't have `goto` (or discourage it).
### Object-Oriented Programming
- **Forbids:** Raw function pointers / indirect transfer of control through unmanaged pointers.
- **Provides:** Polymorphism. The language manages the function pointers for you.
- **Why:** Raw function pointers (as in C) are correct but fragile — every caller must follow conventions every time. Polymorphism provides the same runtime capability through a disciplined mechanism: objects carry their own dispatch table, set up once when the object is created.
- **The reductionist core:** OO = polymorphism. Encapsulation, methods-bound-to-data, and simple inheritance exist in C and Pascal too. **What OO uniquely gives you is convenient polymorphism.** "OO without polymorphism is not OO."
### Functional Programming
- **Forbids:** Assignment / mutation of state.
- **Provides:** Referential transparency. Same inputs → same outputs, always, everywhere.
- **Why:** Shared mutable state is the source of most concurrency bugs and most "action at a distance" reasoning failures. Forbidding it means state changes are explicit and localized.
- **The reductionist core:** FP = referential transparency. Higher-order functions exist in OO languages too (Smalltalk, etc.). What FP uniquely gives you is the guarantee that a function call cannot change anything you didn't pass to it.
### Why "Three Paradigms" Matters
These are **orthogonal**, not competing. Each removes a different freedom:
| Paradigm | Discipline on | Mechanism |
|---|---|---|
| Structured | Direct transfer of control | No `goto` |
| OO | Indirect transfer of control | Polymorphism |
| FP | Assignment | Referential transparency |
A language can (and modern ones often do) impose all three disciplines at once. You can write OO code functionally, and you can apply SOLID inside a functional program.
---
## OO and FP Are Orthogonal, Not Exclusive
From Uncle Bob's 2014 and 2018 "FP vs OO" posts:
> "The principles of software design still apply, regardless of your programming style. The fact that you've decided to use a language that doesn't have an assignment operator does not mean that you can ignore the Single Responsibility Principle; or that the Open Closed Principle is somehow automatic."
And from his 2023 *Functional Classes* post: "Should you subdivide a functional program into classes the way you would an object oriented program? Yes. You should. Because the rules don't change just because you've chosen to use immutable data structures."
**A class, reductively:** "A group of cohesive and narrowly defined functions that operate on an encapsulated data structure. The functions may, or may not, be polymorphically deployed." This definition works in Clojure, Haskell, Rust, Java, TypeScript, Python.
**The design principles transcend paradigm:**
- SRP applies in Clojure (group functions by actor).
- OCP applies in Haskell (use abstraction, add type class instances).
- DIP applies anywhere there are modules.
- A "class" in the sense above is a cohesive namespace of related functions plus the data they operate on.
---
## Data/Object Anti-Symmetry
From Chapter 6 of *Clean Code* and elaborated in the 2019 blog post "Classes vs. Data Structures."
**Two definitions that complement each other:**
- **Object:** A set of functions that operate on **implied** data. Data exists but is hidden. Callers see only functions.
- **Data structure:** A set of data elements operated on by **implied** functions. Data is exposed. Functions exist but are not specified by the structure.
They are **diametric opposites**. You cannot fully be both.
### Consequences
- **DTOs are data structures, not objects.**
- **Database tables are data structures, not objects.**
- **"ORM" is a misnomer.** There is no mapping between database tables and objects. ORMs map tables to data structures. (This is not pedantic; it explains why ORMs have the smells they do.)
- **Polymorphism is the marker of objects.** When `shape.area()` dispatches dynamically to the Circle or Square implementation, you are doing OO. When `area(shape)` is a free function with `match shape { Circle => …, Square => … }`, you are doing procedural work.
### The Four Symmetry Rules
These tell you when to choose each style.
| | Add new FUNCTION | Add new TYPE |
|---|---|---|
| **Classes (OO)** | **Hard** — change every class | **Easy** — add one class |
| **Data structures (procedural)** | **Easy** — add one function | **Hard** — change every function |
**Choose by expected axis of change:**
- If you expect more new functions than new types → procedural style with data structures + functions (e.g., visitor pattern, pattern matching over enums, Clojure-style).
- If you expect more new types than new functions → OO style with classes and polymorphism.
- The **Visitor pattern** is procedural-style behavior over OO data — it bridges the two.
**In Rust specifically:** enums with `match` are procedural by this taxonomy (add a variant → every match must handle it); traits with implementations are OO (add an impl → no existing code changes). Neither is wrong; choose by axis of change. If new variants are rare and new operations are common, the enum wins. If new types are common, the trait wins.
---
## Polymorphism and if-else-switch
From "if-else-switch" (2021). A very common refactor:
**The pattern.** When you see an if/else chain or switch that branches by type or by "kind," replace it with:
1. A base class or interface with one method per case.
2. Concrete implementations, one per branch.
3. A **factory** that creates the right implementation based on the discriminator (this is where the if/else/switch ends up, condensed into one place).
4. The business logic calls the interface, never the discriminator.
**Runtime characteristics are identical.** If/else does a procedural lookup, switch uses a compiler-built jump table, polymorphic dispatch uses a vtable — similar performance.
**What you gain:**
- The high-level business code no longer transitively depends on every low-level case.
- Each case is its own named method, not an indented block within a branch.
- New cases = new classes (OCP).
- Independent deployment becomes possible: the high-level module and each implementation can live in separate components.
**When not to apply:** if the switch is small, stable, and not type-based (e.g., processing a small enum of flags in one place), leaving it as a switch is fine. The rule is "factor out switches on *type*," not "destroy every conditional."
---
## The Tell-Don't-Ask Style
Alan Kay's original OO conception: objects as cells in a biological system.
> "Neurons are tellers, not askers. Hormones are tellers, not askers. In biological systems, communication was half-duplex."
Instead of:
```
if account.getBalance() < amount:
throw InsufficientFunds
account.setBalance(account.getBalance() - amount)
```
Say:
```
account.withdraw(amount) // account decides if it can, and how
```
The caller stops interrogating state and deciding. The object owns the decision. This is what Law of Demeter is a weak shadow of — the deeper principle is that state should not leak out of objects.
---
## Loops and State Machines
From the 2020 "Loopy" post. Any program with nested loops can be refactored step-by-step into a Turing-style finite state machine, with tests passing at every step. This is a useful mental exercise: a nested loop is a state machine that a programmer wrote too compactly.
Practical takeaway: when a loop body is getting complex, consider extracting an explicit state (enum of states) and transitioning between them. Reads better than four nested `if`s; generalizes better; easier to test.
---
## Applying This in Practice
- **Default to OO + polymorphism** for business logic where types vary (entities, strategies, handlers). Polymorphism is the mechanism behind DIP, OCP, and Clean Architecture boundaries.
- **Default to data structures + free functions** for values, messages, and records that flow through the system. DTOs, events, API payloads, DB rows.
- **Keep the two species apart.** A "hybrid" that has both public fields and rich behavior usually gets the worst of both worlds.
- **FP is not an exception to SOLID.** Cohesion, SRP, DIP all still apply; you express them with namespaces, protocols, or type classes instead of classes.
@@ -0,0 +1,138 @@
# SOLID Principles
The five class- and module-level principles that make a codebase flexible, testable, and resistant to rot. Load when designing a new class, module, or microservice; when refactoring for flexibility; or when reviewing dependencies between units.
Uncle Bob reaffirmed in 2020 that these principles remain as relevant as they were in the 1990s, and that microservices and dynamic typing do *not* make them obsolete. The shape of software — sequence, selection, iteration — has not fundamentally changed since the first stored-program computer, and neither has the shape of good design.
The "SOLID" acronym was popularized by Uncle Bob, but most of the individual principles predate him. Understanding the roots helps you reason about them when they seem to conflict.
---
## SRP — Single Responsibility Principle
**Roots.** David L. Parnas, "On the Criteria To Be Used in Decomposing Systems into Modules" (CACM 15:12, December 1972): "begin decomposition with a list of difficult design decisions or design decisions *which are likely to change*. Each module is designed to hide such a decision from the others." Edsger Dijkstra's 1974 paper "On the role of scientific thought" coined **Separation of Concerns**. Larry Constantine, Tom DeMarco, and Meilir Page-Jones formalized **cohesion** as "functional relatedness" through the 1970s and 1980s. Uncle Bob consolidated these into "SRP" in the late 1990s (he suspects he borrowed the name from Bertrand Meyer).
**The definition has evolved three times:**
1. *Early:* "A module should do one thing, do it well, and do it only."
2. *Clean Code era (2008):* "A class should have one, and only one, reason to change."
3. *Clean Architecture (2017):* "A module should be responsible to one, and only one, **actor**." An actor is a person or a tightly coupled group representing a single narrowly defined business function.
The actor formulation is the current canonical one. Uncle Bob gave this example (2014): "SRP is about people. When you write a software module, you want to make sure that when changes are requested, those changes can only originate from a single person, or rather, a single tightly coupled group of people representing a single narrowly defined business function. Why? Because we don't want to get the COO fired because we made a change requested by the CTO."
**What this means in practice:**
- Business rules do not live in GUI code.
- SQL queries do not live next to communication protocols.
- A module modified because of a change in report format should not also be modified because of a change in tax law — those are different actors.
- Microservices do not solve SRP. A tangled microservice is still tangled; a tangled set of microservices is worse than a tangled monolith because the tangles cross network boundaries.
**Smells that suggest SRP violation:**
- The class keeps getting edited by different people for different reasons.
- Changing one feature breaks tests for an unrelated feature.
- The class name contains "and," "manager," "util," or "helper."
---
## OCP — Open-Closed Principle
**Roots.** Bertrand Meyer, *Object-Oriented Software Construction* (1988). Meyer's original formulation used **implementation inheritance**: "A class is closed, since it may be compiled, stored in a library, baselined, and used by client classes. But it is also open, since any new class may use it as parent, adding new features."
In the 1990s the principle was **reinterpreted polymorphically** (largely by Uncle Bob's writing): use abstracted interfaces with multiple implementations, not base-class inheritance. This is the dominant modern reading.
**Definition (modern):** "A module should be open for extension but closed for modification." Or: "You should be able to extend the behavior of a system without having to modify that system."
**In practice:**
- Imagine writing a system where writing to disk, printer, screen, or network pipe were scattered as `if` cases throughout business logic. That is the OCP failure mode — and why operating systems invented device independence.
- New payment methods plug in without modifying the checkout flow. New report formats plug in without modifying the report generator.
- **Plugin architectures are the apotheosis of OCP.** Eclipse, IntelliJ, VS Code, Vim, Minecraft — all extend without modifying.
**Simple code is both open and closed.** Complexity in this dimension comes from *missing* abstractions, not extra ones. Do not over-abstract speculatively.
---
## LSP — Liskov Substitution Principle
**Roots.** Barbara Liskov's 1987 keynote "Data abstraction and hierarchy" at OOPSLA, later formalized with Jeannette Wing (1994). Liskov's own framing is mathematical: about subtypes that preserve the behavior their supertype's clients expect.
**A common misread:** LSP is about inheritance. It is not — it is about **subtyping**. Subtyping includes:
- Interface implementations.
- Trait/protocol implementations.
- Duck types that satisfy an implicit interface.
- Any context where "type B can be used where type A is expected."
**Canonical definition (Uncle Bob):** "A program that uses an interface must not be confused by an implementation of that interface."
**In practice:**
- The classic Square-from-Rectangle example: Square cannot be substituted for Rectangle without surprising callers who expect to vary width and height independently.
- Keep subtype contracts crisp. Document invariants, preconditions, postconditions (Meyer's Design by Contract from *OOSC*).
- If a subtype needs to refuse operations the base type promised, the hierarchy is wrong.
- An abstraction that leaks its concretions breaks LSP.
Michael Feathers noted (2006) that in dynamic languages LSP applies just as strongly — it is about substitutability, not inheritance. Duck typing gives you substitutability; LSP is what ensures substituted objects behave sensibly.
---
## ISP — Interface Segregation Principle
**Definition:** "Keep interfaces small so that clients don't end up depending on things they don't need."
ISP matters most where compile-time or link-time coupling exists — which is still most of the industry. In statically typed languages (Rust, Java, Go, C#, C++, Swift, TypeScript with strict mode), when module A depends on module B at compile time but only uses one method, a change to an unrelated method in B still triggers recompilation and redeployment of A.
Dynamically typed languages are not immune — package managers (npm, Maven, Cargo, pip) impose coupling through version resolution.
**In practice:**
- Prefer many small, role-focused interfaces over one fat interface.
- Split a class with two unrelated interfaces into two classes (often aligns with SRP).
- In Rust, favor small focused traits over giant trait blobs.
---
## DIP — Dependency Inversion Principle
**Definition:** "Depend in the direction of abstraction. High-level modules should not depend on low-level details; both should depend on abstractions."
This is the single most important architectural principle. Computations that produce business value must not depend on:
- SQL dialects.
- HTTP framework types.
- File formats.
- UI widget libraries.
- Vendor SDKs.
**The mechanic (from "OO vs FP", 2014):** In most software systems when one function calls another, the runtime dependency and the source-code dependency point the same direction. When polymorphism is injected between them, an **inversion of the source-code dependency** occurs. The calling module still depends on the called module at runtime, but the source of the calling module depends only on a polymorphic interface — not on the source of the called module. The called module becomes a plugin.
**In practice:**
- Define interfaces in terms of what the domain needs, not what the infrastructure provides.
- Place those interfaces in the high-level module; place implementations in the low-level module.
- Wire them together in a single composition root (the Main component).
- "To be robust, a system must employ polymorphism across significant architectural boundaries."
DIP is the mechanism that makes Clean Architecture's Dependency Rule enforceable. See [architecture.md](architecture.md).
---
## Component Principles
Once modules are organized, they group into **components** — independently deployable units (libraries, services, jars, crates). Two sets of principles govern them.
### Component Cohesion — what belongs together
- **REP — Reuse/Release Equivalence Principle.** The unit of reuse is the unit of release. Things reused together must be released together, with version numbers.
- **CCP — Common Closure Principle.** Group together classes that change for the same reasons at the same times. (SRP at component scale.)
- **CRP — Common Reuse Principle.** Classes that are used together belong together; classes that are not used together do not belong together. (ISP at component scale.)
**The tension diagram.** These three principles pull in different directions — REP and CCP tend to include more; CRP tends to exclude. Designing components is an ongoing balance within the triangle they form. Where you place a component in this triangle depends on maturity: early-stage components lean toward REP+CCP (include-more); mature, widely-reused components shift toward CRP (exclude).
### Component Coupling — how they relate
- **ADP — Acyclic Dependencies Principle.** The dependency graph among components must have no cycles. Break cycles with DIP or by extracting a new component both sides depend on.
- **SDP — Stable Dependencies Principle.** Depend in the direction of stability. Volatile components may depend on stable ones, never the reverse.
- **SAP — Stable Abstractions Principle.** Stable components should be abstract, so they can be extended. Volatile components should be concrete. Corollary: depend on stable abstractions.
---
## Applying SOLID in Practice
- **Do not apply all five at once on day one.** Let the code tell you which principle is being violated. Pain surfaces one at a time.
- **Duplication and rigidity are the strongest signals.** If you cannot change one thing without changing ten, some SOLID principle is being violated — usually SRP or DIP.
- **Beware of over-abstraction.** SOLID is about *managing* dependencies, not maximizing interfaces. A speculative interface with one implementation is YAGNI until a second implementation appears or tests demand it.
- **Uncle Bob's synthesis (2020):** Simple code is both open and closed. Simple code maintains crisp subtype relationships. Simple code depends on abstractions. The principles describe what simple code looks like when it survives contact with change.
+177
View File
@@ -0,0 +1,177 @@
# Test Driven Development
When to load this reference: when writing new tests, reviewing tests, debugging brittle tests, dealing with legacy code that resists testing, or deciding on a testing strategy for a module.
Tests are the safety net that makes fearless refactoring possible. Without that net, every change is a gamble; with it, every change can be confident. Tests are also the most precise, executable documentation a system will ever have.
**Michael Feathers's definition of legacy code:** *Legacy code is code without tests.* Uncle Bob adopted this definition and it underpins the TDD practice.
---
## The Three Laws of TDD
1. **You are not allowed to write any production code unless it is to make a failing unit test pass.**
2. **You are not allowed to write any more of a unit test than is sufficient to fail — and compilation failures are failures.**
3. **You are not allowed to write any more production code than is sufficient to pass the one failing unit test.**
The loop is measured in seconds, not minutes. Write a line or two of test, see it fail, write a line or two of production, see it pass, repeat. This is the **nano-cycle**.
**Why these rules:**
- **Debugging time plummets** — you were never more than 60 seconds away from working code.
- **Tests are automatic documentation** that cannot fall out of sync with the system.
- **Design improves** because code written to be testable is naturally decoupled.
- **Refactoring becomes fearless** because the net catches regressions instantly.
This is double-entry bookkeeping for software. Every behavior is stated twice — once in the test, once in the code — and they must agree.
---
## F.I.R.S.T. — Clean Tests
Clean tests are:
- **Fast.** Slow tests will stop being run. If a suite takes 10 minutes, people will commit without running it. 15-minute CI feedback is too slow for the TDD loop.
- **Independent.** No test depends on another. Any test can run alone, in any order.
- **Repeatable.** Same result in every environment — laptop, CI, staging. If a test depends on the network, wall clock, or shared database, it is flaky and must be fixed.
- **Self-validating.** Pass or fail. No manual inspection.
- **Timely.** Written *just before* the production code they cover — not "when we have time."
Test code is first-class. Hold it to the same clarity bar as production code. When tests rot, production code rots.
---
## Canonical Test Definitions (First-Class Tests, 2017)
The industry has been sloppy about what "unit," "integration," "acceptance," etc. mean. Uncle Bob's proposed taxonomy:
- **Unit Test.** Written by a programmer, for a programmer. Ensures production code does what the programmer expected. Sometimes called **programmer test** or **micro-test**.
- **Acceptance Test.** Written by the business (or a BA/QA representing the business). Ensures production code does what the business expects. Sometimes called **customer test**.
- **Integration Test.** Written by architects or technical leads. Ensures a sub-assembly of system components operates correctly. **These are plumbing tests, not business-rule tests** — rules are already verified by unit and acceptance tests.
- **System Test.** An integration test for the whole integrated system.
- **Micro-test** (Mike Hill / @GeePawHill). A unit test at very small scope — tests a single function or small group.
- **Functional Test.** A unit test at larger scope, with mocks for slow components.
> "Integration tests do not test business rules. Those rules have already been tested, once by programmer (unit) tests, and again by customer (acceptance) tests. Integration tests test the plumbing and choreography of the components." — Uncle Bob (Twitter, 2019)
**Implication for Claude when writing tests:** Know which kind of test you are writing and don't couple it to the wrong kind. If you're asked to "add tests" for a pure function, write unit/micro tests. If you're asked to "test the API works end-to-end," that's integration/system. Don't test business rules in an integration test — the rules should already have unit tests.
---
## Test Structure
Use one of these structures; be consistent.
- **Arrange / Act / Assert** — set up context, perform action, check result.
- **Given / When / Then** — same thing in BDD vocabulary.
- **Build / Operate / Check** — same thing, different vocabulary.
One *concept* per test. Often one assertion, but "one concept" is the real rule — several assertions verifying the same behavior are fine.
### Test Naming
Name the test for what it verifies about behavior, not for the method. `returns_empty_list_when_given_empty_input` beats `test_filter_1`. If the name runs long, the test is probably doing more than one thing.
---
## Test Doubles — The Hierarchy
Adapted from Gerard Meszaros's *xUnit Patterns*, with Uncle Bob's gloss. Each is a degree of sophistication above the last.
- **Dummy.** Passed around but never used. Fills a parameter slot.
- **Stub.** Returns canned answers. No logic.
- **Spy.** A stub that records the calls it received.
- **Mock.** A spy with expectations built in: set up *before* the act, verified *after*. Fails if expected interactions didn't happen.
- **Fake.** A working implementation with production-unfit shortcuts — e.g., in-memory repo that stands in for a real database.
Pick the lowest-sophistication double that does the job. A mock where a stub would suffice adds coupling and fragility.
**Uncle Bob hand-rolls most of his Java mocks** ("Manual Mocking," 2009) rather than using mockito, to keep explicit control over ceremony. This is a taste preference, not a rule, but his reasoning (less magic, clearer test code) is worth knowing.
---
## Chicago vs. London (State-ism vs. Mockism)
Two schools of TDD.
- **Chicago / Classical / State-ist.** Test behavior through state. Exercise the object, assert on its final state (or collaborators' state). Minimal mocking. Less coupled to implementation detail.
- **London / Mockist.** Test behavior through interactions. Mock collaborators; assert on calls. More explicit about collaboration but more coupled to it.
**Practical guidance:** Use Chicago for value objects, algorithms, internal logic. Use London at **boundaries** — where the code coordinates external collaborators. Never mock what you own when you could exercise it directly; mock (or fake) what you do not own when the real thing would make the test slow or flaky.
---
## Fragile Tests
Tests that break without a real regression are worse than no tests — they train developers to ignore the suite. Known causes:
- **Interface sensitivity.** Tests break because a signature changed, not behavior. Often a sign of excessive mocking.
- **Behavior sensitivity.** Tests break because an unrelated behavior changed. A sign of poor isolation.
- **Data sensitivity.** Tests break because shared fixtures changed. Fix by making tests own their data.
- **Context sensitivity.** Tests pass locally, fail in CI. Remove environmental coupling: clock, network, filesystem, time zone.
- **Over-specification.** Tests assert on more than the behavior under test — internal call order, private fields, log output. Assert on what the *user of the code* would observe.
A fragile test is a design signal — usually a missing abstraction, a leaky boundary, or an over-eager mock.
"Skilled TDDers understand that neither micro-tests, nor functional tests, nor acceptance tests should be coupled to the implementation of the system." — *First-Class Tests* (2017)
---
## As Tests Get More Specific, Code Gets More Generic
Uncle Bob's formulation (2009): tests are specifications. As you add tests, the specifications grow more specific. To satisfy them all, the production code must grow more *generic*. This is the inverse relationship that drives TDD-induced good design — the code gets pushed toward abstractions that cover many cases rather than one.
---
## The Transformation Priority Premise (TPP)
When making a failing test pass, there is a natural ordering of changes, simpler before more complex. Prefer earlier transformations when more than one would work:
1. `{} → nil` — no code → returning nil
2. `nil → constant` — return a constant
3. `constant → variable` — replace constant with a variable
4. `statement → statements` — add another statement
5. `unconditional → if` — introduce a branch
6. `scalar → array` — move from a single value to a collection
7. `array → container` — move to a richer collection type
8. `statement → recursion` — replace a statement with recursion
9. `if → while` — replace a branch with iteration
10. `expression → function` — extract a function
11. `variable → assignment` — introduce mutation
Using lower-priority transformations earlier creates needless complexity; using higher-priority ones later often indicates a design that could be simpler. TPP is a tiebreaker, not a law — but it usually guides tests toward algorithms that generalize cleanly.
---
## The Cycles of TDD
TDD operates at multiple time scales simultaneously. Working at only one scale produces bad software.
- **Seconds (Red-Green-Refactor).** The nano-cycle.
- **Minutes (Specific-to-Generic).** Tests grow more specific; code grows more generic.
- **Tens of minutes (Boundary).** Periodically step back and ask whether the module is still well-factored. Extract. Rename. Regroup.
- **Hours (Architecture).** Once a day or so, step back further: are the component boundaries still correct? Does the Dependency Rule still hold?
- **Days (Acceptance).** Acceptance tests (at the feature/use-case level) close the loop with the business.
Skipping the larger cycles is the most common failure mode. Red-Green-Refactor religiously, but never step back to reconsider architecture, and you end up with a suite of fine-grained tests wrapped around a tangled ball of mud.
---
## Testing Across Architectural Boundaries
- **The test boundary** is a first-class part of architecture. Tests live outside the system they test.
- **Do not couple tests to UI frameworks or databases.** If a test needs a browser to exercise a use case, the boundary between use case and UI is broken.
- **Legacy code strategy** (Feathers). Find a seam — a place where behavior can be varied without modifying code. Write a characterization test at that seam to pin down current behavior. Refactor behind the pin. Repeat.
Uncle Bob's position on test placement: "Don't test through UIs. Don't test through web servers. Test as close to the code as you can." — *Testing Like the TSA* (2017)
---
## Common Pitfalls
- **Writing tests after the fact.** Produces tests that confirm whatever the code happens to do, including the bugs. Much lower value than TDD.
- **Slow test suites.** If any unit test takes more than a fraction of a second, isolate it. Keep the unit suite fast and run integration tests separately.
- **Mocking what you own.** Prefer real objects for your own code.
- **Testing implementation details.** Refactors then break tests without any real regression, and people conclude "TDD gets in the way of refactoring." It doesn't — the tests were just wrong.
- **Skipping refactor.** Red-Green-… is not TDD. The third step is where design emerges.
- **Over-coverage religion.** Uncle Bob's ratio for some project types: 20% test-first, 80% test-after is acceptable for controllers/models/views (per *Testing Like the TSA*, 2017). The three laws are guidance for the hottest logic in the system, not dogma for every trivial accessor.
@@ -0,0 +1,449 @@
---
name: kana-rust-backend-best-practice
description: Reference guide for building a Rust clean-architecture backend with Axum, SeaORM, Argon2, JWT, and sea-orm-migration. Use when scaffolding a new Rust service, adding a feature (domain + use-case + repository + handler), or reviewing Rust code against the axum-clean-architecture reference layout.
---
# Axum Clean Architecture Skill
Reference stack (see `../axum-clean-architecture`):
| Layer | Tech |
|---|---|
| HTTP framework | Axum 0.8 |
| ORM | SeaORM 1.1 (PostgreSQL via sqlx + rustls) |
| Migrations | sea-orm-migration |
| Auth | Argon2 (password hashing) + jsonwebtoken (JWT) |
| Validation | zod-rs (schema-driven, mirrors Zod) |
| Pagination | paginator-rs + paginator-sea-orm + paginator-axum |
| Observability | tracing + tracing-subscriber |
| Middleware | tower-http (CORS, TraceLayer) |
| Runtime | Tokio (full features) |
| Error handling | anyhow (app-level), typed domain errors |
---
## 0. Workspace layout
```
axum-clean-architecture/
├── Cargo.toml # workspace, resolver = "3"
├── apps/
│ ├── iam/ # core domain library (lib crate)
│ │ └── src/
│ │ ├── domain/ # entities, repository traits, domain errors
│ │ ├── application/ # use cases + port traits
│ │ ├── infrastructure/ # SeaORM repos + auth services
│ │ └── presentation/ # Axum handlers, DTOs, middleware, state
│ ├── gateway/ # binary — assembles router, runs server
│ └── bootstrap/ # binary — seeds permissions/roles/admin
├── .config/ # AppServer, database/env helpers
└── .migrations/ # sea-orm-migration crate
```
The `iam` app is a **library crate**. `gateway` and `bootstrap` depend on it.
---
## 1. Dependency rules (strictly enforced)
```
presentation → application → domain
infrastructure → domain (implements domain traits)
presentation → infrastructure (only to wire AppState)
```
- Domain has **zero** external crate dependencies beyond `uuid`, `chrono`.
- Use cases depend only on port traits — never on concrete infrastructure types.
- Presentation instantiates use cases from `AppState` on every request; use cases are not stored.
---
## 2. Domain layer
### Entity pattern
Plain Rust structs — no derives beyond what domain logic needs. No ORM annotations.
```rust
// domain/user/entity.rs
pub struct User {
pub id: Uuid,
pub email: String,
pub password_hash: String,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
pub struct NewUser {
pub id: Uuid,
pub email: String,
pub password_hash: String,
}
#[derive(Default)]
pub struct UserPatch {
pub email: Option<String>,
pub password_hash: Option<String>,
}
```
### Repository trait pattern
Use `impl Future` in trait methods (Rust 2024 edition, no `async_trait` needed).
Always `Send + Sync` on the trait.
```rust
// domain/user/repository.rs
pub trait UserRepository: Send + Sync {
fn find_by_id(&self, id: Uuid)
-> impl Future<Output = Result<Option<User>, RepositoryError>> + Send;
fn find_by_email(&self, email: &str)
-> impl Future<Output = Result<Option<User>, RepositoryError>> + Send;
fn create(&self, user: NewUser)
-> impl Future<Output = Result<User, RepositoryError>> + Send;
fn update(&self, id: Uuid, patch: UserPatch)
-> impl Future<Output = Result<User, RepositoryError>> + Send;
fn delete(&self, id: Uuid)
-> impl Future<Output = Result<(), RepositoryError>> + Send;
fn list(&self, params: &PaginationParams)
-> impl Future<Output = Result<PaginatorResponse<User>, RepositoryError>> + Send;
}
```
### Shared RepositoryError (lives in domain)
```rust
pub enum RepositoryError {
NotFound,
Conflict(String),
Database(String),
}
```
### Domain errors
Per-aggregate. `AuthError` lives in `domain/auth/errors.rs`:
```rust
pub enum AuthError {
InvalidCredentials,
EmailAlreadyExists,
UserNotFound,
PasswordHashFailed(String),
PasswordVerificationFailed(String),
TokenGenerationFailed(String),
InvalidToken(String),
RepositoryError(String),
}
```
---
## 3. Application layer
### Port traits (interfaces for external services)
```rust
// application/auth/ports/password.rs
pub trait PasswordService: Send + Sync {
fn hash(&self, password: &str)
-> impl Future<Output = Result<String, PasswordError>> + Send;
fn verify(&self, password: &str, hash: &str)
-> impl Future<Output = Result<bool, PasswordError>> + Send;
}
```
```rust
// application/auth/ports/token.rs
pub trait TokenService: Send + Sync {
fn generate_auth_tokens(&self, sub: &str)
-> impl Future<Output = Result<(String, String), TokenError>> + Send;
fn verify_access_token(&self, token: &str)
-> Result<String, TokenError>;
}
```
### Use case pattern
Generic over port traits and repository traits. Constructed in the handler, not stored.
```rust
// application/user/use_cases/create.rs
pub struct CreateUserCommand { pub email: String, pub password: String }
pub struct CreateUserUseCase<P, R> {
password_service: P,
user_repository: R,
}
impl<P: PasswordService, R: UserRepository> CreateUserUseCase<P, R> {
pub fn new(password_service: P, user_repository: R) -> Self { ... }
pub async fn execute(&self, cmd: CreateUserCommand) -> Result<User, AuthError> {
// 1. guard: check uniqueness
// 2. hash password via port
// 3. create domain entity with Uuid::new_v4()
// 4. persist via repository
// 5. log + return
info!(user_id = %user.id, "user created");
Ok(user)
}
}
```
### Use case naming convention
| File | Struct | Command/Query |
|---|---|---|
| `create.rs` | `CreateXxxUseCase` | `CreateXxxCommand` |
| `update.rs` | `UpdateXxxUseCase` | `UpdateXxxCommand` |
| `delete.rs` | `DeleteXxxUseCase` | `DeleteXxxCommand` |
| `detail.rs` | `XxxDetailUseCase` | `XxxDetailQuery` |
| `list.rs` | `ListXxxsUseCase` | takes `&PaginationParams` |
---
## 4. Infrastructure layer
### SeaORM repository implementation
```rust
// infrastructure/repository/user.rs
#[derive(Clone)]
pub struct SeaOrmUserRepository { db: DatabaseConnection }
// Convert ORM Model → domain entity here (not in domain)
impl From<Model> for User { ... }
// Map DbErr → RepositoryError
fn map_db_err(e: DbErr) -> RepositoryError {
match e {
DbErr::RecordNotFound(_) => RepositoryError::NotFound,
other => { error!(error = %other, "database operation failed"); RepositoryError::Database(other.to_string()) }
}
}
impl UserRepository for SeaOrmUserRepository {
async fn create(&self, user: NewUser) -> Result<User, RepositoryError> {
let model = ActiveModel {
id: Set(user.id),
email: Set(user.email),
password_hash: Set(user.password_hash),
created_at: Set(now),
updated_at: Set(now),
};
let inserted = model.insert(&self.db).await.map_err(|e| match e {
DbErr::Exec(ref msg) | DbErr::Query(ref msg)
if msg.to_string().contains("unique") =>
RepositoryError::Conflict("email already exists".into()),
other => RepositoryError::Database(other.to_string()),
})?;
Ok(User::from(inserted))
}
}
```
Pagination uses `paginator-sea-orm`:
```rust
let response = UserEntity::find()
.paginate_with(&self.db, params)
.await
.map_err(|e| RepositoryError::Database(e.to_string()))?;
let mapped: Vec<User> = response.data.into_iter().map(User::from).collect();
Ok(PaginatorResponse { data: mapped, meta: response.meta })
```
### Auth services
- `Argon2PasswordService`: uses `spawn_blocking` for CPU-bound hashing, `SaltString::generate(OsRng)`.
- `JwtTokenService`: stores `secret: Vec<u8>`, generates separate access/refresh tokens with a `type` claim. `verify_access_token` checks `claims.token_type == "access"`.
### SeaORM entities (ORM models)
Live in `infrastructure/repository/entities/`. One file per table. Junction tables (`user_role`, `role_permission`) have composite primary keys. Timestamps use `DateTimeWithTimeZone`.
---
## 5. Presentation layer
### AppState
Concrete types only — no trait objects. Cheap to clone because `DatabaseConnection` is internally Arc-backed.
```rust
#[derive(Clone)]
pub struct AppState {
pub password_service: Argon2PasswordService,
pub token_service: JwtTokenService,
pub user_repository: SeaOrmUserRepository,
pub role_repository: SeaOrmRoleRepository,
pub permission_repository: SeaOrmPermissionRepository,
}
```
Injected via `Extension(state)` on every handler. Use cases are constructed inside handlers.
### AppError
```rust
pub enum AppError { BadRequest(String), Unauthorized, Forbidden, NotFound, Conflict(String), Internal(String) }
impl IntoResponse for AppError { /* maps to HTTP status + JSON { "error": "..." } */ }
impl From<AuthError> for AppError { ... }
impl From<RepositoryError> for AppError { ... }
impl From<TokenError> for AppError { ... }
```
Internal errors are logged with `tracing::error!` before returning a generic 500 message.
### Handler pattern
```rust
#[instrument(skip_all, fields(actor = %actor.id, email = %req.email))]
pub async fn create(
Extension(state): Extension<AppState>,
Extension(actor): Extension<AuthenticatedUser>,
Json(req): Json<CreateUserRequest>,
) -> Result<(StatusCode, Json<UserResponse>), AppError> {
let use_case = CreateUserUseCase::new(
state.password_service.clone(),
state.user_repository.clone(),
);
let user = use_case.execute(req.into()).await?;
Ok((StatusCode::CREATED, Json(user.into())))
}
```
Rules:
- Always `#[instrument(skip_all, fields(...))]` on every handler.
- Use `?` to propagate `AppError` (via `From` impls).
- `201 CREATED` for `POST`, `204 NO_CONTENT` for `DELETE`, `200 OK` for everything else.
- Pagination handlers return `PaginatedJson<Dto>` via `paginator-axum`.
### DTO pattern
```rust
#[derive(Debug, Serialize, Deserialize, ZodSchema)]
pub struct CreateUserRequest {
#[zod(email)]
pub email: String,
#[zod(min_length(8), max_length(128))]
pub password: String,
}
impl From<CreateUserRequest> for CreateUserCommand { ... }
#[derive(Debug, Serialize)]
pub struct UserResponse { pub id: Uuid, pub email: String, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc> }
impl From<User> for UserResponse { ... }
```
- Request structs: `Deserialize + ZodSchema`. Use `#[zod(...)]` for field-level validation.
- Response structs: `Serialize` only. Never expose `password_hash`.
- Conversions: `impl From<Request> for Command` and `impl From<DomainEntity> for Response`.
### Middleware
**Auth middleware** (`presentation/middleware/auth.rs`):
- Extracts `Bearer <token>` from `Authorization` header.
- Calls `state.token_service.verify_access_token(token)`.
- Inserts `AuthenticatedUser { id: Uuid }` into request extensions.
**Permission check** (`presentation/middleware/permission.rs`):
- Called inline from handlers: `ensure_permission(&state, &actor, "users:write").await?`.
- Queries `permission_repository.find_for_user(actor.id)` and checks by name.
### Router assembly
```rust
pub fn build_router(state: AppState) -> Router {
Router::new()
.nest("/auth", auth::router())
.nest("/me", me::router())
.nest("/users", user::router())
.nest("/roles", role::router())
.nest("/permissions", permission::router())
.layer(Extension(state))
}
```
Gateway nests the IAM router at `/api/v1/iam` and adds a health check at `/`.
---
## 6. Migrations (sea-orm-migration)
```rust
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager.create_table(
Table::create()
.table(Users::Table)
.if_not_exists()
.col(ColumnDef::new(Users::Id).uuid().not_null().primary_key())
.col(ColumnDef::new(Users::Email).string().not_null().unique_key())
...
.to_owned(),
).await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager.drop_table(Table::drop().table(Users::Table).to_owned()).await
}
}
#[derive(DeriveIden)]
pub enum Users { Table, Id, Email, PasswordHash, CreatedAt, UpdatedAt }
```
Naming convention: `m{YYYYMMDD}_{6-digit-seq}_{description}.rs`, e.g. `m20260413_000001_create_users.rs`.
---
## 7. Bootstrap pattern
A separate `bootstrap` binary seeds idempotent system data (permissions, roles, admin user):
```rust
// Check existence before inserting — fully idempotent
if permission_repo.find_by_name("rbac:manage").await?.is_none() {
permission_repo.create(...).await?;
}
```
Standard permissions:
- `rbac:manage`, `users:read`, `users:write`, `roles:read`, `roles:write`, `permissions:read`, `permissions:write`
---
## 8. Adding a new aggregate (checklist)
1. **Domain**: `domain/{name}/entity.rs` (entity + NewXxx + XxxPatch), `domain/{name}/repository.rs` (trait + errors), `domain/{name}/errors.rs` if needed.
2. **Application**: `application/{name}/mod.rs`, `application/{name}/use_cases/{create,update,delete,detail,list}.rs`.
3. **Infrastructure entity**: `infrastructure/repository/entities/{name}.rs` (SeaORM model).
4. **Infrastructure repo**: `infrastructure/repository/{name}.rs` (`From<Model>`, `impl XxxRepository for SeaOrmXxxRepository`).
5. **Add to AppState**: `{name}_repository: SeaOrmXxxRepository`.
6. **Presentation DTO**: `presentation/{name}/dto.rs` (Request + Response with `From` impls).
7. **Presentation handlers**: `presentation/{name}/handlers.rs` (`#[instrument]`, construct use case, return DTO).
8. **Presentation router**: `presentation/{name}/mod.rs` (define routes with `axum_route_macro` or `Router::new().route(...)`).
9. **Nest in `build_router`**.
10. **Migration**: new file in `.migrations/src/` following naming convention.
11. **Bootstrap**: seed any required initial data.
---
## 9. Key conventions
- Edition **2024** — use `impl Future` in traits, not `#[async_trait]`.
- All timestamps are `DateTime<Utc>` in domain; `DateTimeWithTimeZone` in SeaORM models; convert with `.with_timezone(&Utc)`.
- UUIDs generated with `Uuid::new_v4()` in the use case, not the repository.
- Unique-constraint conflicts detected via string match on `DbErr::Exec`/`DbErr::Query` containing `"unique"` — map to `RepositoryError::Conflict`.
- `tracing::instrument` on every handler; log user/actor IDs as structured fields.
- `warn!` for expected failures (wrong password, permission denied), `error!` for unexpected DB errors.
- Response structs never expose internal fields (`password_hash`, internal IDs from junction tables).
@@ -0,0 +1,107 @@
---
name: push-flow-convention
description: Enforce pre-commit/pre-push hooks, lint-staged checks, and semver version bump on every push
---
# Push Flow Convention
Every repository MUST enforce the same pre-commit, pre-push, and versioning flow. No push lands without hooks, lint-staged, and a version bump.
## Required Setup
### 1. Lefthook (pre-commit + pre-push)
> **Always use [Lefthook](https://lefthook.dev/) for git hooks. Never use husky.**
Install once per repo:
```bash
pnpm add -D lefthook lint-staged
pnpm exec lefthook install
```
Create `lefthook.yml` in project root:
```yaml
pre-commit:
commands:
lint-staged:
run: pnpm exec lint-staged
pre-push:
commands:
lint-staged:
run: pnpm exec lint-staged --diff="origin/{push_remote_branch}...HEAD"
bump:
run: pnpm run bump
```
### 2. lint-staged
Declared in `package.json`. Runs ONLY on staged files so commits stay fast.
```json
{
"lint-staged": {
"*.{ts,tsx,js,jsx}": [
"eslint --fix",
"prettier --write"
],
"*.{json,md,yml,yaml}": [
"prettier --write"
]
}
}
```
### 3. Version bump script
`package.json` MUST expose a `bump` script used by `pre-push`:
```json
{
"scripts": {
"bump": "node scripts/bump-version.mjs"
}
}
```
The script inspects the diff between the current branch and its upstream, applies the semver rule below, and writes the new version back to `package.json`. Commit the bump before pushing (amend the previous commit or create a `chore: adjust package.json version (bump)` commit — see `commit-convention`).
## Semver Rules (applied on every push)
The bump is based on the changes in the commits being pushed:
| Change size / kind | Bump |
|--------------------|------|
| `< 5` changed files across pushed commits | **patch** (`x.y.Z`) |
| `>= 5` changed files across pushed commits | **minor** (`x.Y.0`) |
| New feature OR new behaviour (any `feat:` commit) | **major** (`X.0.0`) |
Rules in order of precedence:
1. If ANY commit being pushed is a `feat(...)`**major** bump.
2. Otherwise, count files changed (`git diff --name-only origin/<branch>...HEAD | wc -l`):
- fewer than 5 → **patch**
- 5 or more → **minor**
The `feat` rule always wins — a new feature is always a major bump regardless of file count.
## Non-negotiables
1. NEVER push without pre-commit and pre-push hooks installed.
2. NEVER bypass hooks with `--no-verify` — if a hook fails, fix the root cause.
3. NEVER push without a version bump. Every push = new version.
4. The bump commit MUST use the `chore: adjust package.json version (bump)` message (see `commit-convention`).
5. lint-staged MUST run on every commit. A green lint-staged is a prerequisite for the commit to be created.
6. If `pnpm` is not the package manager, substitute with `npm` or `yarn` but keep the same flow.
## Quick verification checklist
Before declaring the push flow set up, confirm:
- [ ] `lefthook.yml` exists with `pre-commit` and `pre-push` hooks
- [ ] `pnpm exec lefthook install` has been run (hooks registered in `.git/hooks/`)
- [ ] `package.json` has a `lint-staged` block
- [ ] `package.json` has a `bump` script
- [ ] A dry-run commit triggers lint-staged
- [ ] A dry-run push triggers the version bump